code
stringlengths
2
1.05M
/* Highcharts JS v8.2.2 (2020-10-22) (c) 2016-2019 Highsoft AS Authors: Jon Arild Nygard License: www.highcharts.com/license */ (function(b){"object"===typeof module&&module.exports?(b["default"]=b,module.exports=b):"function"===typeof define&&define.amd?define("highcharts/modules/sunburst",["highcharts"],function(q){b(q);b.Highcharts=q;return b}):b("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(b){function q(b,d,p,D){b.hasOwnProperty(d)||(b[d]=D.apply(null,p))}b=b?b._modules:{};q(b,"Mixins/DrawPoint.js",[],function(){var b=function(b){return"function"===typeof b},d=function(p){var d,u=this,l=u.graphic,w=p.animatableAttribs, A=p.onComplete,g=p.css,k=p.renderer,V=null===(d=u.series)||void 0===d?void 0:d.options.animation;if(u.shouldDraw())l||(u.graphic=l=k[p.shapeType](p.shapeArgs).add(p.group)),l.css(g).attr(p.attribs).animate(w,p.isNew?!1:V,A);else if(l){var H=function(){u.graphic=l=l.destroy();b(A)&&A()};Object.keys(w).length?l.animate(w,void 0,function(){H()}):H()}};return{draw:d,drawPoint:function(b){(b.attribs=b.attribs||{})["class"]=this.getClassName();d.call(this,b)},isFn:b}});q(b,"Mixins/TreeSeries.js",[b["Core/Color/Color.js"], b["Core/Utilities.js"]],function(b,d){var p=d.extend,D=d.isArray,u=d.isNumber,l=d.isObject,w=d.merge,A=d.pick;return{getColor:function(g,k){var l=k.index,d=k.mapOptionsToLevel,p=k.parentColor,u=k.parentColorIndex,K=k.series,C=k.colors,I=k.siblings,r=K.points,w=K.chart.options.chart,B;if(g){r=r[g.i];g=d[g.level]||{};if(d=r&&g.colorByPoint){var D=r.index%(C?C.length:w.colorCount);var L=C&&C[D]}if(!K.chart.styledMode){C=r&&r.options.color;w=g&&g.color;if(B=p)B=(B=g&&g.colorVariation)&&"brightness"=== B.key?b.parse(p).brighten(l/I*B.to).get():p;B=A(C,w,L,B,K.color)}var q=A(r&&r.options.colorIndex,g&&g.colorIndex,D,u,k.colorIndex)}return{color:B,colorIndex:q}},getLevelOptions:function(b){var k=null;if(l(b)){k={};var d=u(b.from)?b.from:1;var g=b.levels;var A={};var q=l(b.defaults)?b.defaults:{};D(g)&&(A=g.reduce(function(b,k){if(l(k)&&u(k.level)){var g=w({},k);var r="boolean"===typeof g.levelIsConstant?g.levelIsConstant:q.levelIsConstant;delete g.levelIsConstant;delete g.level;k=k.level+(r?0:d-1); l(b[k])?p(b[k],g):b[k]=g}return b},{}));g=u(b.to)?b.to:1;for(b=0;b<=g;b++)k[b]=w({},q,l(A[b])?A[b]:{})}return k},setTreeValues:function H(b,d){var k=d.before,l=d.idRoot,u=d.mapIdToNode[l],C=d.points[b.i],w=C&&C.options||{},r=0,q=[];p(b,{levelDynamic:b.level-(("boolean"===typeof d.levelIsConstant?d.levelIsConstant:1)?0:u.level),name:A(C&&C.name,""),visible:l===b.id||("boolean"===typeof d.visible?d.visible:!1)});"function"===typeof k&&(b=k(b,d));b.children.forEach(function(k,l){var u=p({},d);p(u,{index:l, siblings:b.children.length,visible:b.visible});k=H(k,u);q.push(k);k.visible&&(r+=k.val)});b.visible=0<r||b.visible;k=A(w.value,r);p(b,{children:q,childrenTotal:r,isLeaf:b.visible&&!r,val:k});return b},updateRootId:function(b){if(l(b)){var d=l(b.options)?b.options:{};d=A(b.rootNode,d.rootId,"");l(b.userOptions)&&(b.userOptions.rootId=d);b.rootNode=d}return d}}});q(b,"Mixins/ColorMapSeries.js",[b["Core/Globals.js"],b["Core/Series/Point.js"],b["Core/Utilities.js"]],function(b,d,p){var q=p.defined;return{colorMapPointMixin:{dataLabelOnNull:!0, isValid:function(){return null!==this.value&&Infinity!==this.value&&-Infinity!==this.value},setState:function(b){d.prototype.setState.call(this,b);this.graphic&&this.graphic.attr({zIndex:"hover"===b?1:0})}},colorMapSeriesMixin:{pointArrayMap:["value"],axisTypes:["xAxis","yAxis","colorAxis"],trackerGroups:["group","markerGroup","dataLabelsGroup"],getSymbol:b.noop,parallelArrays:["x","y","value"],colorKey:"value",pointAttribs:b.seriesTypes.column.prototype.pointAttribs,colorAttribs:function(b){var d= {};q(b.color)&&(d[this.colorProp||"fill"]=b.color);return d}}}});q(b,"Series/TreemapSeries.js",[b["Core/Series/Series.js"],b["Core/Color/Color.js"],b["Mixins/ColorMapSeries.js"],b["Mixins/DrawPoint.js"],b["Core/Globals.js"],b["Mixins/LegendSymbol.js"],b["Core/Series/Point.js"],b["Mixins/TreeSeries.js"],b["Core/Utilities.js"]],function(b,d,p,q,u,l,w,A,g){var k=b.seriesTypes,D=d.parse,H=p.colorMapSeriesMixin;d=u.noop;var Q=A.getColor,N=A.getLevelOptions,K=A.updateRootId,C=g.addEvent,I=g.correctFloat, r=g.defined,R=g.error,B=g.extend,S=g.fireEvent,L=g.isArray,O=g.isNumber,P=g.isObject,M=g.isString,J=g.merge,T=g.objectEach,f=g.pick,h=g.stableSort,t=u.Series,y=function(a,c,e){e=e||this;T(a,function(b,m){c.call(e,b,m,a)})},E=function(a,c,e){e=e||this;a=c.call(e,a);!1!==a&&E(a,c,e)},n=!1;b.seriesType("treemap","scatter",{allowTraversingTree:!1,animationLimit:250,showInLegend:!1,marker:void 0,colorByPoint:!1,dataLabels:{defer:!1,enabled:!0,formatter:function(){var a=this&&this.point?this.point:{};return M(a.name)? a.name:""},inside:!0,verticalAlign:"middle"},tooltip:{headerFormat:"",pointFormat:"<b>{point.name}</b>: {point.value}<br/>"},ignoreHiddenPoint:!0,layoutAlgorithm:"sliceAndDice",layoutStartingDirection:"vertical",alternateStartingDirection:!1,levelIsConstant:!0,drillUpButton:{position:{align:"right",x:-10,y:10}},traverseUpButton:{position:{align:"right",x:-10,y:10}},borderColor:"#e6e6e6",borderWidth:1,colorKey:"colorValue",opacity:.15,states:{hover:{borderColor:"#999999",brightness:k.heatmap?0:.1, halo:!1,opacity:.75,shadow:!1}}},{pointArrayMap:["value"],directTouch:!0,optionalAxis:"colorAxis",getSymbol:d,parallelArrays:["x","y","value","colorValue"],colorKey:"colorValue",trackerGroups:["group","dataLabelsGroup"],getListOfParents:function(a,c){a=L(a)?a:[];var e=L(c)?c:[];c=a.reduce(function(a,c,e){c=f(c.parent,"");"undefined"===typeof a[c]&&(a[c]=[]);a[c].push(e);return a},{"":[]});y(c,function(a,c,b){""!==c&&-1===e.indexOf(c)&&(a.forEach(function(a){b[""].push(a)}),delete b[c])});return c}, getTree:function(){var a=this.data.map(function(a){return a.id});a=this.getListOfParents(this.data,a);this.nodeMap={};return this.buildNode("",-1,0,a)},hasData:function(){return!!this.processedXData.length},init:function(a,c){H&&(this.colorAttribs=H.colorAttribs);var e=C(this,"setOptions",function(a){a=a.userOptions;r(a.allowDrillToNode)&&!r(a.allowTraversingTree)&&(a.allowTraversingTree=a.allowDrillToNode,delete a.allowDrillToNode);r(a.drillUpButton)&&!r(a.traverseUpButton)&&(a.traverseUpButton= a.drillUpButton,delete a.drillUpButton)});t.prototype.init.call(this,a,c);delete this.opacity;this.eventsToUnbind.push(e);this.options.allowTraversingTree&&this.eventsToUnbind.push(C(this,"click",this.onClickDrillToNode))},buildNode:function(a,c,e,b,m){var f=this,x=[],h=f.points[c],d=0,F;(b[a]||[]).forEach(function(c){F=f.buildNode(f.points[c].id,c,e+1,b,a);d=Math.max(F.height+1,d);x.push(F)});c={id:a,i:c,children:x,height:d,level:e,parent:m,visible:!1};f.nodeMap[c.id]=c;h&&(h.node=c);return c},setTreeValues:function(a){var c= this,e=c.options,b=c.nodeMap[c.rootNode];e="boolean"===typeof e.levelIsConstant?e.levelIsConstant:!0;var m=0,U=[],v=c.points[a.i];a.children.forEach(function(a){a=c.setTreeValues(a);U.push(a);a.ignore||(m+=a.val)});h(U,function(a,c){return(a.sortIndex||0)-(c.sortIndex||0)});var d=f(v&&v.options.value,m);v&&(v.value=d);B(a,{children:U,childrenTotal:m,ignore:!(f(v&&v.visible,!0)&&0<d),isLeaf:a.visible&&!m,levelDynamic:a.level-(e?0:b.level),name:f(v&&v.name,""),sortIndex:f(v&&v.sortIndex,-d),val:d}); return a},calculateChildrenAreas:function(a,c){var e=this,b=e.options,m=e.mapOptionsToLevel[a.level+1],d=f(e[m&&m.layoutAlgorithm]&&m.layoutAlgorithm,b.layoutAlgorithm),v=b.alternateStartingDirection,h=[];a=a.children.filter(function(a){return!a.ignore});m&&m.layoutStartingDirection&&(c.direction="vertical"===m.layoutStartingDirection?0:1);h=e[d](c,a);a.forEach(function(a,b){b=h[b];a.values=J(b,{val:a.childrenTotal,direction:v?1-c.direction:c.direction});a.pointValues=J(b,{x:b.x/e.axisRatio,y:100- b.y-b.height,width:b.width/e.axisRatio});a.children.length&&e.calculateChildrenAreas(a,a.values)})},setPointValues:function(){var a=this,c=a.xAxis,e=a.yAxis,b=a.chart.styledMode;a.points.forEach(function(f){var m=f.node,x=m.pointValues;m=m.visible;if(x&&m){m=x.height;var d=x.width,h=x.x,t=x.y,n=b?0:(a.pointAttribs(f)["stroke-width"]||0)%2/2;x=Math.round(c.toPixels(h,!0))-n;d=Math.round(c.toPixels(h+d,!0))-n;h=Math.round(e.toPixels(t,!0))-n;m=Math.round(e.toPixels(t+m,!0))-n;f.shapeArgs={x:Math.min(x, d),y:Math.min(h,m),width:Math.abs(d-x),height:Math.abs(m-h)};f.plotX=f.shapeArgs.x+f.shapeArgs.width/2;f.plotY=f.shapeArgs.y+f.shapeArgs.height/2}else delete f.plotX,delete f.plotY})},setColorRecursive:function(a,c,e,b,f){var m=this,x=m&&m.chart;x=x&&x.options&&x.options.colors;if(a){var d=Q(a,{colors:x,index:b,mapOptionsToLevel:m.mapOptionsToLevel,parentColor:c,parentColorIndex:e,series:m,siblings:f});if(c=m.points[a.i])c.color=d.color,c.colorIndex=d.colorIndex;(a.children||[]).forEach(function(c, e){m.setColorRecursive(c,d.color,d.colorIndex,e,a.children.length)})}},algorithmGroup:function(a,c,e,b){this.height=a;this.width=c;this.plot=b;this.startDirection=this.direction=e;this.lH=this.nH=this.lW=this.nW=this.total=0;this.elArr=[];this.lP={total:0,lH:0,nH:0,lW:0,nW:0,nR:0,lR:0,aspectRatio:function(a,c){return Math.max(a/c,c/a)}};this.addElement=function(a){this.lP.total=this.elArr[this.elArr.length-1];this.total+=a;0===this.direction?(this.lW=this.nW,this.lP.lH=this.lP.total/this.lW,this.lP.lR= this.lP.aspectRatio(this.lW,this.lP.lH),this.nW=this.total/this.height,this.lP.nH=this.lP.total/this.nW,this.lP.nR=this.lP.aspectRatio(this.nW,this.lP.nH)):(this.lH=this.nH,this.lP.lW=this.lP.total/this.lH,this.lP.lR=this.lP.aspectRatio(this.lP.lW,this.lH),this.nH=this.total/this.width,this.lP.nW=this.lP.total/this.nH,this.lP.nR=this.lP.aspectRatio(this.lP.nW,this.nH));this.elArr.push(a)};this.reset=function(){this.lW=this.nW=0;this.elArr=[];this.total=0}},algorithmCalcPoints:function(a,c,e,b){var f, x,d,h,t=e.lW,n=e.lH,g=e.plot,k=0,y=e.elArr.length-1;if(c)t=e.nW,n=e.nH;else var G=e.elArr[e.elArr.length-1];e.elArr.forEach(function(a){if(c||k<y)0===e.direction?(f=g.x,x=g.y,d=t,h=a/d):(f=g.x,x=g.y,h=n,d=a/h),b.push({x:f,y:x,width:d,height:I(h)}),0===e.direction?g.y+=h:g.x+=d;k+=1});e.reset();0===e.direction?e.width-=t:e.height-=n;g.y=g.parent.y+(g.parent.height-e.height);g.x=g.parent.x+(g.parent.width-e.width);a&&(e.direction=1-e.direction);c||e.addElement(G)},algorithmLowAspectRatio:function(a, c,e){var b=[],f=this,d,h={x:c.x,y:c.y,parent:c},t=0,g=e.length-1,n=new this.algorithmGroup(c.height,c.width,c.direction,h);e.forEach(function(e){d=e.val/c.val*c.height*c.width;n.addElement(d);n.lP.nR>n.lP.lR&&f.algorithmCalcPoints(a,!1,n,b,h);t===g&&f.algorithmCalcPoints(a,!0,n,b,h);t+=1});return b},algorithmFill:function(a,c,e){var b=[],f,d=c.direction,h=c.x,t=c.y,n=c.width,g=c.height,k,y,l,G;e.forEach(function(e){f=e.val/c.val*c.height*c.width;k=h;y=t;0===d?(G=g,l=f/G,n-=l,h+=l):(l=n,G=f/l,g-=G, t+=G);b.push({x:k,y:y,width:l,height:G});a&&(d=1-d)});return b},strip:function(a,c){return this.algorithmLowAspectRatio(!1,a,c)},squarified:function(a,c){return this.algorithmLowAspectRatio(!0,a,c)},sliceAndDice:function(a,c){return this.algorithmFill(!0,a,c)},stripes:function(a,c){return this.algorithmFill(!1,a,c)},translate:function(){var a=this,c=a.options,e=K(a);t.prototype.translate.call(a);var b=a.tree=a.getTree();var f=a.nodeMap[e];a.renderTraverseUpButton(e);a.mapOptionsToLevel=N({from:f.level+ 1,levels:c.levels,to:b.height,defaults:{levelIsConstant:a.options.levelIsConstant,colorByPoint:c.colorByPoint}});""===e||f&&f.children.length||(a.setRootNode("",!1),e=a.rootNode,f=a.nodeMap[e]);E(a.nodeMap[a.rootNode],function(c){var e=!1,b=c.parent;c.visible=!0;if(b||""===b)e=a.nodeMap[b];return e});E(a.nodeMap[a.rootNode].children,function(a){var c=!1;a.forEach(function(a){a.visible=!0;a.children.length&&(c=(c||[]).concat(a.children))});return c});a.setTreeValues(b);a.axisRatio=a.xAxis.len/a.yAxis.len; a.nodeMap[""].pointValues=e={x:0,y:0,width:100,height:100};a.nodeMap[""].values=e=J(e,{width:e.width*a.axisRatio,direction:"vertical"===c.layoutStartingDirection?0:1,val:b.val});a.calculateChildrenAreas(b,e);a.colorAxis||c.colorByPoint||a.setColorRecursive(a.tree);c.allowTraversingTree&&(c=f.pointValues,a.xAxis.setExtremes(c.x,c.x+c.width,!1),a.yAxis.setExtremes(c.y,c.y+c.height,!1),a.xAxis.setScale(),a.yAxis.setScale());a.setPointValues()},drawDataLabels:function(){var a=this,c=a.mapOptionsToLevel, e,b;a.points.filter(function(a){return a.node.visible}).forEach(function(f){b=c[f.node.level];e={style:{}};f.node.isLeaf||(e.enabled=!1);b&&b.dataLabels&&(e=J(e,b.dataLabels),a._hasPointLabels=!0);f.shapeArgs&&(e.style.width=f.shapeArgs.width,f.dataLabel&&f.dataLabel.css({width:f.shapeArgs.width+"px"}));f.dlOptions=J(e,f.options.dataLabels)});t.prototype.drawDataLabels.call(this)},alignDataLabel:function(a,c,b){var e=b.style;!r(e.textOverflow)&&c.text&&c.getBBox().width>c.text.textWidth&&c.css({textOverflow:"ellipsis", width:e.width+="px"});k.column.prototype.alignDataLabel.apply(this,arguments);a.dataLabel&&a.dataLabel.attr({zIndex:(a.node.zIndex||0)+1})},pointAttribs:function(a,c){var b=P(this.mapOptionsToLevel)?this.mapOptionsToLevel:{},d=a&&b[a.node.level]||{};b=this.options;var h=c&&b.states[c]||{},t=a&&a.getClassName()||"";a={stroke:a&&a.borderColor||d.borderColor||h.borderColor||b.borderColor,"stroke-width":f(a&&a.borderWidth,d.borderWidth,h.borderWidth,b.borderWidth),dashstyle:a&&a.borderDashStyle||d.borderDashStyle|| h.borderDashStyle||b.borderDashStyle,fill:a&&a.color||this.color};-1!==t.indexOf("highcharts-above-level")?(a.fill="none",a["stroke-width"]=0):-1!==t.indexOf("highcharts-internal-node-interactive")?(c=f(h.opacity,b.opacity),a.fill=D(a.fill).setOpacity(c).get(),a.cursor="pointer"):-1!==t.indexOf("highcharts-internal-node")?a.fill="none":c&&(a.fill=D(a.fill).brighten(h.brightness).get());return a},drawPoints:function(){var a=this,c=a.chart,b=c.renderer,f=c.styledMode,d=a.options,h=f?{}:d.shadow,t=d.borderRadius, n=c.pointCount<d.animationLimit,g=d.allowTraversingTree;a.points.forEach(function(c){var e=c.node.levelDynamic,m={},x={},G={},k="level-group-"+c.node.level,l=!!c.graphic,y=n&&l,E=c.shapeArgs;c.shouldDraw()&&(t&&(x.r=t),J(!0,y?m:x,l?E:{},f?{}:a.pointAttribs(c,c.selected?"select":void 0)),a.colorAttribs&&f&&B(G,a.colorAttribs(c)),a[k]||(a[k]=b.g(k).attr({zIndex:1E3-(e||0)}).add(a.group),a[k].survive=!0));c.draw({animatableAttribs:m,attribs:x,css:G,group:a[k],renderer:b,shadow:h,shapeArgs:E,shapeType:"rect"}); g&&c.graphic&&(c.drillId=d.interactByLeaf?a.drillToByLeaf(c):a.drillToByGroup(c))})},onClickDrillToNode:function(a){var c=(a=a.point)&&a.drillId;M(c)&&(a.setState(""),this.setRootNode(c,!0,{trigger:"click"}))},drillToByGroup:function(a){var c=!1;1!==a.node.level-this.nodeMap[this.rootNode].level||a.node.isLeaf||(c=a.id);return c},drillToByLeaf:function(a){var c=!1;if(a.node.parent!==this.rootNode&&a.node.isLeaf)for(a=a.node;!c;)a=this.nodeMap[a.parent],a.parent===this.rootNode&&(c=a.id);return c}, drillUp:function(){var a=this.nodeMap[this.rootNode];a&&M(a.parent)&&this.setRootNode(a.parent,!0,{trigger:"traverseUpButton"})},drillToNode:function(a,c){R(32,!1,void 0,{"treemap.drillToNode":"use treemap.setRootNode"});this.setRootNode(a,c)},setRootNode:function(a,c,b){a=B({newRootId:a,previousRootId:this.rootNode,redraw:f(c,!0),series:this},b);S(this,"setRootNode",a,function(a){var c=a.series;c.idPreviousRoot=a.previousRootId;c.rootNode=a.newRootId;c.isDirty=!0;a.redraw&&c.chart.redraw()})},renderTraverseUpButton:function(a){var c= this,b=c.options.traverseUpButton,d=f(b.text,c.nodeMap[a].name,"\u25c1 Back");if(""===a||c.is("sunburst")&&1===c.tree.children.length&&a===c.tree.children[0].id)c.drillUpButton&&(c.drillUpButton=c.drillUpButton.destroy());else if(this.drillUpButton)this.drillUpButton.placed=!1,this.drillUpButton.attr({text:d}).align();else{var h=(a=b.theme)&&a.states;this.drillUpButton=this.chart.renderer.button(d,0,0,function(){c.drillUp()},a,h&&h.hover,h&&h.select).addClass("highcharts-drillup-button").attr({align:b.position.align, zIndex:7}).add().align(b.position,!1,b.relativeTo||"plotBox")}},buildKDTree:d,drawLegendSymbol:l.drawRectangle,getExtremes:function(){var a=t.prototype.getExtremes.call(this,this.colorValueData),c=a.dataMax;this.valueMin=a.dataMin;this.valueMax=c;return t.prototype.getExtremes.call(this)},getExtremesFromAll:!0,setState:function(a){this.options.inactiveOtherPoints=!0;t.prototype.setState.call(this,a,!1);this.options.inactiveOtherPoints=!1},utils:{recursive:E}},{draw:q.drawPoint,setVisible:k.pie.prototype.pointClass.prototype.setVisible, getClassName:function(){var a=w.prototype.getClassName.call(this),c=this.series,b=c.options;this.node.level<=c.nodeMap[c.rootNode].level?a+=" highcharts-above-level":this.node.isLeaf||f(b.interactByLeaf,!b.allowTraversingTree)?this.node.isLeaf||(a+=" highcharts-internal-node"):a+=" highcharts-internal-node-interactive";return a},isValid:function(){return!(!this.id&&!O(this.value))},setState:function(a){w.prototype.setState.call(this,a);this.graphic&&this.graphic.attr({zIndex:"hover"===a?1:0})},shouldDraw:function(){return O(this.plotY)&& null!==this.y}});C(u.Series,"afterBindAxes",function(){var a=this.xAxis,c=this.yAxis;if(a&&c)if(this.is("treemap")){var b={endOnTick:!1,gridLineWidth:0,lineWidth:0,min:0,dataMin:0,minPadding:0,max:100,dataMax:100,maxPadding:0,startOnTick:!1,title:null,tickPositions:[]};B(c.options,b);B(a.options,b);n=!0}else n&&(c.setOptions(c.userOptions),a.setOptions(a.userOptions),n=!1)});""});q(b,"Series/SunburstSeries.js",[b["Core/Series/Series.js"],b["Mixins/CenteredSeries.js"],b["Mixins/DrawPoint.js"],b["Core/Globals.js"], b["Mixins/TreeSeries.js"],b["Core/Utilities.js"]],function(b,d,p,q,u,l){var w=b.seriesTypes,A=d.getCenter,g=d.getStartAndEndRadians,k=u.getColor,D=u.getLevelOptions,H=u.setTreeValues,Q=u.updateRootId,N=l.correctFloat,K=l.error,C=l.extend,I=l.isNumber,r=l.isObject,R=l.isString,B=l.merge,S=l.splat,L=q.Series,O=180/Math.PI,P=function(b,d){var f=[];if(I(b)&&I(d)&&b<=d)for(;b<=d;b++)f.push(b);return f},M=function(b,d){d=r(d)?d:{};var f=0,h;if(r(b)){var g=B({},b);b=I(d.from)?d.from:0;var n=I(d.to)?d.to: 0;var a=P(b,n);b=Object.keys(g).filter(function(c){return-1===a.indexOf(+c)});var c=h=I(d.diffRadius)?d.diffRadius:0;a.forEach(function(a){a=g[a];var b=a.levelSize.unit,e=a.levelSize.value;"weight"===b?f+=e:"percentage"===b?(a.levelSize={unit:"pixels",value:e/100*c},h-=a.levelSize.value):"pixels"===b&&(h-=e)});a.forEach(function(a){var c=g[a];"weight"===c.levelSize.unit&&(c=c.levelSize.value,g[a].levelSize={unit:"pixels",value:c/f*h})});b.forEach(function(a){g[a].levelSize={value:0,unit:"pixels"}})}return g}, J=function(b){var f=b.level;return{from:0<f?f:1,to:f+b.height}},T=function(b,d){var f=d.mapIdToNode[b.parent],h=d.series,g=h.chart,n=h.points[b.i];f=k(b,{colors:h.options.colors||g&&g.options.colors,colorIndex:h.colorIndex,index:d.index,mapOptionsToLevel:d.mapOptionsToLevel,parentColor:f&&f.color,parentColorIndex:f&&f.colorIndex,series:d.series,siblings:d.siblings});b.color=f.color;b.colorIndex=f.colorIndex;n&&(n.color=b.color,n.colorIndex=b.colorIndex,b.sliced=b.id!==d.idRoot?n.sliced:!1);return b}; d={drawDataLabels:q.noop,drawPoints:function(){var b=this,d=b.mapOptionsToLevel,g=b.shapeRoot,k=b.group,l=b.hasRendered,n=b.rootNode,a=b.idPreviousRoot,c=b.nodeMap,e=c[a],x=e&&e.shapeArgs;e=b.points;var m=b.startAndEndRadians,p=b.chart,v=p&&p.options&&p.options.chart||{},u="boolean"===typeof v.animation?v.animation:!0,q=b.center[3]/2,A=b.chart.renderer,w=!1,D=!1;if(v=!!(u&&l&&n!==a&&b.dataLabelsGroup)){b.dataLabelsGroup.attr({opacity:0});var H=function(){w=!0;b.dataLabelsGroup&&b.dataLabelsGroup.animate({opacity:1, visibility:"visible"})}}e.forEach(function(e){var f=e.node,h=d[f.level];var t=e.shapeExisting||{};var y=f.shapeArgs||{},v=!(!f.visible||!f.shapeArgs);if(l&&u){var E={};var w={end:y.end,start:y.start,innerR:y.innerR,r:y.r,x:y.x,y:y.y};v?!e.graphic&&x&&(E=n===e.id?{start:m.start,end:m.end}:x.end<=y.start?{start:m.end,end:m.end}:{start:m.start,end:m.start},E.innerR=E.r=q):e.graphic&&(a===e.id?w={innerR:q,r:q}:g&&(w=g.end<=t.start?{innerR:q,r:q,start:m.end,end:m.end}:{innerR:q,r:q,start:m.start,end:m.start})); t=E}else w=y,t={};E=[y.plotX,y.plotY];if(!e.node.isLeaf)if(n===e.id){var z=c[n];z=z.parent}else z=e.id;C(e,{shapeExisting:y,tooltipPos:E,drillId:z,name:""+(e.name||e.id||e.index),plotX:y.plotX,plotY:y.plotY,value:f.val,isNull:!v});z=e.options;f=r(y)?y:{};z=r(z)?z.dataLabels:{};h=S(r(h)?h.dataLabels:{})[0];h=B({style:{}},h,z);z=h.rotationMode;if(!I(h.rotation)){if("auto"===z||"circular"===z)if(1>e.innerArcLength&&e.outerArcLength>f.radius){var F=0;e.dataLabelPath&&"circular"===z&&(h.textPath={enabled:!0})}else 1< e.innerArcLength&&e.outerArcLength>1.5*f.radius?"circular"===z?h.textPath={enabled:!0,attributes:{dy:5}}:z="parallel":(e.dataLabel&&e.dataLabel.textPathWrapper&&"circular"===z&&(h.textPath={enabled:!1}),z="perpendicular");"auto"!==z&&"circular"!==z&&(F=f.end-(f.end-f.start)/2);h.style.width="parallel"===z?Math.min(2.5*f.radius,(e.outerArcLength+e.innerArcLength)/2):f.radius;"perpendicular"===z&&e.series.chart.renderer.fontMetrics(h.style.fontSize).h>e.outerArcLength&&(h.style.width=1);h.style.width= Math.max(h.style.width-2*(h.padding||0),1);F=F*O%180;"parallel"===z&&(F-=90);90<F?F-=180:-90>F&&(F+=180);h.rotation=F}h.textPath&&(0===e.shapeExisting.innerR&&h.textPath.enabled?(h.rotation=0,h.textPath.enabled=!1,h.style.width=Math.max(2*e.shapeExisting.r-2*(h.padding||0),1)):e.dlOptions&&e.dlOptions.textPath&&!e.dlOptions.textPath.enabled&&"circular"===z&&(h.textPath.enabled=!0),h.textPath.enabled&&(h.rotation=0,h.style.width=Math.max((e.outerArcLength+e.innerArcLength)/2-2*(h.padding||0),1))); 0===h.rotation&&(h.rotation=.001);e.dlOptions=h;if(!D&&v){D=!0;var G=H}e.draw({animatableAttribs:w,attribs:C(t,!p.styledMode&&b.pointAttribs(e,e.selected&&"select")),onComplete:G,group:k,renderer:A,shapeType:"arc",shapeArgs:y})});v&&D?(b.hasRendered=!1,b.options.dataLabels.defer=!0,L.prototype.drawDataLabels.call(b),b.hasRendered=!0,w&&H()):L.prototype.drawDataLabels.call(b)},pointAttribs:w.column.prototype.pointAttribs,layoutAlgorithm:function(b,d,g){var f=b.start,h=b.end-f,n=b.val,a=b.x,c=b.y,e= g&&r(g.levelSize)&&I(g.levelSize.value)?g.levelSize.value:0,k=b.r,t=k+e,l=g&&I(g.slicedOffset)?g.slicedOffset:0;return(d||[]).reduce(function(b,d){var g=1/n*d.val*h,m=f+g/2,y=a+Math.cos(m)*l;m=c+Math.sin(m)*l;d={x:d.sliced?y:a,y:d.sliced?m:c,innerR:k,r:t,radius:e,start:f,end:f+g};b.push(d);f=d.end;return b},[])},setShapeArgs:function(b,d,g){var f=[],h=g[b.level+1];b=b.children.filter(function(b){return b.visible});f=this.layoutAlgorithm(d,b,h);b.forEach(function(b,a){a=f[a];var c=a.start+(a.end-a.start)/ 2,e=a.innerR+(a.r-a.innerR)/2,d=a.end-a.start;e=0===a.innerR&&6.28<d?{x:a.x,y:a.y}:{x:a.x+Math.cos(c)*e,y:a.y+Math.sin(c)*e};var h=b.val?b.childrenTotal>b.val?b.childrenTotal:b.val:b.childrenTotal;this.points[b.i]&&(this.points[b.i].innerArcLength=d*a.innerR,this.points[b.i].outerArcLength=d*a.r);b.shapeArgs=B(a,{plotX:e.x,plotY:e.y+4*Math.abs(Math.cos(c))});b.values=B(a,{val:h});b.children.length&&this.setShapeArgs(b,b.values,g)},this)},translate:function(){var b=this,d=b.options,k=b.center=A.call(b), l=b.startAndEndRadians=g(d.startAngle,d.endAngle),p=k[3]/2,n=k[2]/2-p,a=Q(b),c=b.nodeMap,e=c&&c[a],q={};b.shapeRoot=e&&e.shapeArgs;L.prototype.translate.call(b);var m=b.tree=b.getTree();b.renderTraverseUpButton(a);c=b.nodeMap;e=c[a];var r=R(e.parent)?e.parent:"";r=c[r];var v=J(e);var u=v.from,w=v.to;v=D({from:u,levels:b.options.levels,to:w,defaults:{colorByPoint:d.colorByPoint,dataLabels:d.dataLabels,levelIsConstant:d.levelIsConstant,levelSize:d.levelSize,slicedOffset:d.slicedOffset}});v=M(v,{diffRadius:n, from:u,to:w});H(m,{before:T,idRoot:a,levelIsConstant:d.levelIsConstant,mapOptionsToLevel:v,mapIdToNode:c,points:b.points,series:b});d=c[""].shapeArgs={end:l.end,r:p,start:l.start,val:e.val,x:k[0],y:k[1]};this.setShapeArgs(r,d,v);b.mapOptionsToLevel=v;b.data.forEach(function(a){q[a.id]&&K(31,!1,b.chart);q[a.id]=!0});q={}},alignDataLabel:function(b,d,g){if(!g.textPath||!g.textPath.enabled)return w.treemap.prototype.alignDataLabel.apply(this,arguments)},animate:function(b){var d=this.chart,f=[d.plotWidth/ 2,d.plotHeight/2],g=d.plotLeft,k=d.plotTop;d=this.group;b?(b={translateX:f[0]+g,translateY:f[1]+k,scaleX:.001,scaleY:.001,rotation:10,opacity:.01},d.attr(b)):(b={translateX:g,translateY:k,scaleX:1,scaleY:1,rotation:0,opacity:1},d.animate(b,this.options.animation))},utils:{calculateLevelSizes:M,getLevelFromAndTo:J,range:P}};p={draw:p.drawPoint,shouldDraw:function(){return!this.isNull},isValid:function(){return!0},getDataLabelPath:function(b){var d=this.series.chart.renderer,f=this.shapeExisting,g= f.start,k=f.end,l=g+(k-g)/2;l=0>l&&l>-Math.PI||l>Math.PI;var a=f.r+(b.options.distance||0);g===-Math.PI/2&&N(k)===N(1.5*Math.PI)&&(g=-Math.PI+Math.PI/360,k=-Math.PI/360,l=!0);if(k-g>Math.PI){l=!1;var c=!0}this.dataLabelPath&&(this.dataLabelPath=this.dataLabelPath.destroy());this.dataLabelPath=d.arc({open:!0,longArc:c?1:0}).add(b);this.dataLabelPath.attr({start:l?g:k,end:l?k:g,clockwise:+l,x:f.x,y:f.y,r:(a+f.innerR)/2});return this.dataLabelPath}};"";b.seriesType("sunburst","treemap",{center:["50%", "50%"],colorByPoint:!1,opacity:1,dataLabels:{allowOverlap:!0,defer:!0,rotationMode:"auto",style:{textOverflow:"ellipsis"}},rootId:void 0,levelIsConstant:!0,levelSize:{value:1,unit:"weight"},slicedOffset:10},d,p)});q(b,"masters/modules/sunburst.src.js",[],function(){})}); //# sourceMappingURL=sunburst.js.map
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import PropTypes from 'prop-types'; import { Transition } from 'react-transition-group'; import useTheme from '../styles/useTheme'; import { reflow, getTransitionProps } from '../transitions/utils'; import useForkRef from '../utils/useForkRef'; function getScale(value) { return `scale(${value}, ${value ** 2})`; } const styles = { entering: { opacity: 1, transform: getScale(1) }, entered: { opacity: 1, transform: 'none' } }; /** * The Grow transition is used by the [Tooltip](/components/tooltips/) and * [Popover](/components/popover/) components. * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally. */ const Grow = React.forwardRef(function Grow(props, ref) { const { children, in: inProp, onEnter, onExit, style, timeout = 'auto' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]); const timer = React.useRef(); const autoTimeout = React.useRef(); const handleRef = useForkRef(children.ref, ref); const theme = useTheme(); const handleEnter = (node, isAppearing) => { reflow(node); // So the animation always start from the start. const { duration: transitionDuration, delay } = getTransitionProps({ style, timeout }, { mode: 'enter' }); let duration; if (timeout === 'auto') { duration = theme.transitions.getAutoHeightDuration(node.clientHeight); autoTimeout.current = duration; } else { duration = transitionDuration; } node.style.transition = [theme.transitions.create('opacity', { duration, delay }), theme.transitions.create('transform', { duration: duration * 0.666, delay })].join(','); if (onEnter) { onEnter(node, isAppearing); } }; const handleExit = node => { const { duration: transitionDuration, delay } = getTransitionProps({ style, timeout }, { mode: 'exit' }); let duration; if (timeout === 'auto') { duration = theme.transitions.getAutoHeightDuration(node.clientHeight); autoTimeout.current = duration; } else { duration = transitionDuration; } node.style.transition = [theme.transitions.create('opacity', { duration, delay }), theme.transitions.create('transform', { duration: duration * 0.666, delay: delay || duration * 0.333 })].join(','); node.style.opacity = '0'; node.style.transform = getScale(0.75); if (onExit) { onExit(node); } }; const addEndListener = (_, next) => { if (timeout === 'auto') { timer.current = setTimeout(next, autoTimeout.current || 0); } }; React.useEffect(() => { return () => { clearTimeout(timer.current); }; }, []); return /*#__PURE__*/React.createElement(Transition, _extends({ appear: true, in: inProp, onEnter: handleEnter, onExit: handleExit, addEndListener: addEndListener, timeout: timeout === 'auto' ? null : timeout }, other), (state, childProps) => { return React.cloneElement(children, _extends({ style: _extends({ opacity: 0, transform: getScale(0.75), visibility: state === 'exited' && !inProp ? 'hidden' : undefined }, styles[state], {}, style, {}, children.props.style), ref: handleRef }, childProps)); }); }); process.env.NODE_ENV !== "production" ? Grow.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * A single child content element. */ children: PropTypes.element, /** * If `true`, show the component; triggers the enter or exit animation. */ in: PropTypes.bool, /** * @ignore */ onEnter: PropTypes.func, /** * @ignore */ onExit: PropTypes.func, /** * @ignore */ style: PropTypes.object, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. * * Set to 'auto' to automatically calculate transition time based on height. */ timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number })]) } : void 0; Grow.muiSupportAuto = true; export default Grow;
"use strict"; exports.__esModule = true; exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createElement = _interopRequireDefault(require("../createElement")); var _css = _interopRequireDefault(require("../StyleSheet/css")); var _pick = _interopRequireDefault(require("../../modules/pick")); var _useElementLayout = _interopRequireDefault(require("../../hooks/useElementLayout")); var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs")); var _usePlatformMethods = _interopRequireDefault(require("../../hooks/usePlatformMethods")); var _useResponderEvents = _interopRequireDefault(require("../../hooks/useResponderEvents")); var _StyleSheet = _interopRequireDefault(require("../StyleSheet")); var _TextAncestorContext = _interopRequireDefault(require("../Text/TextAncestorContext")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ var forwardPropsList = { accessibilityLabel: true, accessibilityLiveRegion: true, accessibilityRole: true, accessibilityState: true, accessibilityValue: true, accessible: true, children: true, classList: true, disabled: true, importantForAccessibility: true, nativeID: true, onBlur: true, onClick: true, onClickCapture: true, onContextMenu: true, onFocus: true, onKeyDown: true, onKeyUp: true, onTouchCancel: true, onTouchCancelCapture: true, onTouchEnd: true, onTouchEndCapture: true, onTouchMove: true, onTouchMoveCapture: true, onTouchStart: true, onTouchStartCapture: true, pointerEvents: true, ref: true, style: true, testID: true, // unstable dataSet: true, onMouseDown: true, onMouseEnter: true, onMouseLeave: true, onMouseMove: true, onMouseOver: true, onMouseOut: true, onMouseUp: true, onScroll: true, onWheel: true, href: true, rel: true, target: true }; var pickProps = function pickProps(props) { return (0, _pick.default)(props, forwardPropsList); }; var View = (0, React.forwardRef)(function (props, forwardedRef) { var onLayout = props.onLayout, onMoveShouldSetResponder = props.onMoveShouldSetResponder, onMoveShouldSetResponderCapture = props.onMoveShouldSetResponderCapture, onResponderEnd = props.onResponderEnd, onResponderGrant = props.onResponderGrant, onResponderMove = props.onResponderMove, onResponderReject = props.onResponderReject, onResponderRelease = props.onResponderRelease, onResponderStart = props.onResponderStart, onResponderTerminate = props.onResponderTerminate, onResponderTerminationRequest = props.onResponderTerminationRequest, onScrollShouldSetResponder = props.onScrollShouldSetResponder, onScrollShouldSetResponderCapture = props.onScrollShouldSetResponderCapture, onSelectionChangeShouldSetResponder = props.onSelectionChangeShouldSetResponder, onSelectionChangeShouldSetResponderCapture = props.onSelectionChangeShouldSetResponderCapture, onStartShouldSetResponder = props.onStartShouldSetResponder, onStartShouldSetResponderCapture = props.onStartShouldSetResponderCapture; if (process.env.NODE_ENV !== 'production') { React.Children.toArray(props.children).forEach(function (item) { if (typeof item === 'string') { console.error("Unexpected text node: " + item + ". A text node cannot be a child of a <View>."); } }); } var hasTextAncestor = (0, React.useContext)(_TextAncestorContext.default); var hostRef = (0, React.useRef)(null); var classList = [classes.view]; var style = _StyleSheet.default.compose(hasTextAncestor && styles.inline, props.style); (0, _useElementLayout.default)(hostRef, onLayout); (0, _useResponderEvents.default)(hostRef, { onMoveShouldSetResponder: onMoveShouldSetResponder, onMoveShouldSetResponderCapture: onMoveShouldSetResponderCapture, onResponderEnd: onResponderEnd, onResponderGrant: onResponderGrant, onResponderMove: onResponderMove, onResponderReject: onResponderReject, onResponderRelease: onResponderRelease, onResponderStart: onResponderStart, onResponderTerminate: onResponderTerminate, onResponderTerminationRequest: onResponderTerminationRequest, onScrollShouldSetResponder: onScrollShouldSetResponder, onScrollShouldSetResponderCapture: onScrollShouldSetResponderCapture, onSelectionChangeShouldSetResponder: onSelectionChangeShouldSetResponder, onSelectionChangeShouldSetResponderCapture: onSelectionChangeShouldSetResponderCapture, onStartShouldSetResponder: onStartShouldSetResponder, onStartShouldSetResponderCapture: onStartShouldSetResponderCapture }); var supportedProps = pickProps(props); supportedProps.classList = classList; supportedProps.style = style; var platformMethodsRef = (0, _usePlatformMethods.default)(hostRef, supportedProps); var setRef = (0, _useMergeRefs.default)(hostRef, platformMethodsRef, forwardedRef); supportedProps.ref = setRef; return (0, _createElement.default)('div', supportedProps); }); View.displayName = 'View'; var classes = _css.default.create({ view: { alignItems: 'stretch', border: '0 solid black', boxSizing: 'border-box', display: 'flex', flexBasis: 'auto', flexDirection: 'column', flexShrink: 0, margin: 0, minHeight: 0, minWidth: 0, padding: 0, position: 'relative', zIndex: 0 } }); var styles = _StyleSheet.default.create({ inline: { display: 'inline-flex' } }); var _default = View; exports.default = _default; module.exports = exports.default;
/** * window.c.ProjectSuggestedContributions component * A Project-show page helper to show suggested amounts of contributions * * Example of use: * view: () => { * ... * m.component(c.ProjectSuggestedContributions, {project: project}) * ... * } */ import m from 'mithril'; import _ from 'underscore'; const projectSuggestedContributions = { view(ctrl, args) { const project = args.project(); const suggestionUrl = amount => `/projects/${project.project_id}/contributions/new?amount=${amount}`, suggestedValues = [10, 25, 50, 100]; return m('#suggestions', _.map(suggestedValues, amount => project ? m(`a[href="${suggestionUrl(amount)}"].card-reward.card-big.card-secondary.u-marginbottom-20`, [ m('.fontsize-larger', `R$ ${amount}`) ]) : '')); } }; export default projectSuggestedContributions;
import { get } from '../get' export function getSearchData(page, cityName, category, keyword) { const keywordStr = keyword ? '/' + keyword : '' const result = get('/api/search/' + page + '/' + cityName + '/' + category + keywordStr) return result }
/*global define*/ /*jslint white:true,browser:true*/ define([ 'bluebird', // CDN 'kb_common/html', // LOCAL 'common/ui', 'common/runtime', 'common/events', 'common/props', // Wrapper for inputs './inputWrapperWidget', 'widgets/appWidgets/fieldWidget', // Display widgets 'widgets/appWidgets/paramDisplayResolver' ], function ( Promise, html, UI, Runtime, Events, Props, //Wrappers RowWidget, FieldWidget, ParamResolver ) { 'use strict'; var t = html.tag, form = t('form'), span = t('span'), div = t('div'); function factory(config) { var runtime = Runtime.make(), parentBus = config.bus, cellId = config.cellId, workspaceInfo = config.workspaceInfo, container, ui, bus, places, model = Props.make(), inputBusses = [], settings = { showAdvanced: null }, paramResolver = ParamResolver.make(); // DATA /* * The input control widget is selected based on these parameters: * - data type - (text, int, float, workspaceObject (ref, name) * - input app - input, select */ // RENDERING function makeFieldWidget(parameterSpec, value) { var bus = runtime.bus().makeChannelBus(null, 'Params view input bus comm widget'), inputWidget = paramResolver.getWidgetFactory(parameterSpec); inputBusses.push(bus); // An input widget may ask for the current model value at any time. bus.on('sync', function () { parentBus.emit('parameter-sync', { parameter: parameterSpec.id() }); }); parentBus.listen({ key: { type: 'update', parameter: parameterSpec.id() }, handle: function (message) { bus.emit('update', { value: message.value }); } }); // Just pass the update along to the input widget. // TODO: commented out, is it even used? // parentBus.listen({ // test: function (message) { // var pass = (message.type === 'update' && message.parameter === parameterSpec.id()); // return pass; // }, // handle: function (message) { // bus.send(message); // } // }); return FieldWidget.make({ inputControlFactory: inputWidget, showHint: true, useRowHighight: true, initialValue: value, parameterSpec: parameterSpec, bus: bus, workspaceId: workspaceInfo.id }); } function renderAdvanced() { var advancedInputs = container.querySelectorAll('[data-advanced-parameter]'); if (advancedInputs.length === 0) { return; } var removeClass = (settings.showAdvanced ? 'advanced-parameter-hidden' : 'advanced-parameter-showing'), addClass = (settings.showAdvanced ? 'advanced-parameter-showing' : 'advanced-parameter-hidden'); for (var i = 0; i < advancedInputs.length; i += 1) { var input = advancedInputs[i]; input.classList.remove(removeClass); input.classList.add(addClass); } // How many advanaced? // Also update the button var button = container.querySelector('[data-button="toggle-advanced"]'); button.innerHTML = (settings.showAdvanced ? 'Hide Advanced' : 'Show Advanced (' + advancedInputs.length + ' hidden)'); // Also update the } function renderLayout() { var events = Events.make(), content = form({dataElement: 'input-widget-form'}, [ ui.buildPanel({ type: 'default', classes: 'kb-panel-light', body: [ ui.makeButton('Show Advanced', 'toggle-advanced', {events: events}) ] }), ui.buildPanel({ title: 'Inputs', body: div({dataElement: 'input-fields'}), classes: ['kb-panel-container'] }), ui.buildPanel({ title: span(['Parameters', span({dataElement: 'advanced-hidden'})]), body: div({dataElement: 'parameter-fields'}), classes: ['kb-panel-container'] }), ui.buildPanel({ title: 'Outputs', body: div({dataElement: 'output-fields'}), classes: ['kb-panel-container'] }) ]); return { content: content, events: events }; } // MESSAGE HANDLERS function doAttach(node) { container = node; ui = UI.make({ node: container, bus: bus }); var layout = renderLayout(); container.innerHTML = layout.content; layout.events.attachEvents(container); places = { inputFields: ui.getElement('input-fields'), outputFields: ui.getElement('output-fields'), parameterFields: ui.getElement('parameter-fields'), advancedParameterFields: ui.getElement('advanced-parameter-fields') }; } // EVENTS function attachEvents() { bus.on('reset-to-defaults', function () { inputBusses.forEach(function (inputBus) { inputBus.send({ type: 'reset-to-defaults' }); }); }); bus.on('toggle-advanced', function () { settings.showAdvanced = !settings.showAdvanced; renderAdvanced(); }); } // LIFECYCLE API function renderParameters(params) { var widgets = []; // First get the app specs, which is stashed in the model, // with the parameters returned. // Separate out the params into the primary groups. var params = model.getItem('parameters'), inputParams = params.filter(function (spec) { return (spec.spec.ui_class === 'input'); }), outputParams = params.filter(function (spec) { return (spec.spec.ui_class === 'output'); }), parameterParams = params.filter(function (spec) { return (spec.spec.ui_class === 'parameter'); }); return Promise.resolve() .then(function () { if (inputParams.length === 0) { places.inputFields.innerHTML = span({style: {fontStyle: 'italic'}}, 'No input objects for this app'); } else { return Promise.all(inputParams.map(function (spec) { var fieldWidget = makeFieldWidget(spec, model.getItem(['params', spec.name()])), rowWidget = RowWidget.make({widget: fieldWidget, spec: spec}), rowNode = document.createElement('div'); places.inputFields.appendChild(rowNode); widgets.push(rowWidget); rowWidget.attach(rowNode); })); } }) .then(function () { if (outputParams.length === 0) { places.outputFields.innerHTML = span({style: {fontStyle: 'italic'}}, 'No output objects for this app'); } else { return Promise.all(outputParams.map(function (spec) { var fieldWidget = makeFieldWidget(spec, model.getItem(['params', spec.name()])), rowWidget = RowWidget.make({widget: fieldWidget, spec: spec}), rowNode = document.createElement('div'); places.outputFields.appendChild(rowNode); widgets.push(rowWidget); rowWidget.attach(rowNode); })); } }) .then(function () { if (parameterParams.length === 0) { ui.setContent('parameter-fields', span({style: {fontStyle: 'italic'}}, 'No parameters for this app')); } else { return Promise.all(parameterParams.map(function (spec) { var fieldWidget = makeFieldWidget(spec, model.getItem(['params', spec.name()])), rowWidget = RowWidget.make({widget: fieldWidget, spec: spec}), rowNode = document.createElement('div'); places.parameterFields.appendChild(rowNode); widgets.push(rowWidget); rowWidget.attach(rowNode); })); } }) .then(function () { return Promise.all(widgets.map(function (widget) { return widget.start(); })); }) .then(function () { return Promise.all(widgets.map(function (widget) { return widget.run(params); })); }) .then(function () { renderAdvanced(); }); } function start() { // send parent the ready message return Promise.try(function () { parentBus.emit('ready'); // parent will send us our initial parameters parentBus.on('run', function (message) { doAttach(message.node); model.setItem('parameters', message.parameters); // we then create our widgets renderParameters() .then(function () { // do something after success attachEvents(); }) .catch(function (err) { // do somethig with the error. console.error('ERROR in start', err); }); }); }); } function stop() { return Promise.try(function () { // unregister listerrs... }); } // CONSTRUCTION bus = runtime.bus().makeChannelBus(null, 'params view own bus'); return { start: start, stop: stop, bus: function () { return bus; } }; } return { make: function (config) { return factory(config); } }; });
// Copyright 2011 Splunk, Inc. // // 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() { var Http = require('../../http'); var utils = require('../../utils'); var root = exports || this; var getHeaders = function(headersString) { var headers = {}; var headerLines = headersString.split("\n"); for(var i = 0; i < headerLines.length; i++) { if (utils.trim(headerLines[i]) !== "") { var headerParts = headerLines[i].split(": "); headers[headerParts[0]] = headerParts[1]; } } return headers; }; root.JQueryHttp = Http.extend({ init: function(isSplunk) { this._super(isSplunk); }, makeRequest: function(url, message, callback) { var that = this; var params = { url: url, type: message.method, headers: message.headers, data: message.body || "", timeout: message.timeout || 0, dataType: "json", success: utils.bind(this, function(data, error, res) { var response = { statusCode: res.status, headers: getHeaders(res.getAllResponseHeaders()) }; var complete_response = this._buildResponse(error, response, data); callback(complete_response); }), error: function(res, data, error) { var response = { statusCode: res.status, headers: getHeaders(res.getAllResponseHeaders()) }; if (data === "abort") { response.statusCode = "abort"; res.responseText = "{}"; } var json = JSON.parse(res.responseText); var complete_response = that._buildResponse(error, response, json); callback(complete_response); } }; return $.ajax(params); }, parseJson: function(json) { // JQuery does this for us return json; } }); })();
var fs = require('fs'); var PNG = require('../lib/png').PNG; var test = require('tape'); var noLargeOption = process.argv.indexOf("nolarge") >= 0; fs.readdir(__dirname + '/in/', function (err, files) { if (err) throw err; files = files.filter(function (file) { return (!noLargeOption || !file.match(/large/i)) && Boolean(file.match(/\.png$/i)); }); console.log("Converting images"); files.forEach(function (file) { var expectedError = false; if (file.match(/^x/)) { expectedError = true; } test('convert sync - ' + file, function (t) { t.timeoutAfter(1000 * 60 * 5); var data = fs.readFileSync(__dirname + '/in/' + file); try { var png = PNG.sync.read(data); } catch (e) { if (!expectedError) { t.fail('Unexpected error parsing..' + file + '\n' + e.message + "\n" + e.stack); } else { t.pass("completed"); } return t.end(); } if (expectedError) { t.fail("Sync: Error expected, parsed fine .. - " + file); return t.end(); } var outpng = new PNG(); outpng.gamma = png.gamma; outpng.data = png.data; outpng.width = png.width; outpng.height = png.height; outpng.pack() .pipe(fs.createWriteStream(__dirname + '/outsync/' + file) .on("finish", function () { t.pass("completed"); t.end(); })); }); test('convert async - ' + file, function (t) { t.timeoutAfter(1000 * 60 * 5); fs.createReadStream(__dirname + '/in/' + file) .pipe(new PNG()) .on('error', function (err) { if (!expectedError) { t.fail("Async: Unexpected error parsing.." + file + '\n' + err.message + '\n' + err.stack); } else { t.pass("completed"); } t.end(); }) .on('parsed', function () { if (expectedError) { t.fail("Async: Error expected, parsed fine .." + file); return t.end(); } this.pack() .pipe( fs.createWriteStream(__dirname + '/out/' + file) .on("finish", function () { t.pass("completed"); t.end(); })); }); }); }); });
var assert = require('assert'); var Q = require('q'); var R = require('..'); describe('pipeP', function() { function a(x) {return x + 'A';} function b(x) {return x + 'B';} it('handles promises', function() { var plusOne = function(a) {return a + 1;}; var multAsync = function(a, b) {return Q.when(a * b);}; return R.pipeP(multAsync, plusOne)(2, 3) .then(function(result) { assert.strictEqual(result, 7); }); }); it('returns a function with arity == leftmost argument', function() { function a2(x, y) { void y; return 'A2'; } function a3(x, y) { void y; return Q.when('A2'); } function a4(x, y) { void y; return 'A2'; } var f1 = R.pipeP(a, b); assert.strictEqual(f1.length, a.length); var f2 = R.pipeP(a2, b); assert.strictEqual(f2.length, a2.length); var f3 = R.pipeP(a3, b); assert.strictEqual(f3.length, a3.length); var f4 = R.pipeP(a4, b); assert.strictEqual(f4.length, a4.length); }); });
var _ = require('underscore'); /* A rule should contain explain and rule methods */ // TODO explain explain // TODO explain missing // TODO explain assert function assert (options, password) { return !!password && options.minLength <= password.length; } function explain(options) { if (options.minLength === 1) { return { message: 'Non-empty password required', code: 'nonEmpty' }; } return { message: 'At least %d characters in length', format: [options.minLength], code: 'lengthAtLeast' }; } module.exports = { validate: function (options) { if (!_.isObject(options)) { throw new Error('options should be an object'); } if (!_.isNumber(options.minLength) || _.isNaN(options.minLength)) { throw new Error('length expects minLength to be a non-zero number'); } return true; }, explain: explain, missing: function (options, password) { var explained = explain(options); explained.verified = !!assert(options, password); return explained; }, assert: assert };
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): Jesse Ruderman * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var gTestfile = 'regress-463259.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 463259; var summary = 'Do not assert: VALUE_IS_FUNCTION(cx, fval)'; var actual = ''; var expect = ''; printBugNumber(BUGNUMBER); printStatus (summary); jit(true); try { (function(){ eval("(function(){ for (var j=0;j<4;++j) if (j==3) undefined(); })();"); })(); } catch(ex) { } jit(false); reportCompare(expect, actual, summary);
import { rectangle } from 'leaflet'; import boundsType from './types/bounds'; import Path from './Path'; export default class Rectangle extends Path { static propTypes = { bounds: boundsType.isRequired, }; componentWillMount() { super.componentWillMount(); const { bounds, map, ...props } = this.props; this.leafletElement = rectangle(bounds, props); } componentDidUpdate(prevProps) { if (this.props.bounds !== prevProps.bounds) { this.leafletElement.setBounds(this.props.bounds); } this.setStyleIfChanged(prevProps, this.props); } }
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("dd-drop-plugin",function(e,t){var n=function(e){e.node=e.host,n.superclass.constructor.apply(this,arguments)};n.NAME="dd-drop-plugin",n.NS="drop",e.extend(n,e.DD.Drop),e.namespace("Plugin"),e.Plugin.Drop=n},"3.8.0pr2",{requires:["dd-drop"]});
//= require d3/d3 //= require jquery.qtip.min //= require simple_statistics gfw.ui.model.CountriesEmbedOverview = cdb.core.Model.extend({ defaults: { graph: 'total_loss', years: true, class: null } }); gfw.ui.view.CountriesEmbedOverview = cdb.core.View.extend({ el: document.body, events: { 'click .graph_tab': '_updateGraph' }, initialize: function() { this.model = new gfw.ui.model.CountriesEmbedOverview(); this.$graph = $('.overview_graph__area'); this.$years = $('.overview_graph__years'); var m = this.m = 40, w = this.w = this.$graph.width()+(m*2), h = this.h = this.$graph.height(), vertical_m = this.vertical_m = 20; this.x_scale = d3.scale.linear() .range([m, w-m]) .domain([2001, 2012]); this.grid_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([0, 1]); this.model.bind('change:graph', this._redrawGraph, this); this.model.bind('change:years', this._toggleYears, this); this.model.bind('change:class', this._toggleClass, this); this._initViews(); }, _initViews: function() { this.tooltip = d3.select('body') .append('div') .attr('class', 'tooltip'); this._drawYears(); this._drawGraph(); }, _toggleYears: function() { var that = this; if(this.model.get('years') === false) { this.$years.slideUp(250, function() { $('.overview_graph__axis').slideDown(); }); } else { $('.overview_graph__axis').slideUp(250, function() { that.$years.slideDown(); }); } }, _showYears: function() { if (!this.model.get('years')) { this.model.set('years', true); } }, _hideYears: function() { if (this.model.get('years')) { this.model.set('years', false); } }, _updateGraph: function(e) { e.preventDefault(); var $target = $(e.target).closest('.graph_tab'), graph = $target.attr('data-slug'); if (graph === this.model.get('graph')) { return; } else { $('.graph_tab').removeClass('selected'); $target.addClass('selected'); this.model.set('graph', graph); } }, _redrawGraph: function() { var graph = this.model.get('graph'); $('.overview_graph__title').html(config.GRAPHS[graph].title); $('.overview_graph__legend p').html(config.GRAPHS[graph].subtitle); $('.overview_graph__legend .info').attr('data-source', graph); this.$graph.find('.'+graph); this.$graph.find('.chart').hide(); this.$graph.find('.'+graph).fadeIn(); this._drawGraph(); }, _drawYears: function() { var markup_years = ''; for (var y = 2001; y<=2012; y += 1) { var y_ = this.x_scale(y); if (y === 2001) { y_ -= 25; } else if (y === 2012) { y_ -= 55; } else { y_ -= 40; } markup_years += '<span class="year" style="left:'+y_+'px">'+y+'</span>'; } this.$years.html(markup_years); }, _drawGraph: function() { var that = this; var w = this.w, h = this.h, vertical_m = this.vertical_m, m = this.m, x_scale = this.x_scale; var grid_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([1, 0]); d3.select('#chart').remove(); var svg = d3.select('.overview_graph__area') .append('svg:svg') .attr('id', 'chart') .attr('width', w) .attr('height', h); // grid svg.selectAll('line.grid_h') .data(grid_scale.ticks(4)) .enter() .append('line') .attr({ 'class': 'grid grid_h', 'x1': 0, 'x2': w, 'y1': function(d, i) { return grid_scale(d); }, 'y2': function(d, i) { return grid_scale(d); } }); svg.selectAll('line.grid_v') .data(x_scale.ticks(12)) .enter() .append('line') .attr({ 'class': 'grid grid_v', 'y1': h, 'y2': 0, 'x1': function(d) { return x_scale(d); }, 'x2': function(d) { return x_scale(d); } }); var gradient = svg.append('svg:defs') .append('svg:linearGradient') .attr('id', 'gradient') .attr('x1', '0%') .attr('y1', '0%') .attr('x2', '0%') .attr('y2', '100%') .attr('spreadMethod', 'pad'); gradient.append('svg:stop') .attr('offset', '0%') .attr('stop-color', '#CA46FF') .attr('stop-opacity', .5); gradient.append('svg:stop') .attr('offset', '100%') .attr('stop-color', '#D24DFF') .attr('stop-opacity', 1); if (this.model.get('graph') === 'total_loss') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('Mha') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var sql = 'SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as y'+y+', ' } sql += 'SUM(y2012) as y2012, (SELECT SUM(y2001_y2012)\ FROM countries_gain) as gain\ FROM loss_gt_0'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) { var data = json.rows[0]; var data_ = [], gain = null; _.each(data, function(val, key) { if (key === 'gain') { gain = val/12; } else { data_.push({ 'year': key.replace('y',''), 'value': val }); } }); var y_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([d3.max(data_, function(d) { return d.value; }), 0]); // area var area = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.value); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area) .style('fill', 'url(#gradient)'); // circles svg.selectAll('circle') .data(data_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); var data_gain_ = [ { year: 2001, value: gain }, { year: 2012, value: gain } ]; // line svg.selectAll('line.overview_line') .data(data_gain_) .enter() .append('line') .attr({ 'class': 'overview_line', 'x1': m, 'x2': w-m, 'y1': function(d) { return y_scale(gain); }, 'y2': function(d) { return y_scale(gain); } }); svg.selectAll('circle.gain') .data(data_gain_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>2001-2012</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'percent_loss') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('%') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var sql = 'WITH loss as (SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as sum_loss_y'+y+', '; } sql += 'SUM(y2012) as sum_loss_y2012\ FROM loss_gt_25), extent as (SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as sum_extent_y'+y+', '; } sql += 'SUM(y2012) as sum_extent_y2012\ FROM extent_gt_25)\ SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'sum_loss_y'+y+'/sum_extent_y'+y+' as percent_loss_'+y+', '; } sql += 'sum_loss_y2012/sum_extent_y2012 as percent_loss_2012, (SELECT SUM(y2001_y2012)/('; for(var y = 2001; y < 2012; y++) { sql += 'sum_extent_y'+y+' + '; } sql += 'sum_extent_y2012)\ FROM countries_gain) as gain\ FROM loss, extent'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows[0]; var data_ = [], gain = null; _.each(data, function(val, key) { if (key === 'gain') { gain = val/12; } else { data_.push({ 'year': key.replace('percent_loss_',''), 'value': val }); } }); var y_scale = grid_scale; // area var area = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.value*100); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area) .style('fill', 'url(#gradient)'); // circles svg.selectAll('circle') .data(data_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value*100); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+parseFloat(d.value*100).toFixed(2)+' %'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); var data_gain_ = [ { year: 2001, value: gain }, { year: 2012, value: gain } ]; // line svg.selectAll('line.overview_line') .data(data_gain_) .enter() .append('line') .attr({ 'class': 'overview_line', 'x1': m, 'x2': w-m, 'y1': function(d) { return y_scale(gain*100); }, 'y2': function(d) { return y_scale(gain*100); } }); // circles svg.selectAll('circle.gain') .data(data_gain_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value*100); }) .attr('r', 6) .attr('name', function(d) { return '<span>2001-2012</span>'+parseFloat(d.value*100).toFixed(2)+' %'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'total_extent') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('Mha') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var gradient_extent = svg.append('svg:defs') .append('svg:linearGradient') .attr('id', 'gradient_extent') .attr('x1', '0%') .attr('y1', '0%') .attr('x2', '0%') .attr('y2', '100%') .attr('spreadMethod', 'pad'); gradient_extent.append('svg:stop') .attr('offset', '0%') .attr('stop-color', '#98BD17') .attr('stop-opacity', .5); gradient_extent.append('svg:stop') .attr('offset', '100%') .attr('stop-color', '#98BD17') .attr('stop-opacity', 1); var sql = 'SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(loss.y'+y+') as loss_y'+y+', '; } sql += 'SUM(loss.y2012) as loss_y2012, '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(extent.y'+y+') as extent_y'+y+', '; } sql += 'SUM(extent.y2012) as extent_y2012\ FROM loss_gt_25 loss, extent_gt_25 extent\ WHERE loss.iso = extent.iso'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows[0]; var data_ = [], data_loss_ = [], data_extent_ = []; _.each(data, function(val, key) { var year = key.split('_y')[1]; var obj = _.find(data_, function(obj) { return obj.year == year; }); if(obj === undefined) { data_.push({ 'year': year }); } if (key.indexOf('loss_y') != -1) { data_loss_.push({ 'year': key.split('_y')[1], 'value': val }); } if (key.indexOf('extent_y') != -1) { data_extent_.push({ 'year': key.split('extent_y')[1], 'value': val }); } }); _.each(data_, function(val) { var loss = _.find(data_loss_, function(obj) { return obj.year == val.year; }), extent = _.find(data_extent_, function(obj) { return obj.year == val.year; }); _.extend(val, { 'loss': loss.value, 'extent': extent.value }); }); var domain = [d3.max(data_, function(d) { return d.extent; }), 0]; var y_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain(domain); // area var area_loss = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.loss); }); var area_extent = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(function(d) { return y_scale(d.extent); }) .y1(function(d) { return y_scale(d.loss); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area_loss) .style('fill', 'url(#gradient)'); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area_extent) .style('fill', 'url(#gradient_extent)'); // circles svg.selectAll('circle') .data(data_loss_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); svg.selectAll('circle.gain') .data(data_extent_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'ratio') { this._hideYears(); svg.append('text') .attr('class', 'axis light') .attr('id', 'axis_y') .text('Cover gain 2001-2012') .attr('x', -(h/2)) .attr('y', 30) .attr('transform', 'rotate(-90)'); var shadow = svg.append('svg:defs') .append('svg:filter') .attr('id', 'shadow') .attr('x', '0%') .attr('y', '0%') .attr('width', '200%') .attr('height', '200%') shadow.append('svg:feOffset') .attr('result', 'offOut') .attr('in', 'SourceAlpha') .attr('dx', 0) .attr('dy', 0); shadow.append('svg:feGaussianBlur') .attr('result', 'blurOut') .attr('in', 'offOut') .attr('stdDeviation', 1); shadow.append('svg:feBlend') .attr('in', 'SourceGraphic') .attr('in2', 'blurOut') .attr('mode', 'normal'); var sql = 'WITH loss as (SELECT iso, SUM('; for(var y = 2001; y < 2012; y++) { sql += 'loss.y'+y+' + '; } sql += 'loss.y2012) as sum_loss\ FROM loss_gt_50 loss\ GROUP BY iso), gain as (SELECT g.iso, SUM(y2001_y2012) as sum_gain\ FROM countries_gain g, loss_gt_50 loss\ WHERE loss.iso = g.iso\ GROUP BY g.iso), ratio as ('; sql += 'SELECT c.iso, c.name, c.enabled, loss.sum_loss as loss, gain.sum_gain as gain, loss.sum_loss/gain.sum_gain as ratio\ FROM loss, gain, gfw2_countries c\ WHERE sum_gain IS NOT null\ AND NOT sum_gain = 0\ AND c.iso = gain.iso\ AND c.iso = loss.iso\ ORDER BY loss.sum_loss DESC\ LIMIT 50) '; sql += 'SELECT *\ FROM ratio\ WHERE ratio IS NOT null\ ORDER BY ratio DESC'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows; var log_m = 50; var y_scale = d3.scale.linear() .range([h, 0]) .domain([0, d3.max(data, function(d) { return d.gain; })]); var x_scale = d3.scale.linear() .range([m, w-m]) .domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]); var x_log_scale = d3.scale.log() .range([m, w-m]) .domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]); var y_log_scale = d3.scale.log() .range([h-log_m, m]) .domain([d3.min(data, function(d) { return d.gain; }), d3.max(data, function(d) { return d.gain; })]); var r_scale = d3.scale.linear() .range(['yellow', 'red']) .domain([0, d3.max(data, function(d) { return d.ratio; })]); that.linearRegressionLine(svg, json, x_scale, y_scale); // circles w/ magic numbers :( var circle_attr = { 'cx': function(d) { return d.loss >= 1 ? x_log_scale(d.loss) : m; }, 'cy': function(d) { return d.gain >= 1 ? y_log_scale(d.gain) : h-log_m; }, 'r': '5', 'name': function(d) { return d.name; }, 'class': function(d) { return d.enabled ? 'ball ball_link' : 'ball ball_nolink'; } }; var data_ = [], data_link_ = [], exclude = ['Saint Barthélemy', 'Saint Kitts and Nevis', 'Saint Pierre and Miquelon', 'Virgin Islands', 'Oman', 'Gibraltar', 'Saudi Arabia', 'French Polynesia', 'Samoa', 'Western Sahara', 'United Arab Emirates']; _.each(data, function(row) { if (!_.contains(exclude, row.name)) { if (row.enabled === true) { data_link_.push(row); } else { data_.push(row); } } }); var circles_link = svg.selectAll('circle.ball_link') .data(data_link_) .enter() .append('a') .attr('xlink:href', function(d) { return '/country/' + d.iso }) .attr('target', '_blank') .append('svg:circle') .attr(circle_attr) .style('fill', function(d) { return r_scale(d.ratio); }) .style('filter', 'url(#shadow)') .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', '5') .style('opacity', .8); that.tooltip.style('visibility', 'hidden'); }); var circles = svg.selectAll('circle.ball_nolink') .data(data_) .enter() .append('svg:circle') .attr(circle_attr) .style('filter', 'url(#shadow)') .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', '5') .style('opacity', .8); that.tooltip.style('visibility', 'hidden'); }); }); } else if (this.model.get('graph') === 'domains') { this._showYears(); var sql = 'SELECT name, '; for(var y = 2001; y < 2012; y++) { sql += 'y'+y+', ' } sql += 'y2012, GREATEST(' for(var y = 2001; y < 2012; y++) { sql += 'y'+y+', ' } sql += 'y2012) as max\ FROM countries_domains'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) { var data = json.rows; var r_scale = d3.scale.linear() .range([5, 30]) // max ball radius .domain([0, d3.max(data, function(d) { return d.max; })]) for(var j = 0; j < data.length; j++) { var data_ = [], domain = ''; _.each(data[j], function(val, key) { if (key !== 'max') { if (key === 'name') { domain = val.toLowerCase(); } else { data_.push({ 'year': key.replace('y',''), 'value': val }); } } }); svg.append('text') .attr('class', 'label') .attr('id', 'label_'+domain) .text(domain) .attr('x', function() { var l = x_scale(2002) - $(this).width()/2; return l; }) .attr('y', (h/5)*(j+.6)); var circle_attr = { 'cx': function(d, i) { return x_scale(2001 + i); }, 'cy': function(d) { return (h/5)*(j+1); }, 'r': function(d) { return r_scale(d.value); }, 'class': function(d) { return 'ball'; } }; svg.selectAll('circle.domain_'+domain) .data(data_) .enter() .append('svg:circle') .attr(circle_attr) .attr('data-slug', domain) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .style('fill', function(d) { return config.GRAPHCOLORS[domain]; }) .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d) + 2; }) .style('opacity', 1); var t = $(this).offset().top - 100, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2, slug = $(this).attr('data-slug'); that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip') .attr('data-slug', 'tooltip') .style('color', function() { if (slug === 'subtropical') { return '#FFC926' } else { return config.GRAPHCOLORS[slug]; } }); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d) + 2; }) .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2, slug = $(this).attr('data-slug'); that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip') .attr('data-slug', 'tooltip') .style('color', function() { if (domain === 'subtropical') { return config.GRAPHCOLORS[domain]; } }); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d); }) .style('opacity', .8); that.tooltip .style('color', '') .style('visibility', 'hidden'); }); } }); } }, linearRegressionLine: function(svg, dataset, x_log_scale, y_log_scale) { var that = this; // linear regresion line var lr_line = ss.linear_regression() .data(dataset.rows.map(function(d) { return [d.loss, d.gain]; })) .line(); var line = d3.svg.line() .x(x_log_scale) .y(function(d) { return that.y_log_scale(lr_line(d));} ) var x0 = x_log_scale.domain()[0]; var x1 = x_log_scale.domain()[1]; var lr = svg.selectAll('.linear_regression').data([0]); var attrs = { "x1": x_log_scale(x0), "y1": y_log_scale(lr_line(x0)), "x2": x_log_scale(x1), "y2": y_log_scale(lr_line(x1)), "stroke-width": 1.3, "stroke": "white", "stroke-dasharray": "7,5" }; lr.enter() .append("line") .attr('class', 'linear_regression') .attr(attrs); lr.transition().attr(attrs); } }); gfw.ui.view.CountriesEmbedShow = cdb.core.View.extend({ el: document.body, events: { 'click .forma_dropdown-link': '_openDropdown', 'click .hansen_dropdown-link': '_openDropdown', 'click .hansen_dropdown-menu a': '_redrawCircle' }, initialize: function() { this.iso = this.options.iso; this._initViews(); this._initHansenDropdown(); }, _initViews: function() { this._drawCircle('forma', 'lines', { iso: this.iso }); this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: 'loss' }); }, _initFormaDropdown: function() { $('.forma_dropdown-link').qtip({ show: 'click', hide: { event: 'click unfocus' }, content: { text: $('.forma_dropdown-menu') }, position: { my: 'bottom right', at: 'top right', target: $('.forma_dropdown-link'), adjust: { x: -10 } }, style: { tip: { corner: 'bottom right', mimic: 'bottom center', border: 1, width: 10, height: 6 } } }); }, _initHansenDropdown: function() { this.dropdown = $('.hansen_dropdown-link').qtip({ show: 'click', hide: { event: 'click unfocus' }, content: { text: $('.hansen_dropdown-menu') }, position: { my: 'top right', at: 'bottom right', target: $('.hansen_dropdown-link'), adjust: { x: 10 } }, style: { tip: { corner: 'top right', mimic: 'top center', border: 1, width: 10, height: 6 } } }); }, _openDropdown: function(e) { e.preventDefault(); }, _redrawCircle: function(e) { e.preventDefault(); var dataset = $(e.target).attr('data-slug'), subtitle = $(e.target).text(); var api = this.dropdown.qtip('api'); api.hide(); $('.hansen_dropdown-link').html(subtitle); if(dataset === 'countries_gain') { this._drawCircle('forest_loss', 'comp', { iso: this.iso }); } else { this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: dataset }); } }, _drawCircle: function(id, type, options) { var that = this; var $graph = $('.'+id), $amount = $('.'+id+' .graph-amount'), $date = $('.'+id+' .graph-date'), $coming_soon = $('.'+id+' .coming_soon'), $action = $('.'+id+' .action'); $('.graph.'+id+' .frame_bkg').empty(); $graph.addClass('ghost'); $amount.html(''); $date.html(''); $coming_soon.hide(); var width = options.width || 256, height = options.height || width, h = 100, // maxHeight radius = width / 2; var graph = d3.select('.graph.'+id+' .frame_bkg') .append('svg:svg') .attr('class', type) .attr('width', width) .attr('height', height); var dashedLines = [ { x1:17, y:height/4, x2:239, color: '#ccc' }, { x1:0, y:height/2, x2:width, color: '#ccc' }, { x1:17, y:3*height/4, x2:239, color: '#ccc' } ]; // Adds the dotted lines _.each(dashedLines, function(line) { graph.append('svg:line') .attr('x1', line.x1) .attr('y1', line.y) .attr('x2', line.x2) .attr('y2', line.y) .style('stroke-dasharray', '2,2') .style('stroke', line.color); }); var sql = ["SELECT date_trunc('month', date) as date, COUNT(*) as alerts", 'FROM forma_api', "WHERE iso = '"+options.iso+"'", "GROUP BY date_trunc('month', date)", "ORDER BY date_trunc('month', date) ASC"].join(' '); if (type === 'lines') { d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) { if(json && json.rows.length > 0) { $graph.removeClass('ghost'); $action.removeClass('disabled'); that._initFormaDropdown(); var data = json.rows.slice(1, json.rows.length - 1); } else { $coming_soon.show(); return; } var x_scale = d3.scale.linear() .domain([0, data.length - 1]) .range([0, width - 80]); var max = d3.max(data, function(d) { return parseFloat(d.alerts); }); if (max === d3.min(data, function(d) { return parseFloat(d.alerts); })) { h = h/2; } var y_scale = d3.scale.linear() .domain([0, max]) .range([0, h]); var line = d3.svg.line() .x(function(d, i) { return x_scale(i); }) .y(function(d, i) { return h - y_scale(d.alerts); }) .interpolate('basis'); var marginLeft = 40, marginTop = radius - h/2; $amount.html('<span>'+formatNumber(data[data.length - 1].alerts)+'</span>'); var date = new Date(data[data.length - 1].date), form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear(); $date.html(form_date); graph.append('svg:path') .attr('transform', 'translate(' + marginLeft + ',' + marginTop + ')') .attr('d', line(data)) .on('mousemove', function(d) { var index = Math.round(x_scale.invert(d3.mouse(this)[0])); if (data[index]) { // if there's data $amount.html('<span>'+formatNumber(data[index].alerts)+'</span>'); var date = new Date(data[index].date), form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear(); $date.html(form_date); var cx = d3.mouse(this)[0] + marginLeft; var cy = h - y_scale(data[index].alerts) + marginTop; graph.select('.forma_marker') .attr('cx', cx) .attr('cy', cy); } }); graph.append('svg:circle') .attr('class', 'forma_marker') .attr('cx', -10000) .attr('cy',100) .attr('r', 5); }); } else if (type === 'bars') { var sql = "SELECT "; if (options.dataset === 'loss') { sql += "year, loss_gt_0 loss FROM umd WHERE iso='"+options.iso+"'"; } else if (options.dataset === 'extent') { sql += "year, extent_gt_25 extent FROM umd WHERE iso='"+options.iso+"'"; } d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) { if(json) { $graph.removeClass('ghost'); var data = json.rows; } else { $coming_soon.show(); return; } var data_ = []; _.each(data, function(val, key) { if (val.year >= 2001) { data_.push({ 'year': val.year, 'value': eval('val.'+options.dataset) }); } }); $amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>'); $date.html('Hectares in ' + data_[data_.length - 1].year); var marginLeft = 40, marginTop = radius - h/2 + 5; var y_scale = d3.scale.linear() .domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })]) .range([height, marginTop*2]); var barWidth = (width - 80) / data_.length; var bar = graph.selectAll('g') .data(data_) .enter() .append('g') .attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ','+ -marginTop+')'; }); bar.append('svg:rect') .attr('class', function(d, i) { if(i === 11) { // last year index return 'last bar' } else { return 'bar' } }) .attr('y', function(d) { return y_scale(d.value); }) .attr('height', function(d) { return height - y_scale(d.value); }) .attr('width', barWidth - 1) .on('mouseover', function(d) { d3.selectAll('.bar').style('opacity', '.5'); d3.select(this).style('opacity', '1'); $amount.html('<span>'+formatNumber(parseInt(d.value, 10))+'</span>'); $date.html('Hectares in ' + d.year); }); }); } else if (type === 'comp') { var sql = "SELECT iso, sum(umd.loss_gt_0) loss, max(umd.gain) gain FROM umd WHERE iso='"+options.iso+"' GROUP BY iso"; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { if(json) { $graph.removeClass('ghost'); var data = json.rows[0]; } else { $coming_soon.show(); return; } var data_ = [{ 'key': 'Tree cover gain', 'value': data.gain }, { 'key': 'Tree cover loss', 'value': data.loss }]; $amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>'); $date.html('Ha '+data_[data_.length - 1].key); var barWidth = (width - 80) / 12; var marginLeft = 40 + barWidth*5, marginTop = radius - h/2 + 5; var y_scale = d3.scale.linear() .domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })]) .range([height, marginTop*2]); var bar = graph.selectAll('g') .data(data_) .enter() .append('g') .attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ',' + -marginTop + ')'; }); bar.append('svg:rect') .attr('class', function(d, i) { if (i === 1) { // last bar index return 'last bar' } else { return 'bar' } }) .attr('y', function(d) { return y_scale(d.value); }) .attr('height', function(d) { return height - y_scale(d.value); }) .attr('width', barWidth - 1) .style('fill', '#FFC926') .style('shape-rendering', 'crispEdges') .on('mouseover', function(d) { d3.selectAll('.bar').style('opacity', '.5'); d3.select(this).style('opacity', '1'); $amount.html('<span>'+formatNumber(parseFloat(d.value).toFixed(1))+'</span>'); $date.html('Ha '+d.key); }); }); } } });
declare module 'fast-memoize' { declare type Cache<K, V> = { get: (key: K) => V, set: (key: K, value: V) => void, has: (key: K) => boolean } declare type Options = { cache?: Cache<*, *>; serializer?: (...args: any[]) => any; strategy?: <T>(fn: T, options?: Options) => T; } declare module.exports: <T>(fn: T, options?: Options) => T; }
angular.module('ualib.imageCarousel', ['angular-carousel']) .constant('VIEW_IMAGES_URL', '//wwwdev2.lib.ua.edu/erCarousel/api/slides/active') .factory('imageCarouselFactory', ['$http', 'VIEW_IMAGES_URL', function imageCarouselFactory($http, url){ return { getData: function(){ return $http({method: 'GET', url: url, params: {}}); } }; }]) .controller('imageCarouselCtrl', ['$scope', '$q', 'imageCarouselFactory', function imageCarouselCtrl($scope, $q, imageCarouselFactory){ $scope.slides = null; function loadImages(slides, i, len, deferred){ i = i ? i : 0; len = len ? len : slides.length; deferred = deferred ? deferred : $q.defer(); if (len < 1){ deferred.resolve(slides); } else{ var image = new Image(); image.onload = function(){ slides[i].styles = 'url('+this.src+')'; slides[i].image = this; if (i+1 === len){ deferred.resolve(slides); } else { i++; loadImages(slides, i, len, deferred); } }; image.src = slides[i].image; } return deferred.promise; } imageCarouselFactory.getData() .success(function(data) { loadImages(data.slides).then(function(slides){ $scope.slides = slides; }); }) .error(function(data, status, headers, config) { console.log(data); }); }]) .directive('ualibImageCarousel', [ function() { return { restrict: 'AC', controller: 'imageCarouselCtrl', link: function(scope, elm, attrs, Ctrl){ var toggleLock = false; scope.isLocked = false; scope.pause = function(){ toggleLock = true; scope.isLocked = true; }; scope.play = function(){ toggleLock = false; scope.isLocked = false; }; scope.mouseToggle = function(){ if (!toggleLock){ scope.isLocked = !scope.isLocked; } }; } }; }]);
import { ListWrapper } from 'angular2/src/facade/collection'; import { stringify, isBlank } from 'angular2/src/facade/lang'; import { BaseException, WrappedException } from 'angular2/src/facade/exceptions'; function findFirstClosedCycle(keys) { var res = []; for (var i = 0; i < keys.length; ++i) { if (ListWrapper.contains(res, keys[i])) { res.push(keys[i]); return res; } else { res.push(keys[i]); } } return res; } function constructResolvingPath(keys) { if (keys.length > 1) { var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var tokenStrs = reversed.map(k => stringify(k.token)); return " (" + tokenStrs.join(' -> ') + ")"; } else { return ""; } } /** * Base class for all errors arising from misconfigured providers. */ export class AbstractProviderError extends BaseException { constructor(injector, key, constructResolvingMessage) { super("DI Exception"); this.keys = [key]; this.injectors = [injector]; this.constructResolvingMessage = constructResolvingMessage; this.message = this.constructResolvingMessage(this.keys); } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); this.message = this.constructResolvingMessage(this.keys); } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the * {@link Injector} does not have a {@link Provider} for {@link Key}. * * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview)) * * ```typescript * class A { * constructor(b:B) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` */ export class NoProviderError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { var first = stringify(ListWrapper.first(keys).token); return `No provider for ${first}!${constructResolvingPath(keys)}`; }); } } /** * Thrown when dependencies form a cycle. * * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info)) * * ```typescript * var injector = Injector.resolveAndCreate([ * provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}), * provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]}) * ]); * * expect(() => injector.get("one")).toThrowError(); * ``` * * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed. */ export class CyclicDependencyError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`; }); } } /** * Thrown when a constructing type returns with an Error. * * The `InstantiationError` class contains the original error plus the dependency graph which caused * this object to be instantiated. * * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview)) * * ```typescript * class A { * constructor() { * throw new Error('message'); * } * } * * var injector = Injector.resolveAndCreate([A]); * try { * injector.get(A); * } catch (e) { * expect(e instanceof InstantiationError).toBe(true); * expect(e.originalException.message).toEqual("message"); * expect(e.originalStack).toBeDefined(); * } * ``` */ export class InstantiationError extends WrappedException { constructor(injector, originalException, originalStack, key) { super("DI Exception", originalException, originalStack, null); this.keys = [key]; this.injectors = [injector]; } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); } get wrapperMessage() { var first = stringify(ListWrapper.first(this.keys).token); return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`; } get causeKey() { return this.keys[0]; } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector} * creation. * * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview)) * * ```typescript * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError(); * ``` */ export class InvalidProviderError extends BaseException { constructor(provider) { super("Invalid provider - only instances of Provider and Type are allowed, got: " + provider.toString()); } } /** * Thrown when the class has no annotation information. * * Lack of annotation information prevents the {@link Injector} from determining which dependencies * need to be injected into the constructor. * * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview)) * * ```typescript * class A { * constructor(b) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` * * This error is also thrown when the class not marked with {@link Injectable} has parameter types. * * ```typescript * class B {} * * class A { * constructor(b:B) {} // no information about the parameter types of A is available at runtime. * } * * expect(() => Injector.resolveAndCreate([A,B])).toThrowError(); * ``` */ export class NoAnnotationError extends BaseException { constructor(typeOrFunc, params) { super(NoAnnotationError._genMessage(typeOrFunc, params)); } static _genMessage(typeOrFunc, params) { var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; if (isBlank(parameter) || parameter.length == 0) { signature.push('?'); } else { signature.push(parameter.map(stringify).join(' ')); } } return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; } } /** * Thrown when getting an object by index. * * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview)) * * ```typescript * class A {} * * var injector = Injector.resolveAndCreate([A]); * * expect(() => injector.getAt(100)).toThrowError(); * ``` */ export class OutOfBoundsError extends BaseException { constructor(index) { super(`Index ${index} is out-of-bounds.`); } } // TODO: add a working example after alpha38 is released /** * Thrown when a multi provider and a regular provider are bound to the same token. * * ### Example * * ```typescript * expect(() => Injector.resolveAndCreate([ * new Provider("Strings", {useValue: "string1", multi: true}), * new Provider("Strings", {useValue: "string2", multi: false}) * ])).toThrowError(); * ``` */ export class MixingMultiProvidersWithRegularProvidersError extends BaseException { constructor(provider1, provider2) { super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + provider2.toString()); } } //# sourceMappingURL=exceptions.js.map
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDescription); } framework.addJavaScriptHelp("help", "substring, fileName", "output all the helper functions whose name contains the given 'substring'"); function help(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, false), fileName); } else if (arguments.length > 0) { write(getHelp(substring, false)); } else { write(getHelp("", false)); } } framework.addJavaScriptHelp("apropos", "substring, fileName", "output all the helper functions whose name or description contains the given 'substring'"); function apropos(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, true), fileName); } else if (arguments.length > 0) { write(getHelp(substring, true)); } else { write(getHelp("", true)); } } framework.addJavaScriptHelp("helpRegex", "regex, fileName", "output all helper functions whose name matches 'regex'"); function helpRegex(regex, fileName) { if (arguments.length > 1) { write(framework.getJavaScriptHelp(regex, false), fileName); } else if (arguments.length > 0) { write(framework.getJavaScriptHelp(regex, false)); } }
FullCalendar.globalLocales.push(function () { 'use strict'; var it = { code: 'it', week: { dow: 1, // Monday is the first day of the week. doy: 4, // The week that contains Jan 4th is the first week of the year. }, buttonText: { prev: 'Prec', next: 'Succ', today: 'Oggi', month: 'Mese', week: 'Settimana', day: 'Giorno', list: 'Agenda', }, weekText: 'Sm', allDayText: 'Tutto il giorno', moreLinkText(n) { return '+altri ' + n }, noEventsText: 'Non ci sono eventi da visualizzare', }; return it; }());
/* @flow */ /*eslint-disable no-undef, no-unused-vars, no-console*/ import _, { compose, pipe, curry, filter, find, isNil, repeat, replace, zipWith } from "ramda"; import { describe, it } from 'flow-typed-test'; const ns: Array<number> = [1, 2, 3, 4, 5]; const ss: Array<string> = ["one", "two", "three", "four"]; const obj: { [k: string]: number } = { a: 1, c: 2 }; const objMixed: { [k: string]: mixed } = { a: 1, c: "d" }; const os: Array<{ [k: string]: * }> = [{ a: 1, c: "d" }, { b: 2 }]; const str: string = "hello world"; // Math { const partDiv: (a: number) => number = _.divide(6); const div: number = _.divide(6, 2); //$FlowExpectedError const div2: number = _.divide(6, true); } // String { const ss: Array<string | void> = _.match(/h/, "b"); describe('replace', () => { it('should supports replace by string', () => { const r1: string = replace(",", "|", "b,d,d"); const r2: string = replace(",")("|", "b,d,d"); const r3: string = replace(",")("|")("b,d,d"); const r4: string = replace(",", "|")("b,d,d"); }); it('should supports replace by RegExp', () => { const r1: string = replace(/[,]/, "|", "b,d,d"); const r2: string = replace(/[,]/)("|", "b,d,d"); const r3: string = replace(/[,]/)("|")("b,d,d"); const r4: string = replace(/[,]/, "|")("b,d,d"); }); it('should supports replace by RegExp with replacement fn', () => { const fn = (match: string, g1: string): string => g1; const r1: string = replace(/([,])d/, fn, "b,d,d"); const r2: string = replace(/([,])d/)(fn, "b,d,d"); const r3: string = replace(/([,])d/)(fn)("b,d,d"); const r4: string = replace(/([,])d/, fn)("b,d,d"); }); }); const ss2: Array<string> = _.split(",", "b,d,d"); const ss1: boolean = _.test(/h/, "b"); const s: string = _.trim("s"); const x: string = _.head("one"); const sss: string = _.concat("H", "E"); const sss1: string = _.concat("H")("E"); const ssss: string = _.drop(1, "EF"); const ssss1: string = _.drop(1)("E"); const ssss2: string = _.dropLast(1, "EF"); const ys: string = _.nth(2, "curry"); const ys1: string = _.nth(2)("curry"); } //Type { const x: boolean = _.is(Number, 1); const x1: boolean = isNil(1); // should refine type const x1a: ?{ a: number } = { a: 1 }; //$FlowExpectedError x1a.a; if (!isNil(x1a)) { x1a.a; } const x2: boolean = _.propIs(1, "num", { num: 1 }); }
'use strict'; exports.up = function (knex) { return knex.schema.createTable('migration_test_trx_1', function (t) { t.increments(); t.string('name'); }); }; exports.down = function (knex) { return knex.schema.dropTable('migration_test_trx_1'); };
/** * @author mrdoob / http://mrdoob.com/ * @author bhouston / http://exocortex.com/ */ ( function ( THREE ) { THREE.Raycaster = function ( origin, direction, near, far ) { this.ray = new THREE.Ray( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.lengthSq() > 0 ) { this.ray.direction.normalize(); } this.near = near || 0; this.far = far || Infinity; }; var sphere = new THREE.Sphere(); var localRay = new THREE.Ray(); var facePlane = new THREE.Plane(); var intersectPoint = new THREE.Vector3(); var matrixPosition = new THREE.Vector3(); var inverseMatrix = new THREE.Matrix4(); var descSort = function ( a, b ) { return a.distance - b.distance; }; var intersectObject = function ( object, raycaster, intersects ) { if ( object instanceof THREE.Particle ) { matrixPosition.getPositionFromMatrix( object.matrixWorld ); var distance = raycaster.ray.distanceToPoint( matrixPosition ); if ( distance > object.scale.x ) { return intersects; } intersects.push( { distance: distance, point: object.position, face: null, object: object } ); } else if ( object instanceof THREE.Mesh ) { // Checking boundingSphere distance to ray matrixPosition.getPositionFromMatrix( object.matrixWorld ); sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() ); if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) { return intersects; } // Checking faces var geometry = object.geometry; var vertices = geometry.vertices; var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial; var objectMaterials = isFaceMaterial === true ? object.material.materials : null; var side = object.material.side; var a, b, c, d; var precision = raycaster.precision; object.matrixRotationWorld.extractRotation( object.matrixWorld ); inverseMatrix.getInverse( object.matrixWorld ); localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix ); for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) { var face = geometry.faces[ f ]; var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material; if ( material === undefined ) continue; facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] ); var planeDistance = localRay.distanceToPlane( facePlane ); // bail if raycaster and plane are parallel if ( Math.abs( planeDistance ) < precision ) continue; // if negative distance, then plane is behind raycaster if ( planeDistance < 0 ) continue; // check if we hit the wrong side of a single sided face side = material.side; if( side !== THREE.DoubleSide ) { var planeSign = localRay.direction.dot( facePlane.normal ); if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue; } // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue; intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy if ( face instanceof THREE.Face3 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue; } else if ( face instanceof THREE.Face4 ) { a = vertices[ face.a ]; b = vertices[ face.b ]; c = vertices[ face.c ]; d = vertices[ face.d ]; if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) && ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue; } else { // This is added because if we call out of this if/else group when none of the cases // match it will add a point to the intersection list erroneously. throw Error( "face type not supported" ); } intersects.push( { distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't point: raycaster.ray.at( planeDistance ), face: face, faceIndex: f, object: object } ); } } }; var intersectDescendants = function ( object, raycaster, intersects ) { var descendants = object.getDescendants(); for ( var i = 0, l = descendants.length; i < l; i ++ ) { intersectObject( descendants[ i ], raycaster, intersects ); } }; // THREE.Raycaster.prototype.precision = 0.0001; THREE.Raycaster.prototype.set = function ( origin, direction ) { this.ray.set( origin, direction ); // normalized ray.direction required for accurate distance calculations if( this.ray.direction.length() > 0 ) { this.ray.direction.normalize(); } }; THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) { var intersects = []; if ( recursive === true ) { intersectDescendants( object, this, intersects ); } intersectObject( object, this, intersects ); intersects.sort( descSort ); return intersects; }; THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) { var intersects = []; for ( var i = 0, l = objects.length; i < l; i ++ ) { intersectObject( objects[ i ], this, intersects ); if ( recursive === true ) { intersectDescendants( objects[ i ], this, intersects ); } } intersects.sort( descSort ); return intersects; }; }( THREE ) );
'use strict'; require('../../modules/es.weak-set'); require('../../modules/esnext.weak-set.from'); var WeakSet = require('../../internals/path').WeakSet; var weakSetfrom = WeakSet.from; module.exports = function from(source, mapFn, thisArg) { return weakSetfrom.call(typeof this === 'function' ? this : WeakSet, source, mapFn, thisArg); };
/** @babel */ /** @jsx etch.dom **/ import etch from 'etch'; export default class WelcomeView { constructor(props) { this.props = props; etch.initialize(this); this.element.addEventListener('click', event => { const link = event.target.closest('a'); if (link && link.dataset.event) { this.props.reporterProxy.sendEvent( `clicked-welcome-${link.dataset.event}-link` ); } }); } didChangeShowOnStartup() { atom.config.set('welcome.showOnStartup', this.checked); } update() {} serialize() { return { deserializer: 'WelcomeView', uri: this.props.uri }; } render() { return ( <div className="welcome"> <div className="welcome-container"> <header className="welcome-header"> <a href="https://atom.io/"> <svg className="welcome-logo" width="330px" height="68px" viewBox="0 0 330 68" version="1.1" > <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" > <g transform="translate(2.000000, 1.000000)"> <g transform="translate(96.000000, 8.000000)" fill="currentColor" > <path d="M185.498,3.399 C185.498,2.417 186.34,1.573 187.324,1.573 L187.674,1.573 C188.447,1.573 189.01,1.995 189.5,2.628 L208.676,30.862 L227.852,2.628 C228.272,1.995 228.905,1.573 229.676,1.573 L230.028,1.573 C231.01,1.573 231.854,2.417 231.854,3.399 L231.854,49.403 C231.854,50.387 231.01,51.231 230.028,51.231 C229.044,51.231 228.202,50.387 228.202,49.403 L228.202,8.246 L210.151,34.515 C209.729,35.148 209.237,35.428 208.606,35.428 C207.973,35.428 207.481,35.148 207.061,34.515 L189.01,8.246 L189.01,49.475 C189.01,50.457 188.237,51.231 187.254,51.231 C186.27,51.231 185.498,50.458 185.498,49.475 L185.498,3.399 L185.498,3.399 Z" /> <path d="M113.086,26.507 L113.086,26.367 C113.086,12.952 122.99,0.941 137.881,0.941 C152.77,0.941 162.533,12.811 162.533,26.225 L162.533,26.367 C162.533,39.782 152.629,51.792 137.74,51.792 C122.85,51.792 113.086,39.923 113.086,26.507 M158.74,26.507 L158.74,26.367 C158.74,14.216 149.89,4.242 137.74,4.242 C125.588,4.242 116.879,14.075 116.879,26.225 L116.879,26.367 C116.879,38.518 125.729,48.491 137.881,48.491 C150.031,48.491 158.74,38.658 158.74,26.507" /> <path d="M76.705,5.155 L60.972,5.155 C60.06,5.155 59.287,4.384 59.287,3.469 C59.287,2.556 60.059,1.783 60.972,1.783 L96.092,1.783 C97.004,1.783 97.778,2.555 97.778,3.469 C97.778,4.383 97.005,5.155 96.092,5.155 L80.358,5.155 L80.358,49.405 C80.358,50.387 79.516,51.231 78.532,51.231 C77.55,51.231 76.706,50.387 76.706,49.405 L76.706,5.155 L76.705,5.155 Z" /> <path d="M0.291,48.562 L21.291,3.05 C21.783,1.995 22.485,1.292 23.75,1.292 L23.891,1.292 C25.155,1.292 25.858,1.995 26.348,3.05 L47.279,48.421 C47.49,48.843 47.56,49.194 47.56,49.546 C47.56,50.458 46.788,51.231 45.803,51.231 C44.961,51.231 44.329,50.599 43.978,49.826 L38.219,37.183 L9.21,37.183 L3.45,49.897 C3.099,50.739 2.538,51.231 1.694,51.231 C0.781,51.231 0.008,50.529 0.008,49.685 C0.009,49.404 0.08,48.983 0.291,48.562 L0.291,48.562 Z M36.673,33.882 L23.749,5.437 L10.755,33.882 L36.673,33.882 L36.673,33.882 Z" /> </g> <g> <path d="M40.363,32.075 C40.874,34.44 39.371,36.77 37.006,37.282 C34.641,37.793 32.311,36.29 31.799,33.925 C31.289,31.56 32.791,29.23 35.156,28.718 C37.521,28.207 39.851,29.71 40.363,32.075" fill="currentColor" /> <path d="M48.578,28.615 C56.851,45.587 58.558,61.581 52.288,64.778 C45.822,68.076 33.326,56.521 24.375,38.969 C15.424,21.418 13.409,4.518 19.874,1.221 C22.689,-0.216 26.648,1.166 30.959,4.629" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M7.64,39.45 C2.806,36.94 -0.009,33.915 0.154,30.79 C0.531,23.542 16.787,18.497 36.462,19.52 C56.137,20.544 71.781,27.249 71.404,34.497 C71.241,37.622 68.127,40.338 63.06,42.333" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> <path d="M28.828,59.354 C23.545,63.168 18.843,64.561 15.902,62.653 C9.814,58.702 13.572,42.102 24.296,25.575 C35.02,9.048 48.649,-1.149 54.736,2.803 C57.566,4.639 58.269,9.208 57.133,15.232" stroke="currentColor" stroke-width="3.08" stroke-linecap="round" /> </g> </g> </g> </svg> <h1 className="welcome-title"> A hackable text editor for the 21<sup>st</sup> Century </h1> </a> </header> <section className="welcome-panel"> <p>For help, please visit</p> <ul> <li> The{' '} <a href="https://www.atom.io/docs" dataset={{ event: 'atom-docs' }} > Atom docs </a>{' '} for Guides and the API reference. </li> <li> The Atom forum at{' '} <a href="https://github.com/atom/atom/discussions" dataset={{ event: 'discussions' }} > Github Discussions </a> </li> <li> The{' '} <a href="https://github.com/atom" dataset={{ event: 'atom-org' }} > Atom org </a> . This is where all GitHub-created Atom packages can be found. </li> </ul> </section> <section className="welcome-panel"> <label> <input className="input-checkbox" type="checkbox" checked={atom.config.get('welcome.showOnStartup')} onchange={this.didChangeShowOnStartup} /> Show Welcome Guide when opening Atom </label> </section> <footer className="welcome-footer"> <a href="https://atom.io/" dataset={{ event: 'footer-atom-io' }}> atom.io </a>{' '} <span className="text-subtle">×</span>{' '} <a className="icon icon-octoface" href="https://github.com/" dataset={{ event: 'footer-octocat' }} /> </footer> </div> </div> ); } getURI() { return this.props.uri; } getTitle() { return 'Welcome'; } isEqual(other) { return other instanceof WelcomeView; } }
'use strict'; angular.module('sw.plugin.split', ['sw.plugins']) .factory('split', function ($q) { return { execute: execute }; function execute (url, swagger) { var deferred = $q.defer(); if (swagger && swagger.swagger && !swagger.tags) { var tags = {}; angular.forEach(swagger.paths, function (path, key) { var t = key.replace(/^\/?([^\/]+).*$/g, '$1'); tags[t] = true; angular.forEach(path, function (method) { if (!method.tags || !method.tags.length) { method.tags = [t]; } }); }); swagger.tags = []; Object.keys(tags).forEach(function (tag) { swagger.tags.push({name: tag}); }); } deferred.resolve(true); return deferred.promise; } }) .run(function (plugins, split) { plugins.add(plugins.BEFORE_PARSE, split); });
/*----------------------------------------------------------------------------------- /* /* Main JS /* -----------------------------------------------------------------------------------*/ (function($) { /*---------------------------------------------------- */ /* Preloader ------------------------------------------------------ */ $(window).load(function() { // will first fade out the loading animation $("#status").fadeOut("slow"); // will fade out the whole DIV that covers the website. $("#preloader").delay(500).fadeOut("slow").remove(); $('.js #hero .hero-image img').addClass("animated fadeInUpBig"); $('.js #hero .buttons a.trial').addClass("animated shake"); }) /*---------------------------------------------------- */ /* Mobile Menu ------------------------------------------------------ */ var toggle_button = $("<a>", { id: "toggle-btn", html : "Menu", title: "Menu", href : "#" } ); var nav_wrap = $('nav#nav-wrap') var nav = $("ul#nav"); /* id JS is enabled, remove the two a.mobile-btns and dynamically prepend a.toggle-btn to #nav-wrap */ nav_wrap.find('a.mobile-btn').remove(); nav_wrap.prepend(toggle_button); toggle_button.on("click", function(e) { e.preventDefault(); nav.slideToggle("fast"); }); if (toggle_button.is(':visible')) nav.addClass('mobile'); $(window).resize(function(){ if (toggle_button.is(':visible')) nav.addClass('mobile'); else nav.removeClass('mobile'); }); $('ul#nav li a').on("click", function(){ if (nav.hasClass('mobile')) nav.fadeOut('fast'); }); /*----------------------------------------------------*/ /* FitText Settings ------------------------------------------------------ */ setTimeout(function() { $('h1.responsive-headline').fitText(1.2, { minFontSize: '25px', maxFontSize: '40px' }); }, 100); /*----------------------------------------------------*/ /* Smooth Scrolling ------------------------------------------------------ */ $('.smoothscroll').on('click', function (e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 800, 'swing', function () { window.location.hash = target; }); }); /*----------------------------------------------------*/ /* Highlight the current section in the navigation bar ------------------------------------------------------*/ var sections = $("section"), navigation_links = $("#nav-wrap a"); sections.waypoint( { handler: function(event, direction) { var active_section; active_section = $(this); if (direction === "up") active_section = active_section.prev(); var active_link = $('#nav-wrap a[href="#' + active_section.attr("id") + '"]'); navigation_links.parent().removeClass("current"); active_link.parent().addClass("current"); }, offset: '35%' }); /*----------------------------------------------------*/ /* FitVids /*----------------------------------------------------*/ $(".fluid-video-wrapper").fitVids(); /*----------------------------------------------------*/ /* Waypoints Animations ------------------------------------------------------ */ $('.js .design').waypoint(function() { $('.js .design .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .responsive').waypoint(function() { $('.js .responsive .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .cross-browser').waypoint(function() { $('.js .cross-browser .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js .video').waypoint(function() { $('.js .video .feature-media').addClass( 'animated pulse' ); }, { offset: 'bottom-in-view' }); $('.js #subscribe').waypoint(function() { $('.js #subscribe input[type="email"]').addClass( 'animated fadeInLeftBig show' ); $('.js #subscribe input[type="submit"]').addClass( 'animated fadeInRightBig show' ); }, { offset: 'bottom-in-view' }); /*----------------------------------------------------*/ /* Flexslider /*----------------------------------------------------*/ $('.flexslider').flexslider({ namespace: "flex-", controlsContainer: ".flex-container", animation: 'slide', controlNav: true, directionNav: false, smoothHeight: true, slideshowSpeed: 7000, animationSpeed: 600, randomize: false, }); /*----------------------------------------------------*/ /* ImageLightbox /*----------------------------------------------------*/ if($("html").hasClass('cssanimations')) { var activityIndicatorOn = function() { $( '<div id="imagelightbox-loading"><div></div></div>' ).appendTo( 'body' ); }, activityIndicatorOff = function() { $( '#imagelightbox-loading' ).remove(); }, overlayOn = function() { $( '<div id="imagelightbox-overlay"></div>' ).appendTo( 'body' ); }, overlayOff = function() { $( '#imagelightbox-overlay' ).remove(); }, closeButtonOn = function( instance ) { $( '<a href="#" id="imagelightbox-close" title="close"><i class="fa fa fa-times"></i></a>' ).appendTo( 'body' ).on( 'click touchend', function(){ $( this ).remove(); instance.quitImageLightbox(); return false; }); }, closeButtonOff = function() { $( '#imagelightbox-close' ).remove(); }, captionOn = function() { var description = $( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' ).attr( 'alt' ); if( description.length > 0 ) $( '<div id="imagelightbox-caption">' + description + '</div>' ).appendTo( 'body' ); }, captionOff = function() { $( '#imagelightbox-caption' ).remove(); }; var instanceA = $( 'a[data-imagelightbox="a"]' ).imageLightbox( { onStart: function() { overlayOn(); closeButtonOn( instanceA ); }, onEnd: function() { overlayOff(); captionOff(); closeButtonOff(); activityIndicatorOff(); }, onLoadStart: function() { captionOff(); activityIndicatorOn(); }, onLoadEnd: function() { captionOn(); activityIndicatorOff(); } }); } else { /*----------------------------------------------------*/ /* prettyPhoto for old IE /*----------------------------------------------------*/ $("#screenshots").find(".item-wrap a").attr("rel","prettyPhoto[pp_gal]"); $("a[rel^='prettyPhoto']").prettyPhoto( { animation_speed: 'fast', /* fast/slow/normal */ slideshow: false, /* false OR interval time in ms */ autoplay_slideshow: false, /* true/false */ opacity: 0.80, /* Value between 0 and 1 */ show_title: true, /* true/false */ allow_resize: true, /* Resize the photos bigger than viewport. true/false */ default_width: 500, default_height: 344, counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */ theme: 'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */ hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */ wmode: 'opaque', /* Set the flash wmode attribute */ autoplay: true, /* Automatically start videos: True/False */ modal: false, /* If set to true, only the close button will close the window */ overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */ keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */ deeplinking: false, social_tools: false }); } })(jQuery);
/** * @license Highcharts Gantt JS v7.2.0 (2019-09-03) * * CurrentDateIndicator * * (c) 2010-2019 Lars A. V. Cabrera * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/current-date-indicator', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'parts-gantt/CurrentDateIndicator.js', [_modules['parts/Globals.js']], function (H) { /* * * * (c) 2016-2019 Highsoft AS * * Author: Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var addEvent = H.addEvent, Axis = H.Axis, PlotLineOrBand = H.PlotLineOrBand, merge = H.merge, wrap = H.wrap; var defaultConfig = { /** * Show an indicator on the axis for the current date and time. Can be a * boolean or a configuration object similar to * [xAxis.plotLines](#xAxis.plotLines). * * @sample gantt/current-date-indicator/demo * Current date indicator enabled * @sample gantt/current-date-indicator/object-config * Current date indicator with custom options * * @type {boolean|*} * @default true * @extends xAxis.plotLines * @excluding value * @product gantt * @apioption xAxis.currentDateIndicator */ currentDateIndicator: true, color: '#ccd6eb', width: 2, label: { /** * Format of the label. This options is passed as the fist argument to * [dateFormat](/class-reference/Highcharts#dateFormat) function. * * @type {string} * @default '%a, %b %d %Y, %H:%M' * @product gantt * @apioption xAxis.currentDateIndicator.label.format */ format: '%a, %b %d %Y, %H:%M', formatter: function (value, format) { return H.dateFormat(format, value); }, rotation: 0, style: { fontSize: '10px' } } }; /* eslint-disable no-invalid-this */ addEvent(Axis, 'afterSetOptions', function () { var options = this.options, cdiOptions = options.currentDateIndicator; if (cdiOptions) { cdiOptions = typeof cdiOptions === 'object' ? merge(defaultConfig, cdiOptions) : merge(defaultConfig); cdiOptions.value = new Date(); if (!options.plotLines) { options.plotLines = []; } options.plotLines.push(cdiOptions); } }); addEvent(PlotLineOrBand, 'render', function () { // If the label already exists, update its text if (this.label) { this.label.attr({ text: this.getLabelText(this.options.label) }); } }); wrap(PlotLineOrBand.prototype, 'getLabelText', function (defaultMethod, defaultLabelOptions) { var options = this.options; if (options.currentDateIndicator && options.label && typeof options.label.formatter === 'function') { options.value = new Date(); return options.label.formatter .call(this, options.value, options.label.format); } return defaultMethod.call(this, defaultLabelOptions); }); }); _registerModule(_modules, 'masters/modules/current-date-indicator.src.js', [], function () { }); }));
var dep = require('./dep'); dep('');
(function ($) { $.Redactor.opts.langs['ua'] = { html: 'Код', video: 'Відео', image: 'Зображення', table: 'Таблиця', link: 'Посилання', link_insert: 'Вставити посилання ...', link_edit: 'Edit link', unlink: 'Видалити посилання', formatting: 'Стилі', paragraph: 'Звичайний текст', quote: 'Цитата', code: 'Код', header1: 'Заголовок 1', header2: 'Заголовок 2', header3: 'Заголовок 3', header4: 'Заголовок 4', bold: 'Жирний', italic: 'Похилий', fontcolor: 'Колір тексту', backcolor: 'Заливка тексту', unorderedlist: 'Звичайний список', orderedlist: 'Нумерований список', outdent: 'Зменшити відступ', indent: 'Збільшити відступ', cancel: 'Скасувати', insert: 'Вставити', save: 'Зберегти', _delete: 'Видалити', insert_table: 'Вставити таблицю', insert_row_above: 'Додати рядок зверху', insert_row_below: 'Додати рядок знизу', insert_column_left: 'Додати стовпець ліворуч', insert_column_right: 'Додати стовпець праворуч', delete_column: 'Видалити стовпець', delete_row: 'Видалити рядок', delete_table: 'Видалити таблицю', rows: 'Рядки', columns: 'Стовпці', add_head: 'Додати заголовок', delete_head: 'Видалити заголовок', title: 'Підказка', image_view: 'Завантажити зображення', image_position: 'Обтікання текстом', none: 'ні', left: 'ліворуч', right: 'праворуч', image_web_link: 'Посилання на зображення', text: 'Текст', mailto: 'Ел. пошта', web: 'URL', video_html_code: 'Код відео ролика', file: 'Файл', upload: 'Завантажити', download: 'Завантажити', choose: 'Вибрати', or_choose: 'Або виберіть', drop_file_here: 'Перетягніть файл сюди', align_left: 'По лівому краю', align_center: 'По центру', align_right: 'По правому краю', align_justify: 'Вирівняти текст по ширині', horizontalrule: 'Горизонтальная лінійка', fullscreen: 'На весь екран', deleted: 'Закреслений', anchor: 'Anchor', link_new_tab: 'Open link in new tab', underline: 'Underline', alignment: 'Alignment', filename: 'Name (optional)' }; })( jQuery );
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt $.extend(frappe.model, { docinfo: {}, sync: function(r) { /* docs: extract docs, docinfo (attachments, comments, assignments) from incoming request and set in `locals` and `frappe.model.docinfo` */ var isPlain; if(!r.docs && !r.docinfo) r = {docs:r}; isPlain = $.isPlainObject(r.docs); if(isPlain) r.docs = [r.docs]; if(r.docs) { var last_parent_name = null; for(var i=0, l=r.docs.length; i<l; i++) { var d = r.docs[i]; frappe.model.add_to_locals(d); d.__last_sync_on = new Date(); if(d.doctype==="DocType") { frappe.meta.sync(d); } if(cur_frm && cur_frm.doctype==d.doctype && cur_frm.docname==d.name) { cur_frm.doc = d; } if(d.localname) { frappe.model.new_names[d.localname] = d.name; $(document).trigger('rename', [d.doctype, d.localname, d.name]); delete locals[d.doctype][d.localname]; // update docinfo to new dict keys if(i===0) { frappe.model.docinfo[d.doctype][d.name] = frappe.model.docinfo[d.doctype][d.localname]; frappe.model.docinfo[d.doctype][d.localname] = undefined; } } } if(cur_frm && isPlain) cur_frm.dirty(); } // set docinfo (comments, assign, attachments) if(r.docinfo) { if(r.docs) { var doc = r.docs[0]; } else { if(cur_frm) var doc = cur_frm.doc; } if(doc) { if(!frappe.model.docinfo[doc.doctype]) frappe.model.docinfo[doc.doctype] = {}; frappe.model.docinfo[doc.doctype][doc.name] = r.docinfo; } } return r.docs; }, add_to_locals: function(doc) { if(!locals[doc.doctype]) locals[doc.doctype] = {}; if(!doc.name && doc.__islocal) { // get name (local if required) if(!doc.parentfield) frappe.model.clear_doc(doc); doc.name = frappe.model.get_new_name(doc.doctype); if(!doc.parentfield) frappe.provide("frappe.model.docinfo." + doc.doctype + "." + doc.name); } locals[doc.doctype][doc.name] = doc; // add child docs to locals if(!doc.parentfield) { for(var i in doc) { var value = doc[i]; if($.isArray(value)) { for (var x=0, y=value.length; x < y; x++) { var d = value[x]; if(!d.parent) d.parent = doc.name; frappe.model.add_to_locals(d); } } } } } });
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER' export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
var expect = require('chai').expect; var runner = require('../runner'); describe('nasm runner', function() { describe('.run', function() { it('should handle basic code evaluation (no libc)', function(done) { runner.run({ language: 'nasm', code: [ ' global _start', ' section .text', '_start:', ' mov rax, 1', ' mov rdi, 1', ' mov rsi, message', ' mov rdx, 25', ' syscall', ' mov eax, 60', ' xor rdi, rdi', ' syscall', 'message:', 'db "Hello, Netwide Assembler!", 25' ].join('\n') }, function(buffer) { expect(buffer.stdout).to.equal('Hello, Netwide Assembler!'); done(); }); }); it('should handle basic code evaluation (with libc)', function(done) { runner.run({ language: 'nasm', code: [ ' global main', ' extern puts', ' section .text', 'main:', ' mov rdi, message', ' call puts', ' ret', 'message:', 'db "Netwide Assembler together with LIBC! Let\'s Port Codewars From Rails to THIS! \\m/", 0' ].join('\n') }, function(buffer) { expect(buffer.stdout).to.equal('Netwide Assembler together with LIBC! Let\'s Port Codewars From Rails to THIS! \\m/\n'); done(); }); }); }); });
/** * error handling middleware loosely based off of the connect/errorHandler code. This handler chooses * to render errors using Jade / Express instead of the manual templating used by the connect middleware * sample. This may or may not be a good idea :-) * @param options {object} array of options **/ exports = module.exports = function errorHandler(options) { options = options || {}; // defaults var showStack = options.showStack || options.stack , showMessage = options.showMessage || options.message , dumpExceptions = options.dumpExceptions || options.dump , formatUrl = options.formatUrl; return function errorHandler(err, req, res, next) { res.statusCode = 500; if(dumpExceptions) console.error(err.stack); var app = res.app; if(err instanceof exports.NotFound) { res.render('errors/404', { locals: { title: '404 - Not Found' }, status: 404 }); } else { res.render('errors/500', { locals: { title: 'The Server Encountered an Error' , error: showStack ? err : undefined }, status: 500 }); } }; }; exports.NotFound = function(msg) { this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); }
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.versions.openssl) { console.error('Skipping because node compiled without OpenSSL.'); process.exit(0); } var common = require('../common'); var assert = require('assert'); var fs = require('fs'); var tls = require('tls'); var key = fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'); var cert = fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'); tls.createServer({ key: key, cert: cert }, function(conn) { conn.end(); this.close(); }).listen(0, function() { var options = { port: this.address().port, rejectUnauthorized: true }; tls.connect(options).on('error', common.mustCall(function(err) { assert.equal(err.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'); assert.equal(err.message, 'unable to verify the first certificate'); this.destroy(); })); });
Kanboard.App = function() { this.controllers = {}; }; Kanboard.App.prototype.get = function(controller) { return this.controllers[controller]; }; Kanboard.App.prototype.execute = function() { for (var className in Kanboard) { if (className !== "App") { var controller = new Kanboard[className](this); this.controllers[className] = controller; if (typeof controller.execute === "function") { controller.execute(); } if (typeof controller.listen === "function") { controller.listen(); } if (typeof controller.focus === "function") { controller.focus(); } } } this.focus(); this.datePicker(); this.autoComplete(); this.tagAutoComplete(); }; Kanboard.App.prototype.focus = function() { // Auto-select input fields $(document).on('focus', '.auto-select', function() { $(this).select(); }); // Workaround for chrome $(document).on('mouseup', '.auto-select', function(e) { e.preventDefault(); }); }; Kanboard.App.prototype.datePicker = function() { var bodyElement = $("body"); var dateFormat = bodyElement.data("js-date-format"); var timeFormat = bodyElement.data("js-time-format"); var lang = bodyElement.data("js-lang"); $.datepicker.setDefaults($.datepicker.regional[lang]); $.timepicker.setDefaults($.timepicker.regional[lang]); // Datepicker $(".form-date").datepicker({ showOtherMonths: true, selectOtherMonths: true, dateFormat: dateFormat, constrainInput: false }); // Datetime picker $(".form-datetime").datetimepicker({ dateFormat: dateFormat, timeFormat: timeFormat, constrainInput: false }); }; Kanboard.App.prototype.tagAutoComplete = function() { $(".tag-autocomplete").select2({ tags: true }); }; Kanboard.App.prototype.autoComplete = function() { $(".autocomplete").each(function() { var input = $(this); var field = input.data("dst-field"); var extraFields = input.data("dst-extra-fields"); if ($('#form-' + field).val() === '') { input.parent().find("button[type=submit]").attr('disabled','disabled'); } input.autocomplete({ source: input.data("search-url"), minLength: 1, select: function(event, ui) { $("input[name=" + field + "]").val(ui.item.id); if (extraFields) { var fields = extraFields.split(','); for (var i = 0; i < fields.length; i++) { var fieldName = fields[i].trim(); $("input[name=" + fieldName + "]").val(ui.item[fieldName]); } } input.parent().find("button[type=submit]").removeAttr('disabled'); } }); }); }; Kanboard.App.prototype.hasId = function(id) { return !!document.getElementById(id); }; Kanboard.App.prototype.showLoadingIcon = function() { $("body").append('<span id="app-loading-icon">&nbsp;<i class="fa fa-spinner fa-spin"></i></span>'); }; Kanboard.App.prototype.hideLoadingIcon = function() { $("#app-loading-icon").remove(); };
/* * Should * Copyright(c) 2010-2014 TJ Holowaychuk <[email protected]> * MIT Licensed */ module.exports = function(should, Assertion) { /** * Assert given object is NaN * @name NaN * @memberOf Assertion * @category assertion numbers * @example * * (10).should.not.be.NaN(); * NaN.should.be.NaN(); */ Assertion.add('NaN', function() { this.params = { operator: 'to be NaN' }; this.assert(this.obj !== this.obj); }); /** * Assert given object is not finite (positive or negative) * * @name Infinity * @memberOf Assertion * @category assertion numbers * @example * * (10).should.not.be.Infinity(); * NaN.should.not.be.Infinity(); */ Assertion.add('Infinity', function() { this.params = { operator: 'to be Infinity' }; this.is.a.Number() .and.not.a.NaN() .and.assert(!isFinite(this.obj)); }); /** * Assert given number between `start` and `finish` or equal one of them. * * @name within * @memberOf Assertion * @category assertion numbers * @param {number} start Start number * @param {number} finish Finish number * @param {string} [description] Optional message * @example * * (10).should.be.within(0, 20); */ Assertion.add('within', function(start, finish, description) { this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; this.assert(this.obj >= start && this.obj <= finish); }); /** * Assert given number near some other `value` within `delta` * * @name approximately * @memberOf Assertion * @category assertion numbers * @param {number} value Center number * @param {number} delta Radius * @param {string} [description] Optional message * @example * * (9.99).should.be.approximately(10, 0.1); */ Assertion.add('approximately', function(value, delta, description) { this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description }; this.assert(Math.abs(this.obj - value) <= delta); }); /** * Assert given number above `n`. * * @name above * @alias Assertion#greaterThan * @memberOf Assertion * @category assertion numbers * @param {number} n Margin number * @param {string} [description] Optional message * @example * * (10).should.be.above(0); */ Assertion.add('above', function(n, description) { this.params = { operator: 'to be above ' + n, message: description }; this.assert(this.obj > n); }); /** * Assert given number below `n`. * * @name below * @alias Assertion#lessThan * @memberOf Assertion * @category assertion numbers * @param {number} n Margin number * @param {string} [description] Optional message * @example * * (0).should.be.below(10); */ Assertion.add('below', function(n, description) { this.params = { operator: 'to be below ' + n, message: description }; this.assert(this.obj < n); }); Assertion.alias('above', 'greaterThan'); Assertion.alias('below', 'lessThan'); };
'use strict'; var APPLICATION_JSON = 'application/json'; var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; var JSON_START = /^\[|^\{(?!\{)/; var JSON_ENDS = { '[': /]$/, '{': /}$/ }; var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/; var $httpMinErr = minErr('$http'); var $httpMinErrLegacyFn = function(method) { return function() { throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method); }; }; function serializeValue(v) { if (isObject(v)) { return isDate(v) ? v.toISOString() : toJson(v); } return v; } function $HttpParamSerializerProvider() { /** * @ngdoc service * @name $httpParamSerializer * @description * * Default {@link $http `$http`} params serializer that converts objects to strings * according to the following rules: * * * `{'foo': 'bar'}` results in `foo=bar` * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object) * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element) * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object) * * Note that serializer will sort the request parameters alphabetically. * */ this.$get = function() { return function ngParamSerializer(params) { if (!params) return ''; var parts = []; forEachSorted(params, function(value, key) { if (value === null || isUndefined(value)) return; if (isArray(value)) { forEach(value, function(v, k) { parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v))); }); } else { parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); } }); return parts.join('&'); }; }; } function $HttpParamSerializerJQLikeProvider() { /** * @ngdoc service * @name $httpParamSerializerJQLike * @description * * Alternative {@link $http `$http`} params serializer that follows * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic. * The serializer will also sort the params alphabetically. * * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property: * * ```js * $http({ * url: myUrl, * method: 'GET', * params: myParams, * paramSerializer: '$httpParamSerializerJQLike' * }); * ``` * * It is also possible to set it as the default `paramSerializer` in the * {@link $httpProvider#defaults `$httpProvider`}. * * Additionally, you can inject the serializer and use it explicitly, for example to serialize * form data for submission: * * ```js * .controller(function($http, $httpParamSerializerJQLike) { * //... * * $http({ * url: myUrl, * method: 'POST', * data: $httpParamSerializerJQLike(myData), * headers: { * 'Content-Type': 'application/x-www-form-urlencoded' * } * }); * * }); * ``` * * */ this.$get = function() { return function jQueryLikeParamSerializer(params) { if (!params) return ''; var parts = []; serialize(params, '', true); return parts.join('&'); function serialize(toSerialize, prefix, topLevel) { if (toSerialize === null || isUndefined(toSerialize)) return; if (isArray(toSerialize)) { forEach(toSerialize, function(value, index) { serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']'); }); } else if (isObject(toSerialize) && !isDate(toSerialize)) { forEachSorted(toSerialize, function(value, key) { serialize(value, prefix + (topLevel ? '' : '[') + key + (topLevel ? '' : ']')); }); } else { parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize))); } } }; }; } function defaultHttpResponseTransform(data, headers) { if (isString(data)) { // Strip json vulnerability protection prefix and trim whitespace var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim(); if (tempData) { var contentType = headers('Content-Type'); if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) { data = fromJson(tempData); } } } return data; } function isJsonLike(str) { var jsonStart = str.match(JSON_START); return jsonStart && JSON_ENDS[jsonStart[0]].test(str); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = createMap(), i; function fillInParsed(key, val) { if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } if (isString(headers)) { forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1))); }); } else if (isObject(headers)) { forEach(headers, function(headerVal, headerKey) { fillInParsed(lowercase(headerKey), trim(headerVal)); }); } return parsed; } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { var value = headersObj[lowercase(name)]; if (value === void 0) { value = null; } return value; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers HTTP headers getter fn. * @param {number} status HTTP status code of the response. * @param {(Function|Array.<Function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, status, fns) { if (isFunction(fns)) { return fns(data, headers, status); } forEach(fns, function(fn) { data = fn(data, headers, status); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } /** * @ngdoc provider * @name $httpProvider * @description * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. * */ function $HttpProvider() { /** * @ngdoc property * @name $httpProvider#defaults * @description * * Object containing default values for all {@link ng.$http $http} requests. * * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`} * that will provide the cache for all requests who set their `cache` property to `true`. * If you set the `defaults.cache = false` then only requests that specify their own custom * cache object will be cached. See {@link $http#caching $http Caching} for more information. * * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. * Defaults value is `'XSRF-TOKEN'`. * * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. * * - **`defaults.headers`** - {Object} - Default headers for all $http requests. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on * setting default headers. * - **`defaults.headers.common`** * - **`defaults.headers.post`** * - **`defaults.headers.put`** * - **`defaults.headers.patch`** * * * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function * used to the prepare string representation of request parameters (specified as an object). * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}. * **/ var defaults = this.defaults = { // transform incoming response data transformResponse: [defaultHttpResponseTransform], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', paramSerializer: '$httpParamSerializer' }; var useApplyAsync = false; /** * @ngdoc method * @name $httpProvider#useApplyAsync * @description * * Configure $http service to combine processing of multiple http responses received at around * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in * significant performance improvement for bigger applications that make many HTTP requests * concurrently (common during application bootstrap). * * Defaults to false. If no value is specified, returns the current configured value. * * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window * to load and share the same digest cycle. * * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. **/ this.useApplyAsync = function(value) { if (isDefined(value)) { useApplyAsync = !!value; return this; } return useApplyAsync; }; var useLegacyPromise = true; /** * @ngdoc method * @name $httpProvider#useLegacyPromiseExtensions * @description * * Configure `$http` service to return promises without the shorthand methods `success` and `error`. * This should be used to make sure that applications work without these methods. * * Defaults to true. If no value is specified, returns the current configured value. * * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods. * * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. **/ this.useLegacyPromiseExtensions = function(value) { if (isDefined(value)) { useLegacyPromise = !!value; return this; } return useLegacyPromise; }; /** * @ngdoc property * @name $httpProvider#interceptors * @description * * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} * pre-processing of request or postprocessing of responses. * * These service factories are ordered by request, i.e. they are applied in the same order as the * array, on request, but reverse order, on response. * * {@link ng.$http#interceptors Interceptors detailed info} **/ var interceptorFactories = this.interceptors = []; this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'); /** * Make sure that default param serializer is exposed as a function */ defaults.paramSerializer = isString(defaults.paramSerializer) ? $injector.get(defaults.paramSerializer) : defaults.paramSerializer; /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the * server request. */ var reversedInterceptors = []; forEach(interceptorFactories, function(interceptorFactory) { reversedInterceptors.unshift(isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); /** * @ngdoc service * @kind function * @name $http * @requires ng.$httpBackend * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage * it is important to familiarize yourself with these APIs and the guarantees they provide. * * * ## General usage * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} — * that is used to generate an HTTP request and returns a {@link ng.$q promise}. * * ```js * // Simple GET request example: * $http({ * method: 'GET', * url: '/someUrl' * }).then(function successCallback(response) { * // this callback will be called asynchronously * // when the response is available * }, function errorCallback(response) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * * The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform * functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * - **statusText** – `{string}` – HTTP status text of the response. * * A response status code between 200 and 299 is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * * ## Shortcut methods * * Shortcut methods are also available. All shortcut methods require passing in the URL, and * request data must be passed in for POST/PUT requests. An optional config can be passed as the * last argument. * * ```js * $http.get('/someUrl', config).then(successCallback, errorCallback); * $http.post('/someUrl', data, config).then(successCallback, errorCallback); * ``` * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * - {@link ng.$http#patch $http.patch} * * * ## Writing Unit Tests that use $http * When unit testing (using {@link ngMock ngMock}), it is necessary to call * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending * request using trained responses. * * ``` * $httpBackend.expectGET(...); * $http.get(...); * $httpBackend.flush(); * ``` * * ## Deprecation Notice * <div class="alert alert-danger"> * The `$http` legacy promise methods `success` and `error` have been deprecated. * Use the standard `then` method instead. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error. * </div> * * ## Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`. * * The defaults can also be set at runtime via the `$http.defaults` object in the same * fashion. For example: * * ``` * module.run(function($http) { * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' * }); * ``` * * In addition, you can supply a `headers` property in the config object passed when * calling `$http(config)`, which overrides the defaults without changing them globally. * * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, * Use the `headers` property, setting the desired header to `undefined`. For example: * * ```js * var req = { * method: 'POST', * url: 'http://example.com', * headers: { * 'Content-Type': undefined * }, * data: { test: 'test' } * } * * $http(req).then(function(){...}, function(){...}); * ``` * * ## Transforming Requests and Responses * * Both requests and responses can be transformed using transformation functions: `transformRequest` * and `transformResponse`. These properties can be a single function that returns * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions, * which allows you to `push` or `unshift` a new transformation function into the transformation chain. * * ### Default Transformations * * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and * `defaults.transformResponse` properties. If a request does not provide its own transformations * then these will be applied. * * You can augment or replace the default transformations by modifying these properties by adding to or * replacing the array. * * Angular provides the following default transformations: * * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`): * * - If the `data` property of the request configuration object contains an object, serialize it * into JSON format. * * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`): * * - If XSRF prefix is detected, strip it (see Security Considerations section below). * - If JSON response is detected, deserialize it using a JSON parser. * * * ### Overriding the Default Transformations Per Request * * If you wish override the request/response transformations only for a single request then provide * `transformRequest` and/or `transformResponse` properties on the configuration object passed * into `$http`. * * Note that if you provide these properties on the config object the default transformations will be * overwritten. If you wish to augment the default transformations then you must include them in your * local transformation array. * * The following code demonstrates adding a new response transformation to be run after the default response * transformations have been run. * * ```js * function appendTransform(defaults, transform) { * * // We can't guarantee that the default transformation is an array * defaults = angular.isArray(defaults) ? defaults : [defaults]; * * // Append the new transformation to the defaults * return defaults.concat(transform); * } * * $http({ * url: '...', * method: 'GET', * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { * return doTransform(value); * }) * }); * ``` * * * ## Caching * * To enable caching, set the request configuration `cache` property to `true` (to use default * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). * When the cache is enabled, `$http` stores the response from the server in the specified * cache. The next time the same request is made, the response is served from the cache without * sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same URL that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response from the first request. * * You can change the default cache to a new object (built with * {@link ng.$cacheFactory `$cacheFactory`}) by updating the * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set * their `cache` property to `true` will now use this cache object. * * If you set the default cache to `false` then only requests that specify their own custom * cache object will be cached. * * ## Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication, or any kind of synchronous or * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be * able to intercept requests before they are handed to the server and * responses before they are handed over to the application code that * initiated these requests. The interceptors leverage the {@link ng.$q * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. * * The interceptors are service factories that are registered with the `$httpProvider` by * adding them to the `$httpProvider.interceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor. * * There are two kinds of interceptors (and two kinds of rejection interceptors): * * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to * modify the `config` object or create a new one. The function needs to return the `config` * object directly, or a promise containing the `config` or a new `config` object. * * `requestError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to * modify the `response` object or create a new one. The function needs to return the `response` * object directly, or as a promise containing the `response` or a new `response` object. * * `responseError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * * ```js * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return { * // optional method * 'request': function(config) { * // do something on success * return config; * }, * * // optional method * 'requestError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }, * * * * // optional method * 'response': function(response) { * // do something on success * return response; * }, * * // optional method * 'responseError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * } * }; * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // alternatively, register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { * return { * 'request': function(config) { * // same as above * }, * * 'response': function(response) { * // same as above * } * }; * }); * ``` * * ## Security Considerations * * When designing web applications, consider security threats from: * * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ### JSON Vulnerability Protection * * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * ```js * ['one','two'] * ``` * * which is vulnerable to attack, your server can return: * ```js * )]}', * ['one','two'] * ``` * * Angular will strip the prefix, before processing the JSON. * * * ### Cross Site Request Forgery (XSRF) Protection * * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which * an unauthorized site can gain your user's private data. Angular provides a mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from * making up its own tokens). We recommend that the token is a digest of your site's * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;) * for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, * or the per-request config object. * * In order to prevent collisions in environments where multiple Angular apps share the * same domain or subdomain, we recommend that each application uses unique cookie name. * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized * with the `paramSerializer` and appended as GET parameters. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the * header will not be sent. Functions accept a config object as an argument. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * See {@link ng.$http#overriding-the-default-transformations-per-request * Overriding the Default Transformations} * - **transformResponse** – * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` – * transform function or an array of such functions. The transform function takes the http * response body, headers and status and returns its transformed (typically deserialized) version. * See {@link ng.$http#overriding-the-default-transformations-per-request * Overriding the Default TransformationjqLiks} * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to * prepare the string representation of request parameters (specified as an object). * If specified as string, it is interpreted as function registered with the * {@link $injector $injector}, which means you can create your own serializer * by registering it as a {@link auto.$provide#service service}. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer}; * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike} * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) * for more information. * - **responseType** - `{string}` - see * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype). * * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object * when the request succeeds or fails. * * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example module="httpExample"> <file name="index.html"> <div ng-controller="FetchController"> <select ng-model="method" aria-label="Request method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80" aria-label="URL" /> <button id="fetchbtn" ng-click="fetch()">fetch</button><br> <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button id="samplejsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')"> Sample JSONP </button> <button id="invalidjsonpbtn" ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')"> Invalid JSONP </button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> angular.module('httpExample', []) .controller('FetchController', ['$scope', '$http', '$templateCache', function($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). then(function(response) { $scope.status = response.status; $scope.data = response.data; }, function(response) { $scope.data = response.data || "Request failed"; $scope.status = response.status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; }]); </file> <file name="http-hello.html"> Hello, $http! </file> <file name="protractor.js" type="protractor"> var status = element(by.binding('status')); var data = element(by.binding('data')); var fetchBtn = element(by.id('fetchbtn')); var sampleGetBtn = element(by.id('samplegetbtn')); var sampleJsonpBtn = element(by.id('samplejsonpbtn')); var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); it('should make an xhr GET request', function() { sampleGetBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('200'); expect(data.getText()).toMatch(/Hello, \$http!/); }); // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 // it('should make a JSONP request to angularjs.org', function() { // sampleJsonpBtn.click(); // fetchBtn.click(); // expect(status.getText()).toMatch('200'); // expect(data.getText()).toMatch(/Super Hero!/); // }); it('should make JSONP request to invalid URL and invoke the error handler', function() { invalidJsonpBtn.click(); fetchBtn.click(); expect(status.getText()).toMatch('0'); expect(data.getText()).toMatch('Request failed'); }); </file> </example> */ function $http(requestConfig) { if (!isObject(requestConfig)) { throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); } var config = extend({ method: 'get', transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse, paramSerializer: defaults.paramSerializer }, requestConfig); config.headers = mergeHeaders(requestConfig); config.method = uppercase(config.method); config.paramSerializer = isString(config.paramSerializer) ? $injector.get(config.paramSerializer) : config.paramSerializer; var serverRequest = function(config) { var headers = config.headers; var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); // strip content-type if data is undefined if (isUndefined(reqData)) { forEach(headers, function(value, header) { if (lowercase(header) === 'content-type') { delete headers[header]; } }); } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request return sendReq(config, reqData).then(transformResponse, transformResponse); }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); while (chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } if (useLegacyPromise) { promise.success = function(fn) { assertArgFn(fn, 'fn'); promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { assertArgFn(fn, 'fn'); promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; } else { promise.success = $httpMinErrLegacyFn('success'); promise.error = $httpMinErrLegacyFn('error'); } return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response); resp.data = transformData(response.data, response.headers, response.status, config.transformResponse); return (isSuccess(response.status)) ? resp : $q.reject(resp); } function executeHeaderFns(headers, config) { var headerContent, processedHeaders = {}; forEach(headers, function(headerFn, header) { if (isFunction(headerFn)) { headerContent = headerFn(config); if (headerContent != null) { processedHeaders[header] = headerContent; } } else { processedHeaders[header] = headerFn; } }); return processedHeaders; } function mergeHeaders(config) { var defHeaders = defaults.headers, reqHeaders = extend({}, config.headers), defHeaderName, lowercaseDefHeaderName, reqHeaderName; defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); // using for-in instead of forEach to avoid unecessary iteration after header has been found defaultHeadersIteration: for (defHeaderName in defHeaders) { lowercaseDefHeaderName = lowercase(defHeaderName); for (reqHeaderName in reqHeaders) { if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { continue defaultHeadersIteration; } } reqHeaders[defHeaderName] = defHeaders[defHeaderName]; } // execute if header value is a function for merged headers return executeHeaderFns(reqHeaders, shallowCopy(config)); } } $http.pendingRequests = []; /** * @ngdoc method * @name $http#get * * @description * Shortcut method to perform `GET` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#delete * * @description * Shortcut method to perform `DELETE` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#head * * @description * Shortcut method to perform `HEAD` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#jsonp * * @description * Shortcut method to perform `JSONP` request. * * @param {string} url Relative or absolute URL specifying the destination of the request. * The name of the callback should be the string `JSON_CALLBACK`. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name $http#post * * @description * Shortcut method to perform `POST` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#put * * @description * Shortcut method to perform `PUT` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name $http#patch * * @description * Shortcut method to perform `PATCH` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put', 'patch'); /** * @ngdoc property * @name $http#defaults * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend({}, config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend({}, config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, reqHeaders = config.headers, url = buildUrl(config.url, config.paramSerializer(config.params)); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if ((config.cache || defaults.cache) && config.cache !== false && (config.method === 'GET' || config.method === 'JSONP')) { cache = isObject(config.cache) ? config.cache : isObject(defaults.cache) ? defaults.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (isDefined(cachedResp)) { if (isPromiseLike(cachedResp)) { // cached request has already been sent, but there is no response yet cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult); } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); } else { resolvePromise(cachedResp, 200, {}, 'OK'); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, set the xsrf headers and // send the request to the backend if (isUndefined(cachedResp)) { var xsrfValue = urlIsSameOrigin(config.url) ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName] : undefined; if (xsrfValue) { reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString, statusText) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString), statusText]); } else { // remove promise from the cache cache.remove(url); } } function resolveHttpPromise() { resolvePromise(response, status, headersString, statusText); } if (useApplyAsync) { $rootScope.$applyAsync(resolveHttpPromise); } else { resolveHttpPromise(); if (!$rootScope.$$phase) $rootScope.$apply(); } } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers, statusText) { //status: HTTP response status code, 0, -1 (aborted by timeout / promise) status = status >= -1 ? status : 0; (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config, statusText: statusText }); } function resolvePromiseWithResult(result) { resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText); } function removePendingReq() { var idx = $http.pendingRequests.indexOf(config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, serializedParams) { if (serializedParams.length > 0) { url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams; } return url; } }]; }
import { run } from '@ember/runloop'; import { guidFor, setName } from 'ember-utils'; import { context } from 'ember-environment'; import EmberObject from '../../../lib/system/object'; import Namespace from '../../../lib/system/namespace'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; let originalLookup = context.lookup; let lookup; moduleFor( 'system/object/toString', class extends AbstractTestCase { beforeEach() { context.lookup = lookup = {}; } afterEach() { context.lookup = originalLookup; } ['@test toString() returns the same value if called twice'](assert) { let Foo = Namespace.create(); Foo.toString = function() { return 'Foo'; }; Foo.Bar = EmberObject.extend(); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); let obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); run(Foo, 'destroy'); } ['@test toString on a class returns a useful value when nested in a namespace'](assert) { let obj; let Foo = Namespace.create(); Foo.toString = function() { return 'Foo'; }; Foo.Bar = EmberObject.extend(); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); Foo.Baz = Foo.Bar.extend(); assert.equal(Foo.Baz.toString(), 'Foo.Baz'); obj = Foo.Baz.create(); assert.equal(obj.toString(), '<Foo.Baz:' + guidFor(obj) + '>'); obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); run(Foo, 'destroy'); } ['@test toString on a namespace finds the namespace in lookup'](assert) { let Foo = (lookup.Foo = Namespace.create()); assert.equal(Foo.toString(), 'Foo'); run(Foo, 'destroy'); } ['@test toString on a namespace finds the namespace in lookup'](assert) { let Foo = (lookup.Foo = Namespace.create()); let obj; Foo.Bar = EmberObject.extend(); assert.equal(Foo.Bar.toString(), 'Foo.Bar'); obj = Foo.Bar.create(); assert.equal(obj.toString(), '<Foo.Bar:' + guidFor(obj) + '>'); run(Foo, 'destroy'); } ['@test toString on a namespace falls back to modulePrefix, if defined'](assert) { let Foo = Namespace.create({ modulePrefix: 'foo' }); assert.equal(Foo.toString(), 'foo'); run(Foo, 'destroy'); } ['@test toString includes toStringExtension if defined'](assert) { let Foo = EmberObject.extend({ toStringExtension() { return 'fooey'; }, }); let foo = Foo.create(); let Bar = EmberObject.extend({}); let bar = Bar.create(); // simulate these classes being defined on a Namespace setName(Foo, 'Foo'); setName(Bar, 'Bar'); assert.equal( bar.toString(), '<Bar:' + guidFor(bar) + '>', 'does not include toStringExtension part' ); assert.equal( foo.toString(), '<Foo:' + guidFor(foo) + ':fooey>', 'Includes toStringExtension result' ); } } );
define(["../core","../manipulation"],function(e){function t(t,n){var o,a=e(n.createElement(t)).appendTo(n.body),d=window.getDefaultComputedStyle&&(o=window.getDefaultComputedStyle(a[0]))?o.display:e.css(a[0],"display");return a.detach(),d}function n(n){var d=document,r=a[n];return r||(r=t(n,d),"none"!==r&&r||(o=(o||e("<iframe frameborder='0' width='0' height='0'/>")).appendTo(d.documentElement),d=o[0].contentDocument,d.write(),d.close(),r=t(n,d),o.detach()),a[n]=r),r}var o,a={};return n});
#!/usr/bin/env node 'use strict'; var fs = require('fs'), path = require('path'), exec = require('child_process').exec, chalk = require('chalk'), Table = require('cli-table'); var fileNames = [ 'abc', 'amazon', //'eloquentjavascript', //'es6-draft', 'es6-table', 'google', 'html-minifier', 'msn', 'newyorktimes', 'stackoverflow', 'wikipedia', 'es6' ]; fileNames = fileNames.sort().reverse(); var table = new Table({ head: ['File', 'Before', 'After', 'Savings', 'Time'], colWidths: [20, 25, 25, 20, 20] }); function toKb(size) { return (size / 1024).toFixed(2); } function redSize(size) { return chalk.red.bold(size) + chalk.white(' (' + toKb(size) + ' KB)'); } function greenSize(size) { return chalk.green.bold(size) + chalk.white(' (' + toKb(size) + ' KB)'); } function blueSavings(oldSize, newSize) { var savingsPercent = (1 - newSize / oldSize) * 100; var savings = (oldSize - newSize) / 1024; return chalk.cyan.bold(savingsPercent.toFixed(2)) + chalk.white('% (' + savings.toFixed(2) + ' KB)'); } function blueTime(time) { return chalk.cyan.bold(time) + chalk.white(' ms'); } function test(fileName, done) { if (!fileName) { console.log('\n' + table.toString()); return; } console.log('Processing...', fileName); var filePath = path.join('benchmarks/', fileName + '.html'); var minifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html'); var gzFilePath = path.join('benchmarks/generated/', fileName + '.html.gz'); var gzMinifiedFilePath = path.join('benchmarks/generated/', fileName + '.min.html.gz'); var command = path.normalize('./cli.js') + ' ' + filePath + ' -c benchmark.conf' + ' -o ' + minifiedFilePath; // Open and read the size of the original input fs.stat(filePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + filePath); } var originalSize = stats.size; exec('gzip --keep --force --best --stdout ' + filePath + ' > ' + gzFilePath, function () { // Open and read the size of the gzipped original fs.stat(gzFilePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + gzFilePath); } var gzOriginalSize = stats.size; // Begin timing after gzipped fixtures have been created var startTime = new Date(); exec('node ' + command, function () { // Open and read the size of the minified output fs.stat(minifiedFilePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + minifiedFilePath); } var minifiedSize = stats.size; var minifiedTime = new Date() - startTime; // Gzip the minified output exec('gzip --keep --force --best --stdout ' + minifiedFilePath + ' > ' + gzMinifiedFilePath, function () { // Open and read the size of the minified+gzipped output fs.stat(gzMinifiedFilePath, function (err, stats) { if (err) { throw new Error('There was an error reading ' + gzMinifiedFilePath); } var gzMinifiedSize = stats.size; var gzMinifiedTime = new Date() - startTime; table.push([ [fileName, '+ gzipped'].join('\n'), [redSize(originalSize), redSize(gzOriginalSize)].join('\n'), [greenSize(minifiedSize), greenSize(gzMinifiedSize)].join('\n'), [blueSavings(originalSize, minifiedSize), blueSavings(gzOriginalSize, gzMinifiedSize)].join('\n'), [blueTime(minifiedTime), blueTime(gzMinifiedTime)].join('\n') ]); done(); }); }); }); }); }); }); }); } (function run() { test(fileNames.pop(), run); })();
steal('can/util', 'can/observe', function(can) { // ** - 'this' will be the deepest item changed // * - 'this' will be any changes within *, but * will be the // this returned // tells if the parts part of a delegate matches the broken up props of the event // gives the prop to use as 'this' // - parts - the attribute name of the delegate split in parts ['foo','*'] // - props - the split props of the event that happened ['foo','bar','0'] // - returns - the attribute to delegate too ('foo.bar'), or null if not a match var matches = function(parts, props){ //check props parts are the same or var len = parts.length, i =0, // keeps the matched props we will use matchedProps = [], prop; // if the event matches for(i; i< len; i++){ prop = props[i] // if no more props (but we should be matching them) // return null if( typeof prop !== 'string' ) { return null; } else // if we have a "**", match everything if( parts[i] == "**" ) { return props.join("."); } else // a match, but we want to delegate to "*" if (parts[i] == "*"){ // only do this if there is nothing after ... matchedProps.push(prop); } else if( prop === parts[i] ) { matchedProps.push(prop); } else { return null; } } return matchedProps.join("."); }, // gets a change event and tries to figure out which // delegates to call delegate = function(event, prop, how, newVal, oldVal){ // pre-split properties to save some regexp time var props = prop.split("."), delegates = (this._observe_delegates || []).slice(0), delegate, attr, matchedAttr, hasMatch, valuesEqual; event.attr = prop; event.lastAttr = props[props.length -1 ]; // for each delegate for(var i =0; delegate = delegates[i++];){ // if there is a batchNum, this means that this // event is part of a series of events caused by a single // attrs call. We don't want to issue the same event // multiple times // setting the batchNum happens later if((event.batchNum && delegate.batchNum === event.batchNum) || delegate.undelegated ){ continue; } // reset match and values tests hasMatch = undefined; valuesEqual = true; // for each attr in a delegate for(var a =0 ; a < delegate.attrs.length; a++){ attr = delegate.attrs[a]; // check if it is a match if(matchedAttr = matches(attr.parts, props)){ hasMatch = matchedAttr; } // if it has a value, make sure it's the right value // if it's set, we should probably check that it has a // value no matter what if(attr.value && valuesEqual /* || delegate.hasValues */){ valuesEqual = attr.value === ""+this.attr(attr.attr) } else if (valuesEqual && delegate.attrs.length > 1){ // if there are multiple attributes, each has to at // least have some value valuesEqual = this.attr(attr.attr) !== undefined } } // if there is a match and valuesEqual ... call back if(hasMatch && valuesEqual) { // how to get to the changed property from the delegate var from = prop.replace(hasMatch+".",""); // if this event is part of a batch, set it on the delegate // to only send one event if(event.batchNum ){ delegate.batchNum = event.batchNum } // if we listen to change, fire those with the same attrs // TODO: the attrs should probably be using from if( delegate.event === 'change' ){ arguments[1] = from; event.curAttr = hasMatch; delegate.callback.apply(this.attr(hasMatch), can.makeArray( arguments)); } else if(delegate.event === how ){ // if it's a match, callback with the location of the match delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]); } else if(delegate.event === 'set' && how == 'add' ) { // if we are listening to set, we should also listen to add delegate.callback.apply(this.attr(hasMatch), [event,newVal, oldVal, from]); } } } }; can.extend(can.Observe.prototype,{ /** * @function can.Observe.prototype.delegate * @parent can.Observe.delegate * @plugin can/observe/delegate * * `delegate( selector, event, handler(ev,newVal,oldVal,from) )` listen for changes * in a child attribute from the parent. The child attribute * does not have to exist. * * * // create an observable * var observe = can.Observe({ * foo : { * bar : "Hello World" * } * }) * * //listen to changes on a property * observe.delegate("foo.bar","change", function(ev, prop, how, newVal, oldVal){ * // foo.bar has been added, set, or removed * this //-> * }); * * // change the property * observe.attr('foo.bar',"Goodbye Cruel World") * * ## Types of events * * Delegate lets you listen to add, set, remove, and change events on property. * * __add__ * * An add event is fired when a new property has been added. * * var o = new can.Control({}); * o.delegate("name","add", function(ev, value){ * // called once * can.$('#name').show() * }) * o.attr('name',"Justin") * o.attr('name',"Brian"); * * Listening to add events is useful for 'setup' functionality (in this case * showing the <code>#name</code> element. * * __set__ * * Set events are fired when a property takes on a new value. set events are * always fired after an add. * * o.delegate("name","set", function(ev, value){ * // called twice * can.$('#name').text(value) * }) * o.attr('name',"Justin") * o.attr('name',"Brian"); * * __remove__ * * Remove events are fired after a property is removed. * * o.delegate("name","remove", function(ev){ * // called once * $('#name').text(value) * }) * o.attr('name',"Justin"); * o.removeAttr('name'); * * ## Wildcards - matching multiple properties * * Sometimes, you want to know when any property within some part * of an observe has changed. Delegate lets you use wildcards to * match any property name. The following listens for any change * on an attribute of the params attribute: * * var o = can.Control({ * options : { * limit : 100, * offset: 0, * params : { * parentId: 5 * } * } * }) * o.delegate('options.*','change', function(){ * alert('1'); * }) * o.delegate('options.**','change', function(){ * alert('2'); * }) * * // alerts 1 * // alerts 2 * o.attr('options.offset',100) * * // alerts 2 * o.attr('options.params.parentId',6); * * Using a single wildcard (<code>*</code>) matches single level * properties. Using a double wildcard (<code>**</code>) matches * any deep property. * * ## Listening on multiple properties and values * * Delegate lets you listen on multiple values at once. The following listens * for first and last name changes: * * var o = new can.Observe({ * name : {first: "Justin", last: "Meyer"} * }) * * o.bind("name.first,name.last", * "set", * function(ev,newVal,oldVal,from){ * * }) * * ## Listening when properties are a particular value * * Delegate lets you listen when a property is __set__ to a specific value: * * var o = new can.Observe({ * name : "Justin" * }) * * o.bind("name=Brian", * "set", * function(ev,newVal,oldVal,from){ * * }) * * @param {String} selector The attributes you want to listen for changes in. * * Selector should be the property or * property names of the element you are searching. Examples: * * "name" - listens to the "name" property changing * "name, address" - listens to "name" or "address" changing * "name address" - listens to "name" or "address" changing * "address.*" - listens to property directly in address * "address.**" - listens to any property change in address * "foo=bar" - listens when foo is "bar" * * @param {String} event The event name. One of ("set","add","remove","change") * @param {Function} handler(ev,newVal,oldVal,prop) The callback handler * called with: * * - newVal - the new value set on the observe * - oldVal - the old value set on the observe * - prop - the prop name that was changed * * @return {jQuery.Delegate} the delegate for chaining */ delegate : function(selector, event, handler){ selector = can.trim(selector); var delegates = this._observe_delegates || (this._observe_delegates = []), attrs = []; // split selector by spaces selector.replace(/([^\s=]+)=?([^\s]+)?/g, function(whole, attr, value){ attrs.push({ // the attribute name attr: attr, // the attribute's pre-split names (for speed) parts: attr.split('.'), // the value associated with this prop value: value }) }); // delegates has pre-processed info about the event delegates.push({ // the attrs name for unbinding selector : selector, // an object of attribute names and values {type: 'recipe',id: undefined} // undefined means a value was not defined attrs : attrs, callback : handler, event: event }); if(delegates.length === 1){ this.bind("change",delegate) } return this; }, /** * @function can.Observe.prototype.undelegate * @parent can.Observe.delegate * * `undelegate( selector, event, handler )` removes a delegated event handler from an observe. * * observe.undelegate("name","set", handler ) * * @param {String} selector the attribute name of the object you want to undelegate from. * @param {String} event the event name * @param {Function} handler the callback handler * @return {jQuery.Delegate} the delegate for chaining */ undelegate : function(selector, event, handler){ selector = can.trim(selector); var i =0, delegates = this._observe_delegates || [], delegateOb; if(selector){ while(i < delegates.length){ delegateOb = delegates[i]; if( delegateOb.callback === handler || (!handler && delegateOb.selector === selector) ){ delegateOb.undelegated = true; delegates.splice(i,1) } else { i++; } } } else { // remove all delegates delegates = []; } if(!delegates.length){ //can.removeData(this, "_observe_delegates"); this.unbind("change",delegate) } return this; } }); // add helpers for testing .. can.Observe.prototype.delegate.matches = matches; return can.Observe; })
var name = "Wanderer"; var collection_type = 0; var is_secret = 0; var desc = "Visited 503 new locations."; var status_text = "Gosh, where HAVEN'T you traveled? Your peregrinations have earned you this footworn-but-carefree Wanderer badge."; var last_published = 1348803094; var is_shareworthy = 1; var url = "wanderer"; var category = "exploring"; var url_swf = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-09-18\/wanderer_1316414516_40.png"; function on_apply(pc){ } var conditions = { 8 : { type : "group_count", group : "locations_visited", value : "503" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(1000 * multiplier), true); pc.stats_add_favor_points("lem", round_to_5(200 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 1000, "favor" : { "giant" : "lem", "points" : 200 } }; // generated ok (NO DATE)
export default class ModelAccessor { constructor() { this.value = 10 } get highCount() { return this.value + 100 } set highCount(v) { this.value = v - 100 } get doubleHigh() { return this.highCount * 2 } incr() { this.value++ } }
import { Template } from 'meteor/templating'; Template.messageAction.helpers({ isButton() { return this.type === 'button'; }, areButtonsHorizontal() { return Template.parentData(1).button_alignment === 'horizontal'; }, jsActionButtonClassname(processingType) { return `js-actionButton-${ processingType || 'sendMessage' }`; }, });
import fs from 'fs'; import url from 'url'; import path from 'path'; import mime from 'mime-types'; import gulp from 'gulp'; import createServerTask from './tasks/server'; import consoleArguments from './console-arguments'; import { adminBundle } from './admin-bundle.tasks'; import { dashboardBundle } from './dashboard-bundle.tasks'; import { mediaBundle } from './media-bundle.tasks'; import { translatorBundle } from './translator-bundle.tasks'; const BUNDLES = [adminBundle, dashboardBundle, mediaBundle, translatorBundle]; const writeToResponse = (req, res, bundlePaths) => { const formattedUrl = url.parse(req.url); for (const bundlePath of bundlePaths) { const filePath = path.normalize(bundlePath + formattedUrl.pathname); try { const stat = fs.statSync(filePath); if (stat && stat.isFile()) { const rstream = fs.createReadStream(filePath); const extension = path.extname(filePath); const contentType = mime.lookup(extension); res.writeHead(200, { 'Content-Type': contentType, 'Content-Length': stat.size }); rstream.pipe(res); return; } } catch (e) { // Does not exist } } return new Error(`Local file for ${req.url} not found`); }; const handleRequest = (req, res, next) => { if (writeToResponse(req, res, BUNDLES.map(item => item.config.distPath))) { // Nothing we can write to the stream, fallback to the default behavior return next(); }; }; const startLocalTask = createServerTask({ config: { ui: false, ghostMode: false, open: false, reloadOnRestart: true, notify: true, proxy: { target: consoleArguments.backendProxy }, middleware: BUNDLES.map(bundle => { return { route: bundle.config.publicPath, handle: handleRequest } }) } }); export const buildOnChange = (done) => { for (const bundle of BUNDLES) { const srcPath = bundle.config.srcPath; const jsAssets = srcPath + 'js/**/!(*.spec).js'; gulp.watch(jsAssets, bundle.tasks.scripts); if (bundle.tasks.bundle) { const jsNextAssets = srcPath + 'jsnext/**/!(*.spec).js'; gulp.watch(jsNextAssets, bundle.tasks.bundle); } const styleAssets = srcPath + 'scss/**/*.scss'; gulp.watch(styleAssets, bundle.tasks.cssOptimized); if (bundle.tasks.cssNextOptimized) { const styleNextAssets = srcPath + 'scssnext/**/*.scss'; gulp.watch(styleNextAssets, bundle.tasks.cssNextOptimized); } } done(); }; export function testOnChange(done) { for (const bundle of BUNDLES) { if (bundle.tasks.eslint) { const srcPath = bundle.config.srcPath; gulp.watch(`${srcPath}jsnext/**/*.js`, bundle.tasks.eslint); } if (bundle.tasks.stylelint) { const srcPath = bundle.config.srcPath; gulp.watch(`${srcPath}scssnext/**/*.scss`, bundle.tasks.stylelint); } } done(); } export default startLocalTask;
'use strict'; describe('Service: Initiatives', function () { // instantiate service var Initiatives, Timeout, cfg, $httpBackend, $rootScope, tPromise; // load the service's module beforeEach(module('sumaAnalysis')); beforeEach(inject(function (_$rootScope_, _$httpBackend_, _initiatives_, $q, $timeout) { $rootScope = _$rootScope_; $httpBackend = _$httpBackend_; Initiatives = _initiatives_; tPromise = $q.defer(); Timeout = $timeout; cfg = { timeoutPromise: tPromise, timeout: 180000 }; })); it('should make an AJAX call', function (done) { $httpBackend.whenGET('lib/php/initiatives.php') .respond([{}, {}]); Initiatives.get(cfg).then(function (result) { expect(result.length).to.equal(2); done(); }); $httpBackend.flush(); }); it('should respond with error message on failure', function (done) { $httpBackend.whenGET('lib/php/initiatives.php') .respond(500, {message: 'Error'}); Initiatives.get(cfg).then(function (result) { }, function (result) { expect(result).to.deep.equal({ message: 'Error', code: 500 }); done(); }); $httpBackend.flush(); }); it('should return error with promiseTimeout true on aborted http request', function (done) { // simulate aborted request $httpBackend.whenGET('lib/php/initiatives.php') .respond(0, {message: 'Error'}); Initiatives.get(cfg).then(function (result) { }, function (result) { expect(result).to.deep.equal({ message: 'Initiatives.get Timeout', code: 0, promiseTimeout: true }); done(); }); $httpBackend.flush(); }); it('should return error without promiseTimeout on http timeout', function (done) { $httpBackend.whenGET('lib/php/initiatives.php') .respond([{}, {}]); Initiatives.get(cfg).then(function (result) { }, function (result) { expect(result).to.deep.equal({ message: 'Initiatives.get Timeout', code: 0 }); done(); }); Timeout.flush(); }); });
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* Tabulator v4.0.2 (c) Oliver Folkerd */ var HtmlTableImport = function HtmlTableImport(table) { this.table = table; //hold Tabulator object this.fieldIndex = []; this.hasIndex = false; }; HtmlTableImport.prototype.parseTable = function () { var self = this, element = self.table.element, options = self.table.options, columns = options.columns, headers = element.getElementsByTagName("th"), rows = element.getElementsByTagName("tbody")[0].getElementsByTagName("tr"), data = [], newTable; self.hasIndex = false; self.table.options.htmlImporting.call(this.table); //check for tablator inline options self._extractOptions(element, options); if (headers.length) { self._extractHeaders(headers, rows); } else { self._generateBlankHeaders(headers, rows); } //iterate through table rows and build data set for (var index = 0; index < rows.length; index++) { var row = rows[index], cells = row.getElementsByTagName("td"), item = {}; //create index if the dont exist in table if (!self.hasIndex) { item[options.index] = index; } for (var i = 0; i < cells.length; i++) { var cell = cells[i]; if (typeof this.fieldIndex[i] !== "undefined") { item[this.fieldIndex[i]] = cell.innerHTML; } } //add row data to item data.push(item); } //create new element var newElement = document.createElement("div"); //transfer attributes to new element var attributes = element.attributes; // loop through attributes and apply them on div for (var i in attributes) { if (_typeof(attributes[i]) == "object") { newElement.setAttribute(attributes[i].name, attributes[i].value); } } // replace table with div element element.parentNode.replaceChild(newElement, element); options.data = data; self.table.options.htmlImported.call(this.table); // // newElement.tabulator(options); this.table.element = newElement; }; //extract tabluator attribute options HtmlTableImport.prototype._extractOptions = function (element, options) { var attributes = element.attributes; for (var index in attributes) { var attrib = attributes[index]; var name; if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) { name = attrib.name.replace("tabulator-", ""); for (var key in options) { if (key.toLowerCase() == name) { options[key] = this._attribValue(attrib.value); } } } } }; //get value of attribute HtmlTableImport.prototype._attribValue = function (value) { if (value === "true") { return true; } if (value === "false") { return false; } return value; }; //find column if it has already been defined HtmlTableImport.prototype._findCol = function (title) { var match = this.table.options.columns.find(function (column) { return column.title === title; }); return match || false; }; //extract column from headers HtmlTableImport.prototype._extractHeaders = function (headers, rows) { for (var index = 0; index < headers.length; index++) { var header = headers[index], exists = false, col = this._findCol(header.textContent), width, attributes; if (col) { exists = true; } else { col = { title: header.textContent.trim() }; } if (!col.field) { col.field = header.textContent.trim().toLowerCase().replace(" ", "_"); } width = header.getAttribute("width"); if (width && !col.width) { col.width = width; } //check for tablator inline options attributes = header.attributes; // //check for tablator inline options this._extractOptions(header, col); for (var i in attributes) { var attrib = attributes[i], name; if ((typeof attrib === "undefined" ? "undefined" : _typeof(attrib)) == "object" && attrib.name && attrib.name.indexOf("tabulator-") === 0) { name = attrib.name.replace("tabulator-", ""); col[name] = this._attribValue(attrib.value); } } this.fieldIndex[index] = col.field; if (col.field == this.table.options.index) { this.hasIndex = true; } if (!exists) { this.table.options.columns.push(col); } } }; //generate blank headers HtmlTableImport.prototype._generateBlankHeaders = function (headers, rows) { for (var index = 0; index < headers.length; index++) { var header = headers[index], col = { title: "", field: "col" + index }; this.fieldIndex[index] = col.field; var width = header.getAttribute("width"); if (width) { col.width = width; } this.table.options.columns.push(col); } }; Tabulator.prototype.registerModule("htmlTableImport", HtmlTableImport);
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function DumpArray(a) { var undef_start = -1; for (var i = 0; i < a.length; i++) { if (a[i] == undefined) { if (undef_start == -1) { undef_start = i; } } else { if (undef_start != -1) { WScript.Echo(undef_start + "-" + (i-1) + " = undefined"); undef_start = -1; } WScript.Echo(i + " = " + a[i]); } } } DumpArray([]); DumpArray([ 0 ]); DumpArray([ 0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9]); DumpArray([,,,0,,,1,,,2,,,3,,,4,,,5,,,6,,,7,,,8,,,9,,,]); var s0 = ""; for (var i = 0; i < 100; i++) { s0 += ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,"; } DumpArray(eval("[" + s0 + "1]")); var s1 = ""; for (var i = 0; i < 30; i++) { s1 += s0; } DumpArray(eval("[" + s1 + "1]")); var s2 = ""; for (var i = 0; i < 10; i++) { s2 += s1; } DumpArray(eval("[" + s2 + "1]"));
var expect = require('expect.js'); var path = require('path'); var fs = require('../extfs'); describe('extfs', function () { var rootPath = path.join(__dirname, '../'); it('should return all directories', function (done) { fs.getDirs(rootPath, function (err, dirs) { expect(dirs).to.be.an(Array); expect(dirs.length).to.be.greaterThan(0); done(); }); }); it('should return all directories sync', function () { var dirs = fs.getDirsSync(rootPath); expect(dirs).to.be.an(Array); expect(dirs.length > 0).to.be.ok(); }); it('should check if a file is empty', function (done) { var notEmptyFile = path.join(__dirname, '../README.md'); var emptyFile = './AN EMPTY FILE'; fs.isEmpty(notEmptyFile, function (empty) { expect(empty).to.be(false); fs.isEmpty(emptyFile, function (empty) { expect(empty).to.be(true); done(); }); }); }); it('should check if a file is empty sync', function () { var notEmptyFile = path.join(__dirname, '../README.md'); var emptyFile = './AN EMPTY FILE'; var empty = fs.isEmptySync(notEmptyFile); expect(empty).to.be(false); empty = fs.isEmptySync(emptyFile); expect(empty).to.be(true); }); it('should check if a directory is empty', function (done) { var notEmptyDir = __dirname; var emptyDir = './AN EMPTY DIR'; fs.isEmpty(notEmptyDir, function (empty) { expect(empty).to.be(false); fs.isEmpty(emptyDir, function (empty) { expect(empty).to.be(true); done(); }) }); }); it('should check if a directory is empty sync', function () { var notEmptyDir = __dirname; var emptyDir = './AN EMPTY DIR'; expect(fs.isEmptySync(notEmptyDir)).to.be(false); expect(fs.isEmptySync(emptyDir)).to.be(true); }); describe('remove directories', function () { var tmpPath = path.join(rootPath, 'tmp'); var folders = [ 'folder1', 'folder2', 'folder3' ]; var files = [ '1.txt', '2.txt', '3.txt' ]; folders = folders.map(function (folder) { return path.join(tmpPath, folder); }); /** * Create 3 folders with 3 files each */ beforeEach(function () { if (!fs.existsSync(tmpPath)) { fs.mkdirSync(tmpPath, '0755'); } folders.forEach(function (folder) { if (!fs.existsSync(folder)) { fs.mkdirSync(folder, '0755'); } files.forEach(function (file) { fs.writeFile(path.join(folder, file), 'file content'); }); }); }); it('should remove a non empty directory', function (done) { fs.remove(tmpPath, function (err) { expect(err).to.be(null); expect(fs.existsSync(tmpPath)).to.be(false); done(); }); }); it('should remove a non empty directory synchronously', function () { fs.removeSync(tmpPath); expect(fs.existsSync(tmpPath)).to.be(false); }); it('should remove an array of directories', function (done) { fs.remove(folders, function (err) { expect(err).to.be(null); expect(fs.existsSync(folders[0])).to.be(false); expect(fs.existsSync(folders[1])).to.be(false); expect(fs.existsSync(folders[2])).to.be(false); expect(fs.existsSync(tmpPath)).to.be(true); done(); }); }); it('should remove an array of directories synchronously', function () { fs.removeSync(folders); expect(fs.existsSync(folders[0])).to.be(false); expect(fs.existsSync(folders[1])).to.be(false); expect(fs.existsSync(folders[2])).to.be(false); expect(fs.existsSync(tmpPath)).to.be(true); }); }); it('should extends to fs', function () { expect(fs.readdir).to.be.a(Function); }); });
describe("BASIC CRUD SCENARIOS", function() { require("./basic"); }); describe("VALIDATE CRUD SCENARIOS", function() { require("./validation"); }); describe("REPORT SCENARIOS", function() { require("./report"); });
var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); var testCase = require('../../deps/nodeunit').testCase, debug = require('util').debug, inspect = require('util').inspect, nodeunit = require('../../deps/nodeunit'), gleak = require('../../tools/gleak'), Db = mongodb.Db, Cursor = mongodb.Cursor, Collection = mongodb.Collection, Server = mongodb.Server, ServerManager = require('../../test/tools/server_manager').ServerManager, Step = require("../../deps/step/lib/step"); var MONGODB = 'integration_tests'; var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); var serverManager = null; // Define the tests, we want them to run as a nested test so we only clean up the // db connection once var tests = testCase({ setUp: function(callback) { callback(); }, tearDown: function(callback) { // serverManager.stop(9, function(err, result) { callback(); // }); }, shouldCorrectlyKeepInsertingDocumentsWhenServerDiesAndComesUp : function(test) { var db1 = new Db('mongo-ruby-test-single-server', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); // All inserted docs var docs = []; var errs = []; var insertDocs = []; // Start server serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) serverManager.start(true, function() { db1.open(function(err, db) { // Startup the insert of documents var intervalId = setInterval(function() { db.collection('inserts', function(err, collection) { var doc = {timestamp:new Date().getTime()}; insertDocs.push(doc); // Insert document collection.insert(doc, {safe:{fsync:true}}, function(err, result) { // Save errors if(err != null) errs.push(err); if(err == null) { docs.push(result[0]); } }) }); }, 500); // Wait for a second and then kill the server setTimeout(function() { // Kill server instance serverManager.stop(9, function(err, result) { // Server down for 1 second setTimeout(function() { // Restart server serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); serverManager.start(true, function() { // Wait for it setTimeout(function() { // Drop db db.dropDatabase(function(err, result) { // Close db db.close(); // Check that we got at least one error // test.ok(errs.length > 0); test.ok(docs.length > 0); test.ok(insertDocs.length > 0); // Finish up test.done(); }); }, 5000) }) }, 1000); }); }, 3000); }) }); }, shouldCorrectlyInsertKillServerFailThenRestartServerAndSucceed : function(test) { var db = new Db('test-single-server-recovery', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {numberOfRetries:3, retryMiliSeconds:500, native_parser: (process.env['TEST_NATIVE'] != null)}); // All inserted docs var docs = []; var errs = []; var insertDocs = []; // Start server serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) serverManager.start(true, function() { db.open(function(err, db) { // Add an error handler db.on("error", function(err) { console.log("----------------------------------------------- received error") console.dir(err) errs.push(err); }); db.collection('inserts', function(err, collection) { var doc = {timestamp:new Date().getTime(), a:1}; collection.insert(doc, {safe:true}, function(err, result) { test.equal(null, err); // Kill server instance serverManager.stop(9, function(err, result) { // Attemp insert (should timeout) var doc = {timestamp:new Date().getTime(), b:1}; collection.insert(doc, {safe:true}, function(err, result) { test.ok(err != null); test.equal(null, result); // Restart server serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); serverManager.start(true, function() { // Attemp insert again collection.insert(doc, {safe:true}, function(err, result) { // Fetch the documents collection.find({b:1}).toArray(function(err, items) { test.equal(null, err); test.equal(1, items[0].b); test.done(); }); }); }); }); }); }) }); }); }); }, noGlobalsLeaked : function(test) { var leaks = gleak.detectNew(); test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); test.done(); } }) // Assign out tests module.exports = tests;
'use strict'; describe('Controller: AboutCtrl', function () { // load the controller's module beforeEach(module('e01App')); var AboutCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); AboutCtrl = $controller('AboutCtrl', { $scope: scope // place here mocked dependencies }); })); it('should attach a list of awesomeThings to the scope', function () { expect(AboutCtrl.awesomeThings.length).toBe(3); }); });
var searchData= [ ['digitalpin_2eh',['DigitalPin.h',['../_digital_pin_8h.html',1,'']]] ];
/** * @typedef {object} Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig * @since 3.0.0 * * @property {Phaser.GameObjects.DynamicBitmapText} parent - The Dynamic Bitmap Text object that owns this character being rendered. * @property {Phaser.Types.GameObjects.BitmapText.TintConfig} tint - The tint of the character being rendered. Always zero in Canvas. * @property {number} index - The index of the character being rendered. * @property {number} charCode - The character code of the character being rendered. * @property {number} x - The x position of the character being rendered. * @property {number} y - The y position of the character being rendered. * @property {number} scale - The scale of the character being rendered. * @property {number} rotation - The rotation of the character being rendered. * @property {any} data - Custom data stored with the character being rendered. */ /** * @callback Phaser.Types.GameObjects.BitmapText.DisplayCallback * * @param {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} display - Settings of the character that is about to be rendered. * * @return {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} Altered position, scale and rotation values for the character that is about to be rendered. */
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('is-array') exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var kMaxLength = 0x3fffffff /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Note: * * - Implementation must support adding new properties to `Uint8Array` instances. * Firefox 4-29 lacked support, fixed in Firefox 30+. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will * get the Object implementation, which is slower but will work correctly. */ Buffer.TYPED_ARRAY_SUPPORT = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return 42 === arr.foo() && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject // Find the length var length if (type === 'number') length = subject > 0 ? subject >>> 0 : 0 else if (type === 'string') { if (encoding === 'base64') subject = base64clean(subject) length = Buffer.byteLength(subject, encoding) } else if (type === 'object' && subject !== null) { // assume object is array-like if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data length = +subject.length > 0 ? Math.floor(+subject.length) : 0 } else throw new TypeError('must start with number, buffer, array or string') if (this.length > kMaxLength) throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength.toString(16) + ' bytes') var buf if (Buffer.TYPED_ARRAY_SUPPORT) { // Preferred: Return an augmented `Uint8Array` instance for best performance buf = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return THIS instance of Buffer (created by `new`) buf = this buf.length = length buf._isBuffer = true } var i if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array buf._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array if (Buffer.isBuffer(subject)) { for (i = 0; i < length; i++) buf[i] = subject.readUInt8(i) } else { for (i = 0; i < length; i++) buf[i] = ((subject[i] % 256) + 256) % 256 } } else if (type === 'string') { buf.write(subject, 0, encoding) } else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) { for (i = 0; i < length; i++) { buf[i] = 0 } } return buf } Buffer.isBuffer = function (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) throw new TypeError('Arguments must be Buffers') var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function (list, totalLength) { if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (totalLength === undefined) { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } Buffer.byteLength = function (str, encoding) { var ret str = str + '' switch (encoding || 'utf8') { case 'ascii': case 'binary': case 'raw': ret = str.length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break case 'hex': ret = str.length >>> 1 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'base64': ret = base64ToBytes(str).length break default: ret = str.length } return ret } // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function (encoding, start, end) { var loweredCase = false start = start >>> 0 end = end === undefined || end === Infinity ? this.length : end >>> 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.equals = function (b) { if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') return Buffer.compare(this, b) } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) if (isNaN(byte)) throw new Error('Invalid hex string') buf[offset + i] = byte } return i } function utf8Write (buf, string, offset, length) { var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) return charsWritten } function asciiWrite (buf, string, offset, length) { var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function utf16leWrite (buf, string, offset, length) { var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = utf8Write(this, string, offset, length) break case 'ascii': ret = asciiWrite(this, string, offset, length) break case 'binary': ret = binaryWrite(this, string, offset, length) break case 'base64': ret = base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leWrite(this, string, offset, length) break default: throw new TypeError('Unknown encoding: ' + encoding) } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function binarySlice (buf, start, end) { return asciiSlice(buf, start, end) } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len; if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start if (Buffer.TYPED_ARRAY_SUPPORT) { return Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } return newBuf } } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new TypeError('value is out of bounds') if (offset + ext > buf.length) throw new TypeError('index out of range') } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = value return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else objectWriteUInt16(this, value, offset, true) return offset + 2 } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else objectWriteUInt16(this, value, offset, false) return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = value } else objectWriteUInt32(this, value, offset, true) return offset + 4 } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else objectWriteUInt32(this, value, offset, false) return offset + 4 } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = value return offset + 1 } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) } else objectWriteUInt16(this, value, offset, true) return offset + 2 } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = value } else objectWriteUInt16(this, value, offset, false) return offset + 2 } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else objectWriteUInt32(this, value, offset, true) return offset + 4 } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { value = +value offset = offset >>> 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = value } else objectWriteUInt32(this, value, offset, false) return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new TypeError('value is out of bounds') if (offset + ext > buf.length) throw new TypeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 // Copy 0 bytes; we're done if (end === start) return if (target.length === 0 || source.length === 0) return // Fatal error conditions if (end < start) throw new TypeError('sourceEnd < sourceStart') if (target_start < 0 || target_start >= target.length) throw new TypeError('targetStart out of bounds') if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds') if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 100 || !Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < len; i++) { target[i + target_start] = this[i + start] } } else { target._set(this.subarray(start, start + len), target_start) } } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new TypeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new TypeError('start out of bounds') if (end < 0 || end > this.length) throw new TypeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function (arr) { arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-z]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { var b = str.charCodeAt(i) if (b <= 0x7F) { byteArray.push(b) } else { var start = i if (b >= 0xD800 && b <= 0xDFFF) i++ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') for (var j = 0; j < h.length; j++) { byteArray.push(parseInt(h[j], 16)) } } } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(str) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } },{"base64-js":2,"ieee754":3,"is-array":4}],2:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS) return 62 // '+' if (code === SLASH) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],3:[function(require,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],4:[function(require,module,exports){ /** * isArray */ var isArray = Array.isArray; /** * toString */ var str = Object.prototype.toString; /** * Whether or not the given `val` * is an array. * * example: * * isArray([]); * // > true * isArray(arguments); * // > false * isArray(''); * // > false * * @param {mixed} val * @return {bool} */ module.exports = isArray || function (val) { return !! val && '[object Array]' == str.call(val); }; },{}],5:[function(require,module,exports){ ndarray = require( 'ndarray' ); },{"ndarray":6}],6:[function(require,module,exports){ (function (Buffer){ var iota = require("iota-array") var hasTypedArrays = ((typeof Float64Array) !== "undefined") var hasBuffer = ((typeof Buffer) !== "undefined") function compare1st(a, b) { return a[0] - b[0] } function order() { var stride = this.stride var terms = new Array(stride.length) var i for(i=0; i<terms.length; ++i) { terms[i] = [Math.abs(stride[i]), i] } terms.sort(compare1st) var result = new Array(terms.length) for(i=0; i<result.length; ++i) { result[i] = terms[i][1] } return result } function compileConstructor(dtype, dimension) { var className = ["View", dimension, "d", dtype].join("") if(dimension < 0) { className = "View_Nil" + dtype } var useGetters = (dtype === "generic") if(dimension === -1) { //Special case for trivial arrays var code = "function "+className+"(a){this.data=a;};\ var proto="+className+".prototype;\ proto.dtype='"+dtype+"';\ proto.index=function(){return -1};\ proto.size=0;\ proto.dimension=-1;\ proto.shape=proto.stride=proto.order=[];\ proto.lo=proto.hi=proto.transpose=proto.step=\ function(){return new "+className+"(this.data);};\ proto.get=proto.set=function(){};\ proto.pick=function(){return null};\ return function construct_"+className+"(a){return new "+className+"(a);}" var procedure = new Function(code) return procedure() } else if(dimension === 0) { //Special case for 0d arrays var code = "function "+className+"(a,d) {\ this.data = a;\ this.offset = d\ };\ var proto="+className+".prototype;\ proto.dtype='"+dtype+"';\ proto.index=function(){return this.offset};\ proto.dimension=0;\ proto.size=1;\ proto.shape=\ proto.stride=\ proto.order=[];\ proto.lo=\ proto.hi=\ proto.transpose=\ proto.step=function "+className+"_copy() {\ return new "+className+"(this.data,this.offset)\ };\ proto.pick=function "+className+"_pick(){\ return TrivialArray(this.data);\ };\ proto.valueOf=proto.get=function "+className+"_get(){\ return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+ "};\ proto.set=function "+className+"_set(v){\ return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\ };\ return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}" var procedure = new Function("TrivialArray", code) return procedure(CACHED_CONSTRUCTORS[dtype][0]) } var code = ["'use strict'"] //Create constructor for view var indices = iota(dimension) var args = indices.map(function(i) { return "i"+i }) var index_str = "this.offset+" + indices.map(function(i) { return "this.stride[" + i + "]*i" + i }).join("+") var shapeArg = indices.map(function(i) { return "b"+i }).join(",") var strideArg = indices.map(function(i) { return "c"+i }).join(",") code.push( "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a", "this.shape=[" + shapeArg + "]", "this.stride=[" + strideArg + "]", "this.offset=d|0}", "var proto="+className+".prototype", "proto.dtype='"+dtype+"'", "proto.dimension="+dimension) //view.size: code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\ return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"), "}})") //view.order: if(dimension === 1) { code.push("proto.order=[0]") } else { code.push("Object.defineProperty(proto,'order',{get:") if(dimension < 4) { code.push("function "+className+"_order(){") if(dimension === 2) { code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})") } else if(dimension === 3) { code.push( "var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\ if(s0>s1){\ if(s1>s2){\ return [2,1,0];\ }else if(s0>s2){\ return [1,2,0];\ }else{\ return [1,0,2];\ }\ }else if(s0>s2){\ return [2,0,1];\ }else if(s2>s1){\ return [0,1,2];\ }else{\ return [0,2,1];\ }}})") } } else { code.push("ORDER})") } } //view.set(i0, ..., v): code.push( "proto.set=function "+className+"_set("+args.join(",")+",v){") if(useGetters) { code.push("return this.data.set("+index_str+",v)}") } else { code.push("return this.data["+index_str+"]=v}") } //view.get(i0, ...): code.push("proto.get=function "+className+"_get("+args.join(",")+"){") if(useGetters) { code.push("return this.data.get("+index_str+")}") } else { code.push("return this.data["+index_str+"]}") } //view.index: code.push( "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}") //view.hi(): code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+ indices.map(function(i) { return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("") }).join(",")+","+ indices.map(function(i) { return "this.stride["+i + "]" }).join(",")+",this.offset)}") //view.lo(): var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }) var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" }) code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(",")) for(var i=0; i<dimension; ++i) { code.push( "if(typeof i"+i+"==='number'&&i"+i+">=0){\ d=i"+i+"|0;\ b+=c"+i+"*d;\ a"+i+"-=d}") } code.push("return new "+className+"(this.data,"+ indices.map(function(i) { return "a"+i }).join(",")+","+ indices.map(function(i) { return "c"+i }).join(",")+",b)}") //view.step(): code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+ indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" }).join(",")+","+ indices.map(function(i) { return "b"+i+"=this.stride["+i+"]" }).join(",")+",c=this.offset,d=0,ceil=Math.ceil") for(var i=0; i<dimension; ++i) { code.push( "if(typeof i"+i+"==='number'){\ d=i"+i+"|0;\ if(d<0){\ c+=b"+i+"*(a"+i+"-1);\ a"+i+"=ceil(-a"+i+"/d)\ }else{\ a"+i+"=ceil(a"+i+"/d)\ }\ b"+i+"*=d\ }") } code.push("return new "+className+"(this.data,"+ indices.map(function(i) { return "a" + i }).join(",")+","+ indices.map(function(i) { return "b" + i }).join(",")+",c)}") //view.transpose(): var tShape = new Array(dimension) var tStride = new Array(dimension) for(var i=0; i<dimension; ++i) { tShape[i] = "a[i"+i+"]" tStride[i] = "b[i"+i+"]" } code.push("proto.transpose=function "+className+"_transpose("+args+"){"+ args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"), "var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}") //view.pick(): code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset") for(var i=0; i<dimension; ++i) { code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}") } code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}") //Add return statement code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+ indices.map(function(i) { return "shape["+i+"]" }).join(",")+","+ indices.map(function(i) { return "stride["+i+"]" }).join(",")+",offset)}") //Compile procedure var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n")) return procedure(CACHED_CONSTRUCTORS[dtype], order) } function arrayDType(data) { if(hasBuffer) { if(Buffer.isBuffer(data)) { return "buffer" } } if(hasTypedArrays) { switch(Object.prototype.toString.call(data)) { case "[object Float64Array]": return "float64" case "[object Float32Array]": return "float32" case "[object Int8Array]": return "int8" case "[object Int16Array]": return "int16" case "[object Int32Array]": return "int32" case "[object Uint8Array]": return "uint8" case "[object Uint16Array]": return "uint16" case "[object Uint32Array]": return "uint32" case "[object Uint8ClampedArray]": return "uint8_clamped" } } if(Array.isArray(data)) { return "array" } return "generic" } var CACHED_CONSTRUCTORS = { "float32":[], "float64":[], "int8":[], "int16":[], "int32":[], "uint8":[], "uint16":[], "uint32":[], "array":[], "uint8_clamped":[], "buffer":[], "generic":[] } ;(function() { for(var id in CACHED_CONSTRUCTORS) { CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1)) } }); function wrappedNDArrayCtor(data, shape, stride, offset) { if(data === undefined) { var ctor = CACHED_CONSTRUCTORS.array[0] return ctor([]) } else if(typeof data === "number") { data = [data] } if(shape === undefined) { shape = [ data.length ] } var d = shape.length if(stride === undefined) { stride = new Array(d) for(var i=d-1, sz=1; i>=0; --i) { stride[i] = sz sz *= shape[i] } } if(offset === undefined) { offset = 0 for(var i=0; i<d; ++i) { if(stride[i] < 0) { offset -= (shape[i]-1)*stride[i] } } } var dtype = arrayDType(data) var ctor_list = CACHED_CONSTRUCTORS[dtype] while(ctor_list.length <= d+1) { ctor_list.push(compileConstructor(dtype, ctor_list.length-1)) } var ctor = ctor_list[d+1] return ctor(data, shape, stride, offset) } module.exports = wrappedNDArrayCtor }).call(this,require("buffer").Buffer) },{"buffer":1,"iota-array":7}],7:[function(require,module,exports){ "use strict" function iota(n) { var result = new Array(n) for(var i=0; i<n; ++i) { result[i] = i } return result } module.exports = iota },{}]},{},[5]);
define('lodash/internal/createWrapper', ['exports', 'lodash/internal/baseSetData', 'lodash/internal/createBindWrapper', 'lodash/internal/createHybridWrapper', 'lodash/internal/createPartialWrapper', 'lodash/internal/getData', 'lodash/internal/mergeData', 'lodash/internal/setData'], function (exports, _lodashInternalBaseSetData, _lodashInternalCreateBindWrapper, _lodashInternalCreateHybridWrapper, _lodashInternalCreatePartialWrapper, _lodashInternalGetData, _lodashInternalMergeData, _lodashInternalSetData) { 'use strict'; /** Used to compose bitmasks for wrapper metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of flags. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = undefined; } length -= holders ? holders.length : 0; if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : (0, _lodashInternalGetData['default'])(func), newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; if (data) { (0, _lodashInternalMergeData['default'])(newData, data); bitmask = newData[1]; arity = newData[9]; } newData[9] = arity == null ? isBindKey ? 0 : func.length : nativeMax(arity - length, 0) || 0; if (bitmask == BIND_FLAG) { var result = (0, _lodashInternalCreateBindWrapper['default'])(newData[0], newData[2]); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { result = _lodashInternalCreatePartialWrapper['default'].apply(undefined, newData); } else { result = _lodashInternalCreateHybridWrapper['default'].apply(undefined, newData); } var setter = data ? _lodashInternalBaseSetData['default'] : _lodashInternalSetData['default']; return setter(result, newData); } exports['default'] = createWrapper; });
Clazz.declarePackage ("JU"); Clazz.load (["JU.V3"], "JU.Measure", ["java.lang.Float", "javajs.api.Interface", "JU.Lst", "$.P3", "$.P4", "$.Quat"], function () { c$ = Clazz.declareType (JU, "Measure"); c$.computeAngle = Clazz.defineMethod (c$, "computeAngle", function (pointA, pointB, pointC, vectorBA, vectorBC, asDegrees) { vectorBA.sub2 (pointA, pointB); vectorBC.sub2 (pointC, pointB); var angle = vectorBA.angle (vectorBC); return (asDegrees ? angle / 0.017453292 : angle); }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3,~B"); c$.computeAngleABC = Clazz.defineMethod (c$, "computeAngleABC", function (pointA, pointB, pointC, asDegrees) { var vectorBA = new JU.V3 (); var vectorBC = new JU.V3 (); return JU.Measure.computeAngle (pointA, pointB, pointC, vectorBA, vectorBC, asDegrees); }, "JU.T3,JU.T3,JU.T3,~B"); c$.computeTorsion = Clazz.defineMethod (c$, "computeTorsion", function (p1, p2, p3, p4, asDegrees) { var ijx = p1.x - p2.x; var ijy = p1.y - p2.y; var ijz = p1.z - p2.z; var kjx = p3.x - p2.x; var kjy = p3.y - p2.y; var kjz = p3.z - p2.z; var klx = p3.x - p4.x; var kly = p3.y - p4.y; var klz = p3.z - p4.z; var ax = ijy * kjz - ijz * kjy; var ay = ijz * kjx - ijx * kjz; var az = ijx * kjy - ijy * kjx; var cx = kjy * klz - kjz * kly; var cy = kjz * klx - kjx * klz; var cz = kjx * kly - kjy * klx; var ai2 = 1 / (ax * ax + ay * ay + az * az); var ci2 = 1 / (cx * cx + cy * cy + cz * cz); var ai = Math.sqrt (ai2); var ci = Math.sqrt (ci2); var denom = ai * ci; var cross = ax * cx + ay * cy + az * cz; var cosang = cross * denom; if (cosang > 1) { cosang = 1; }if (cosang < -1) { cosang = -1; }var torsion = Math.acos (cosang); var dot = ijx * cx + ijy * cy + ijz * cz; var absDot = Math.abs (dot); torsion = (dot / absDot > 0) ? torsion : -torsion; return (asDegrees ? torsion / 0.017453292 : torsion); }, "JU.T3,JU.T3,JU.T3,JU.T3,~B"); c$.computeHelicalAxis = Clazz.defineMethod (c$, "computeHelicalAxis", function (a, b, dq) { var vab = new JU.V3 (); vab.sub2 (b, a); var theta = dq.getTheta (); var n = dq.getNormal (); var v_dot_n = vab.dot (n); if (Math.abs (v_dot_n) < 0.0001) v_dot_n = 0; var va_prime_d = new JU.V3 (); va_prime_d.cross (vab, n); if (va_prime_d.dot (va_prime_d) != 0) va_prime_d.normalize (); var vda = new JU.V3 (); var vcb = JU.V3.newV (n); if (v_dot_n == 0) v_dot_n = 1.4E-45; vcb.scale (v_dot_n); vda.sub2 (vcb, vab); vda.scale (0.5); va_prime_d.scale (theta == 0 ? 0 : (vda.length () / Math.tan (theta / 2 / 180 * 3.141592653589793))); var r = JU.V3.newV (va_prime_d); if (theta != 0) r.add (vda); var pt_a_prime = JU.P3.newP (a); pt_a_prime.sub (r); if (v_dot_n != 1.4E-45) n.scale (v_dot_n); var pt_b_prime = JU.P3.newP (pt_a_prime); pt_b_prime.add (n); theta = JU.Measure.computeTorsion (a, pt_a_prime, pt_b_prime, b, true); if (Float.isNaN (theta) || r.length () < 0.0001) theta = dq.getThetaDirectedV (n); var residuesPerTurn = Math.abs (theta == 0 ? 0 : 360 / theta); var pitch = Math.abs (v_dot_n == 1.4E-45 ? 0 : n.length () * (theta == 0 ? 1 : 360 / theta)); return Clazz.newArray (-1, [pt_a_prime, n, r, JU.P3.new3 (theta, pitch, residuesPerTurn), pt_b_prime]); }, "JU.P3,JU.P3,JU.Quat"); c$.getPlaneThroughPoints = Clazz.defineMethod (c$, "getPlaneThroughPoints", function (pointA, pointB, pointC, vNorm, vAB, plane) { var w = JU.Measure.getNormalThroughPoints (pointA, pointB, pointC, vNorm, vAB); plane.set4 (vNorm.x, vNorm.y, vNorm.z, w); return plane; }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3,JU.P4"); c$.getPlaneThroughPoint = Clazz.defineMethod (c$, "getPlaneThroughPoint", function (pt, normal, plane) { plane.set4 (normal.x, normal.y, normal.z, -normal.dot (pt)); }, "JU.T3,JU.V3,JU.P4"); c$.distanceToPlane = Clazz.defineMethod (c$, "distanceToPlane", function (plane, pt) { return (plane == null ? NaN : (plane.dot (pt) + plane.w) / Math.sqrt (plane.dot (plane))); }, "JU.P4,JU.T3"); c$.directedDistanceToPlane = Clazz.defineMethod (c$, "directedDistanceToPlane", function (pt, plane, ptref) { var f = plane.dot (pt) + plane.w; var f1 = plane.dot (ptref) + plane.w; return Math.signum (f1) * f / Math.sqrt (plane.dot (plane)); }, "JU.P3,JU.P4,JU.P3"); c$.distanceToPlaneD = Clazz.defineMethod (c$, "distanceToPlaneD", function (plane, d, pt) { return (plane == null ? NaN : (plane.dot (pt) + plane.w) / d); }, "JU.P4,~N,JU.P3"); c$.distanceToPlaneV = Clazz.defineMethod (c$, "distanceToPlaneV", function (norm, w, pt) { return (norm == null ? NaN : (norm.dot (pt) + w) / Math.sqrt (norm.dot (norm))); }, "JU.V3,~N,JU.P3"); c$.calcNormalizedNormal = Clazz.defineMethod (c$, "calcNormalizedNormal", function (pointA, pointB, pointC, vNormNorm, vAB) { vAB.sub2 (pointB, pointA); vNormNorm.sub2 (pointC, pointA); vNormNorm.cross (vAB, vNormNorm); vNormNorm.normalize (); }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3"); c$.getDirectedNormalThroughPoints = Clazz.defineMethod (c$, "getDirectedNormalThroughPoints", function (pointA, pointB, pointC, ptRef, vNorm, vAB) { var nd = JU.Measure.getNormalThroughPoints (pointA, pointB, pointC, vNorm, vAB); if (ptRef != null) { var pt0 = JU.P3.newP (pointA); pt0.add (vNorm); var d = pt0.distance (ptRef); pt0.sub2 (pointA, vNorm); if (d > pt0.distance (ptRef)) { vNorm.scale (-1); nd = -nd; }}return nd; }, "JU.T3,JU.T3,JU.T3,JU.T3,JU.V3,JU.V3"); c$.getNormalThroughPoints = Clazz.defineMethod (c$, "getNormalThroughPoints", function (pointA, pointB, pointC, vNorm, vTemp) { JU.Measure.calcNormalizedNormal (pointA, pointB, pointC, vNorm, vTemp); vTemp.setT (pointA); return -vTemp.dot (vNorm); }, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3"); c$.getPlaneProjection = Clazz.defineMethod (c$, "getPlaneProjection", function (pt, plane, ptProj, vNorm) { var dist = JU.Measure.distanceToPlane (plane, pt); vNorm.set (plane.x, plane.y, plane.z); vNorm.normalize (); vNorm.scale (-dist); ptProj.add2 (pt, vNorm); }, "JU.P3,JU.P4,JU.P3,JU.V3"); c$.getNormalFromCenter = Clazz.defineMethod (c$, "getNormalFromCenter", function (ptCenter, ptA, ptB, ptC, isOutward, normal, vTemp) { var d = JU.Measure.getNormalThroughPoints (ptA, ptB, ptC, normal, vTemp); var isReversed = (JU.Measure.distanceToPlaneV (normal, d, ptCenter) > 0); if (isReversed == isOutward) normal.scale (-1.0); return !isReversed; }, "JU.P3,JU.P3,JU.P3,JU.P3,~B,JU.V3,JU.V3"); c$.getNormalToLine = Clazz.defineMethod (c$, "getNormalToLine", function (pointA, pointB, vNormNorm) { vNormNorm.sub2 (pointA, pointB); vNormNorm.cross (vNormNorm, JU.Measure.axisY); vNormNorm.normalize (); if (Float.isNaN (vNormNorm.x)) vNormNorm.set (1, 0, 0); }, "JU.P3,JU.P3,JU.V3"); c$.getBisectingPlane = Clazz.defineMethod (c$, "getBisectingPlane", function (pointA, vAB, ptTemp, vTemp, plane) { ptTemp.scaleAdd2 (0.5, vAB, pointA); vTemp.setT (vAB); vTemp.normalize (); JU.Measure.getPlaneThroughPoint (ptTemp, vTemp, plane); }, "JU.P3,JU.V3,JU.T3,JU.V3,JU.P4"); c$.projectOntoAxis = Clazz.defineMethod (c$, "projectOntoAxis", function (point, axisA, axisUnitVector, vectorProjection) { vectorProjection.sub2 (point, axisA); var projectedLength = vectorProjection.dot (axisUnitVector); point.scaleAdd2 (projectedLength, axisUnitVector, axisA); vectorProjection.sub2 (point, axisA); }, "JU.P3,JU.P3,JU.V3,JU.V3"); c$.calcBestAxisThroughPoints = Clazz.defineMethod (c$, "calcBestAxisThroughPoints", function (points, axisA, axisUnitVector, vectorProjection, nTriesMax) { var nPoints = points.length; axisA.setT (points[0]); axisUnitVector.sub2 (points[nPoints - 1], axisA); axisUnitVector.normalize (); JU.Measure.calcAveragePointN (points, nPoints, axisA); var nTries = 0; while (nTries++ < nTriesMax && JU.Measure.findAxis (points, nPoints, axisA, axisUnitVector, vectorProjection) > 0.001) { } var tempA = JU.P3.newP (points[0]); JU.Measure.projectOntoAxis (tempA, axisA, axisUnitVector, vectorProjection); axisA.setT (tempA); }, "~A,JU.P3,JU.V3,JU.V3,~N"); c$.findAxis = Clazz.defineMethod (c$, "findAxis", function (points, nPoints, axisA, axisUnitVector, vectorProjection) { var sumXiYi = new JU.V3 (); var vTemp = new JU.V3 (); var pt = new JU.P3 (); var ptProj = new JU.P3 (); var a = JU.V3.newV (axisUnitVector); var sum_Xi2 = 0; for (var i = nPoints; --i >= 0; ) { pt.setT (points[i]); ptProj.setT (pt); JU.Measure.projectOntoAxis (ptProj, axisA, axisUnitVector, vectorProjection); vTemp.sub2 (pt, ptProj); vTemp.cross (vectorProjection, vTemp); sumXiYi.add (vTemp); sum_Xi2 += vectorProjection.lengthSquared (); } var m = JU.V3.newV (sumXiYi); m.scale (1 / sum_Xi2); vTemp.cross (m, axisUnitVector); axisUnitVector.add (vTemp); axisUnitVector.normalize (); vTemp.sub2 (axisUnitVector, a); return vTemp.length (); }, "~A,~N,JU.P3,JU.V3,JU.V3"); c$.calcAveragePoint = Clazz.defineMethod (c$, "calcAveragePoint", function (pointA, pointB, pointC) { pointC.set ((pointA.x + pointB.x) / 2, (pointA.y + pointB.y) / 2, (pointA.z + pointB.z) / 2); }, "JU.P3,JU.P3,JU.P3"); c$.calcAveragePointN = Clazz.defineMethod (c$, "calcAveragePointN", function (points, nPoints, averagePoint) { averagePoint.setT (points[0]); for (var i = 1; i < nPoints; i++) averagePoint.add (points[i]); averagePoint.scale (1 / nPoints); }, "~A,~N,JU.P3"); c$.transformPoints = Clazz.defineMethod (c$, "transformPoints", function (vPts, m4, center) { var v = new JU.Lst (); for (var i = 0; i < vPts.size (); i++) { var pt = JU.P3.newP (vPts.get (i)); pt.sub (center); m4.rotTrans (pt); pt.add (center); v.addLast (pt); } return v; }, "JU.Lst,JU.M4,JU.P3"); c$.isInTetrahedron = Clazz.defineMethod (c$, "isInTetrahedron", function (pt, ptA, ptB, ptC, ptD, plane, vTemp, vTemp2, fullyEnclosed) { var b = (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptC, ptD, ptA, vTemp, vTemp2, plane), pt) >= 0); if (b != (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptA, ptD, ptB, vTemp, vTemp2, plane), pt) >= 0)) return false; if (b != (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptB, ptD, ptC, vTemp, vTemp2, plane), pt) >= 0)) return false; var d = JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptA, ptB, ptC, vTemp, vTemp2, plane), pt); if (fullyEnclosed) return (b == (d >= 0)); var d1 = JU.Measure.distanceToPlane (plane, ptD); return d1 * d <= 0 || Math.abs (d1) > Math.abs (d); }, "JU.P3,JU.P3,JU.P3,JU.P3,JU.P3,JU.P4,JU.V3,JU.V3,~B"); c$.getIntersectionPP = Clazz.defineMethod (c$, "getIntersectionPP", function (plane1, plane2) { var a1 = plane1.x; var b1 = plane1.y; var c1 = plane1.z; var d1 = plane1.w; var a2 = plane2.x; var b2 = plane2.y; var c2 = plane2.z; var d2 = plane2.w; var norm1 = JU.V3.new3 (a1, b1, c1); var norm2 = JU.V3.new3 (a2, b2, c2); var nxn = new JU.V3 (); nxn.cross (norm1, norm2); var ax = Math.abs (nxn.x); var ay = Math.abs (nxn.y); var az = Math.abs (nxn.z); var x; var y; var z; var diff; var type = (ax > ay ? (ax > az ? 1 : 3) : ay > az ? 2 : 3); switch (type) { case 1: x = 0; diff = (b1 * c2 - b2 * c1); if (Math.abs (diff) < 0.01) return null; y = (c1 * d2 - c2 * d1) / diff; z = (b2 * d1 - d2 * b1) / diff; break; case 2: diff = (a1 * c2 - a2 * c1); if (Math.abs (diff) < 0.01) return null; x = (c1 * d2 - c2 * d1) / diff; y = 0; z = (a2 * d1 - d2 * a1) / diff; break; case 3: default: diff = (a1 * b2 - a2 * b1); if (Math.abs (diff) < 0.01) return null; x = (b1 * d2 - b2 * d1) / diff; y = (a2 * d1 - d2 * a1) / diff; z = 0; } var list = new JU.Lst (); list.addLast (JU.P3.new3 (x, y, z)); nxn.normalize (); list.addLast (nxn); return list; }, "JU.P4,JU.P4"); c$.getIntersection = Clazz.defineMethod (c$, "getIntersection", function (pt1, v, plane, ptRet, tempNorm, vTemp) { JU.Measure.getPlaneProjection (pt1, plane, ptRet, tempNorm); tempNorm.set (plane.x, plane.y, plane.z); tempNorm.normalize (); if (v == null) v = JU.V3.newV (tempNorm); var l_dot_n = v.dot (tempNorm); if (Math.abs (l_dot_n) < 0.01) return null; vTemp.sub2 (ptRet, pt1); ptRet.scaleAdd2 (vTemp.dot (tempNorm) / l_dot_n, v, pt1); return ptRet; }, "JU.P3,JU.V3,JU.P4,JU.P3,JU.V3,JU.V3"); c$.calculateQuaternionRotation = Clazz.defineMethod (c$, "calculateQuaternionRotation", function (centerAndPoints, retStddev) { retStddev[1] = NaN; var q = new JU.Quat (); if (centerAndPoints[0].length == 1 || centerAndPoints[0].length != centerAndPoints[1].length) return q; var n = centerAndPoints[0].length - 1; if (n < 2) return q; var Sxx = 0; var Sxy = 0; var Sxz = 0; var Syx = 0; var Syy = 0; var Syz = 0; var Szx = 0; var Szy = 0; var Szz = 0; var ptA = new JU.P3 (); var ptB = new JU.P3 (); for (var i = n + 1; --i >= 1; ) { var aij = centerAndPoints[0][i]; var bij = centerAndPoints[1][i]; ptA.sub2 (aij, centerAndPoints[0][0]); ptB.sub2 (bij, centerAndPoints[0][1]); Sxx += ptA.x * ptB.x; Sxy += ptA.x * ptB.y; Sxz += ptA.x * ptB.z; Syx += ptA.y * ptB.x; Syy += ptA.y * ptB.y; Syz += ptA.y * ptB.z; Szx += ptA.z * ptB.x; Szy += ptA.z * ptB.y; Szz += ptA.z * ptB.z; } retStddev[0] = JU.Measure.getRmsd (centerAndPoints, q); var N = Clazz.newDoubleArray (4, 4, 0); N[0][0] = Sxx + Syy + Szz; N[0][1] = N[1][0] = Syz - Szy; N[0][2] = N[2][0] = Szx - Sxz; N[0][3] = N[3][0] = Sxy - Syx; N[1][1] = Sxx - Syy - Szz; N[1][2] = N[2][1] = Sxy + Syx; N[1][3] = N[3][1] = Szx + Sxz; N[2][2] = -Sxx + Syy - Szz; N[2][3] = N[3][2] = Syz + Szy; N[3][3] = -Sxx - Syy + Szz; var v = (javajs.api.Interface.getInterface ("JU.Eigen")).setM (N).getEigenvectorsFloatTransposed ()[3]; q = JU.Quat.newP4 (JU.P4.new4 (v[1], v[2], v[3], v[0])); retStddev[1] = JU.Measure.getRmsd (centerAndPoints, q); return q; }, "~A,~A"); c$.getTransformMatrix4 = Clazz.defineMethod (c$, "getTransformMatrix4", function (ptsA, ptsB, m, centerA) { var cptsA = JU.Measure.getCenterAndPoints (ptsA); var cptsB = JU.Measure.getCenterAndPoints (ptsB); var retStddev = Clazz.newFloatArray (2, 0); var q = JU.Measure.calculateQuaternionRotation ( Clazz.newArray (-1, [cptsA, cptsB]), retStddev); var r = q.getMatrix (); if (centerA == null) r.rotate (cptsA[0]); else centerA.setT (cptsA[0]); var t = JU.V3.newVsub (cptsB[0], cptsA[0]); m.setMV (r, t); return retStddev[1]; }, "JU.Lst,JU.Lst,JU.M4,JU.P3"); c$.getCenterAndPoints = Clazz.defineMethod (c$, "getCenterAndPoints", function (vPts) { var n = vPts.size (); var pts = new Array (n + 1); pts[0] = new JU.P3 (); if (n > 0) { for (var i = 0; i < n; i++) { pts[0].add (pts[i + 1] = vPts.get (i)); } pts[0].scale (1 / n); }return pts; }, "JU.Lst"); c$.getRmsd = Clazz.defineMethod (c$, "getRmsd", function (centerAndPoints, q) { var sum2 = 0; var ptsA = centerAndPoints[0]; var ptsB = centerAndPoints[1]; var cA = ptsA[0]; var cB = ptsB[0]; var n = ptsA.length - 1; var ptAnew = new JU.P3 (); for (var i = n + 1; --i >= 1; ) { ptAnew.sub2 (ptsA[i], cA); q.transform2 (ptAnew, ptAnew).add (cB); sum2 += ptAnew.distanceSquared (ptsB[i]); } return Math.sqrt (sum2 / n); }, "~A,JU.Quat"); Clazz.defineStatics (c$, "radiansPerDegree", (0.017453292519943295)); c$.axisY = c$.prototype.axisY = JU.V3.new3 (0, 1, 0); });
import Ember from 'ember'; export default Ember.Object.extend({ content: {}, contentLength: 0, add: function(obj) { var id = this.generateId(); this.get('content')[id] = obj; this.incrementProperty("contentLength"); return id; }, getObj: function(key) { var res = this.get('content')[key]; if (!res) { throw "no obj for key "+key; } return res; }, generateId: function() { var num = Math.random() * 1000000000000.0; num = parseInt(num); num = ""+num; return num; }, keys: function() { var res = []; for (var key in this.get('content')) { res.push(key); } return Ember.A(res); }, lengthBinding: "contentLength" });
require('ember-runtime/core'); require('ember-runtime/system/core_object'); require('ember-runtime/mixins/mutable_enumerable'); require('ember-runtime/mixins/copyable'); require('ember-runtime/mixins/freezable'); /** @module ember @submodule ember-runtime */ var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isNone = Ember.isNone, fmt = Ember.String.fmt; /** An unordered collection of objects. A Set works a bit like an array except that its items are not ordered. You can create a set to efficiently test for membership for an object. You can also iterate through a set just like an array, even accessing objects by index, however there is no guarantee as to their order. All Sets are observable via the Enumerable Observer API - which works on any enumerable object including both Sets and Arrays. ## Creating a Set You can create a set like you would most objects using `new Ember.Set()`. Most new sets you create will be empty, but you can also initialize the set with some content by passing an array or other enumerable of objects to the constructor. Finally, you can pass in an existing set and the set will be copied. You can also create a copy of a set by calling `Ember.Set#copy()`. ```javascript // creates a new empty set var foundNames = new Ember.Set(); // creates a set with four names in it. var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P // creates a copy of the names set. var namesCopy = new Ember.Set(names); // same as above. var anotherNamesCopy = names.copy(); ``` ## Adding/Removing Objects You generally add or remove objects from a set using `add()` or `remove()`. You can add any type of object including primitives such as numbers, strings, and booleans. Unlike arrays, objects can only exist one time in a set. If you call `add()` on a set with the same object multiple times, the object will only be added once. Likewise, calling `remove()` with the same object multiple times will remove the object the first time and have no effect on future calls until you add the object to the set again. NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do so will be ignored. In addition to add/remove you can also call `push()`/`pop()`. Push behaves just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary object, remove it and return it. This is a good way to use a set as a job queue when you don't care which order the jobs are executed in. ## Testing for an Object To test for an object's presence in a set you simply call `Ember.Set#contains()`. ## Observing changes When using `Ember.Set`, you can observe the `"[]"` property to be alerted whenever the content changes. You can also add an enumerable observer to the set to be notified of specific objects that are added and removed from the set. See `Ember.Enumerable` for more information on enumerables. This is often unhelpful. If you are filtering sets of objects, for instance, it is very inefficient to re-filter all of the items each time the set changes. It would be better if you could just adjust the filtered set based on what was changed on the original set. The same issue applies to merging sets, as well. ## Other Methods `Ember.Set` primary implements other mixin APIs. For a complete reference on the methods you will use with `Ember.Set`, please consult these mixins. The most useful ones will be `Ember.Enumerable` and `Ember.MutableEnumerable` which implement most of the common iterator methods you are used to on Array. Note that you can also use the `Ember.Copyable` and `Ember.Freezable` APIs on `Ember.Set` as well. Once a set is frozen it can no longer be modified. The benefit of this is that when you call `frozenCopy()` on it, Ember will avoid making copies of the set. This allows you to write code that can know with certainty when the underlying set data will or will not be modified. @class Set @namespace Ember @extends Ember.CoreObject @uses Ember.MutableEnumerable @uses Ember.Copyable @uses Ember.Freezable @since Ember 0.9 */ Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable, /** @scope Ember.Set.prototype */ { // .......................................................... // IMPLEMENT ENUMERABLE APIS // /** This property will change as the number of objects in the set changes. @property length @type number @default 0 */ length: 0, /** Clears the set. This is useful if you want to reuse an existing set without having to recreate it. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.length; // 3 colors.clear(); colors.length; // 0 ``` @method clear @return {Ember.Set} An empty Set */ clear: function() { if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); } var len = get(this, 'length'); if (len === 0) { return this; } var guid; this.enumerableContentWillChange(len, 0); Ember.propertyWillChange(this, 'firstObject'); Ember.propertyWillChange(this, 'lastObject'); for (var i=0; i < len; i++){ guid = guidFor(this[i]); delete this[guid]; delete this[i]; } set(this, 'length', 0); Ember.propertyDidChange(this, 'firstObject'); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(len, 0); return this; }, /** Returns true if the passed object is also an enumerable that contains the same objects as the receiver. ```javascript var colors = ["red", "green", "blue"], same_colors = new Ember.Set(colors); same_colors.isEqual(colors); // true same_colors.isEqual(["purple", "brown"]); // false ``` @method isEqual @param {Ember.Set} obj the other object. @return {Boolean} */ isEqual: function(obj) { // fail fast if (!Ember.Enumerable.detect(obj)) return false; var loc = get(this, 'length'); if (get(obj, 'length') !== loc) return false; while(--loc >= 0) { if (!obj.contains(this[loc])) return false; } return true; }, /** Adds an object to the set. Only non-`null` objects can be added to a set and those can only be added once. If the object is already in the set or the passed value is null this method will have no effect. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.add("blue"); // ["blue"] colors.add("blue"); // ["blue"] colors.add("red"); // ["blue", "red"] colors.add(null); // ["blue", "red"] colors.add(undefined); // ["blue", "red"] ``` @method add @param {Object} obj The object to add. @return {Ember.Set} The set itself. */ add: Ember.aliasMethod('addObject'), /** Removes the object from the set if it is found. If you pass a `null` value or an object that is already not in the set, this method will have no effect. This is an alias for `Ember.MutableEnumerable.removeObject()`. ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.remove("red"); // ["blue", "green"] colors.remove("purple"); // ["blue", "green"] colors.remove(null); // ["blue", "green"] ``` @method remove @param {Object} obj The object to remove @return {Ember.Set} The set itself. */ remove: Ember.aliasMethod('removeObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.pop(); // "blue" colors.pop(); // "green" colors.pop(); // null ``` @method pop @return {Object} The removed object from the set or null. */ pop: function() { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); var obj = this.length > 0 ? this[this.length-1] : null; this.remove(obj); return obj; }, /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias for `Ember.MutableEnumerable.addObject()`. ```javascript var colors = new Ember.Set(); colors.push("red"); // ["red"] colors.push("green"); // ["red", "green"] colors.push("blue"); // ["red", "green", "blue"] ``` @method push @return {Ember.Set} The set itself. */ push: Ember.aliasMethod('addObject'), /** Removes the last element from the set and returns it, or `null` if it's empty. This is an alias for `Ember.Set.pop()`. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.shift(); // "blue" colors.shift(); // "green" colors.shift(); // null ``` @method shift @return {Object} The removed object from the set or null. */ shift: Ember.aliasMethod('pop'), /** Inserts the given object on to the end of the set. It returns the set itself. This is an alias of `Ember.Set.push()` ```javascript var colors = new Ember.Set(); colors.unshift("red"); // ["red"] colors.unshift("green"); // ["red", "green"] colors.unshift("blue"); // ["red", "green", "blue"] ``` @method unshift @return {Ember.Set} The set itself. */ unshift: Ember.aliasMethod('push'), /** Adds each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.addObjects()` ```javascript var colors = new Ember.Set(); colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"] ``` @method addEach @param {Ember.Enumerable} objects the objects to add. @return {Ember.Set} The set itself. */ addEach: Ember.aliasMethod('addObjects'), /** Removes each object in the passed enumerable to the set. This is an alias of `Ember.MutableEnumerable.removeObjects()` ```javascript var colors = new Ember.Set(["red", "green", "blue"]); colors.removeEach(["red", "blue"]); // ["green"] ``` @method removeEach @param {Ember.Enumerable} objects the objects to remove. @return {Ember.Set} The set itself. */ removeEach: Ember.aliasMethod('removeObjects'), // .......................................................... // PRIVATE ENUMERABLE SUPPORT // init: function(items) { this._super(); if (items) this.addObjects(items); }, // implement Ember.Enumerable nextObject: function(idx) { return this[idx]; }, // more optimized version firstObject: Ember.computed(function() { return this.length > 0 ? this[0] : undefined; }), // more optimized version lastObject: Ember.computed(function() { return this.length > 0 ? this[this.length-1] : undefined; }), // implements Ember.MutableEnumerable addObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (isNone(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), added ; if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added added = [obj]; this.enumerableContentWillChange(null, added); Ember.propertyWillChange(this, 'lastObject'); len = get(this, 'length'); this[guid] = len; this[len] = obj; set(this, 'length', len+1); Ember.propertyDidChange(this, 'lastObject'); this.enumerableContentDidChange(null, added); return this; }, // implements Ember.MutableEnumerable removeObject: function(obj) { if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR); if (isNone(obj)) return this; // nothing to do var guid = guidFor(obj), idx = this[guid], len = get(this, 'length'), isFirst = idx === 0, isLast = idx === len-1, last, removed; if (idx>=0 && idx<len && (this[idx] === obj)) { removed = [obj]; this.enumerableContentWillChange(removed, null); if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); } if (isLast) { Ember.propertyWillChange(this, 'lastObject'); } // swap items - basically move the item to the end so it can be removed if (idx < len-1) { last = this[len-1]; this[idx] = last; this[guidFor(last)] = idx; } delete this[guid]; delete this[len-1]; set(this, 'length', len-1); if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); } if (isLast) { Ember.propertyDidChange(this, 'lastObject'); } this.enumerableContentDidChange(removed, null); } return this; }, // optimized version contains: function(obj) { return this[guidFor(obj)]>=0; }, copy: function() { var C = this.constructor, ret = new C(), loc = get(this, 'length'); set(ret, 'length', loc); while(--loc>=0) { ret[loc] = this[loc]; ret[guidFor(this[loc])] = loc; } return ret; }, toString: function() { var len = this.length, idx, array = []; for(idx = 0; idx < len; idx++) { array[idx] = this[idx]; } return fmt("Ember.Set<%@>", [array.join(',')]); } });
/*! * Bootstrap-select v1.13.2 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2018 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Нищо избрано', noneResultsText: 'Няма резултат за {0}', countSelectedText: function (numSelected, numTotal) { return (numSelected == 1) ? "{0} избран елемент" : "{0} избрани елемента"; }, maxOptionsText: function (numAll, numGroup) { return [ (numAll == 1) ? 'Лимита е достигнат ({n} елемент максимум)' : 'Лимита е достигнат ({n} елемента максимум)', (numGroup == 1) ? 'Груповия лимит е достигнат ({n} елемент максимум)' : 'Груповия лимит е достигнат ({n} елемента максимум)' ]; }, selectAllText: 'Избери всички', deselectAllText: 'Размаркирай всички', multipleSeparator: ', ' }; })(jQuery); }));
'use strict'; // Load modules const Http = require('http'); const Stream = require('stream'); // Declare internals const internals = {}; exports = module.exports = class Response extends Http.ServerResponse { constructor(req, onEnd) { super({ method: req.method, httpVersionMajor: 1, httpVersionMinor: 1 }); this._shot = { headers: null, trailers: {}, payloadChunks: [] }; this._headers = {}; // This forces node@8 to always render the headers this.assignSocket(internals.nullSocket()); this.once('finish', () => { const res = internals.payload(this); res.raw.req = req; process.nextTick(() => onEnd(res)); }); } writeHead() { const result = super.writeHead.apply(this, arguments); this._shot.headers = Object.assign({}, this._headers); // Should be .getHeaders() since node v7.7 // Add raw headers ['Date', 'Connection', 'Transfer-Encoding'].forEach((name) => { const regex = new RegExp('\\r\\n' + name + ': ([^\\r]*)\\r\\n'); const field = this._header.match(regex); if (field) { this._shot.headers[name.toLowerCase()] = field[1]; } }); return result; } write(data, encoding, callback) { super.write(data, encoding, callback); this._shot.payloadChunks.push(new Buffer(data, encoding)); return true; // Write always returns false when disconnected } end(data, encoding, callback) { if (data) { this.write(data, encoding); } super.end(callback); this.emit('finish'); } destroy() { } addTrailers(trailers) { for (const key in trailers) { this._shot.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim(); } } }; internals.payload = function (response) { // Prepare response object const res = { raw: { res: response }, headers: response._shot.headers, statusCode: response.statusCode, statusMessage: response.statusMessage, trailers: {} }; // Prepare payload and trailers const rawBuffer = Buffer.concat(response._shot.payloadChunks); res.rawPayload = rawBuffer; res.payload = rawBuffer.toString(); res.trailers = response._shot.trailers; return res; }; // Throws away all written data to prevent response from buffering payload internals.nullSocket = function () { return new Stream.Writable({ write(chunk, encoding, callback) { setImmediate(callback); } }); };
var chownr = require('chownr') var tar = require('tar-stream') var pump = require('pump') var mkdirp = require('mkdirp') var fs = require('fs') var path = require('path') var os = require('os') var win32 = os.platform() === 'win32' var noop = function () {} var echo = function (name) { return name } var normalize = !win32 ? echo : function (name) { return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_') } var statAll = function (fs, stat, cwd, ignore, entries, sort) { var queue = entries || ['.'] return function loop (callback) { if (!queue.length) return callback() var next = queue.shift() var nextAbs = path.join(cwd, next) stat(nextAbs, function (err, stat) { if (err) return callback(err) if (!stat.isDirectory()) return callback(null, next, stat) fs.readdir(nextAbs, function (err, files) { if (err) return callback(err) if (sort) files.sort() for (var i = 0; i < files.length; i++) { if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) } callback(null, next, stat) }) }) } } var strip = function (map, level) { return function (header) { header.name = header.name.split('/').slice(level).join('/') var linkname = header.linkname if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { header.linkname = linkname.split('/').slice(level).join('/') } return map(header) } } exports.pack = function (cwd, opts) { if (!cwd) cwd = '.' if (!opts) opts = {} var xfs = opts.fs || fs var ignore = opts.ignore || opts.filter || noop var map = opts.map || noop var mapStream = opts.mapStream || echo var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) var strict = opts.strict !== false var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 var pack = opts.pack || tar.pack() var finish = opts.finish || noop if (opts.strip) map = strip(map, opts.strip) if (opts.readable) { dmode |= parseInt(555, 8) fmode |= parseInt(444, 8) } if (opts.writable) { dmode |= parseInt(333, 8) fmode |= parseInt(222, 8) } var onsymlink = function (filename, header) { xfs.readlink(path.join(cwd, filename), function (err, linkname) { if (err) return pack.destroy(err) header.linkname = normalize(linkname) pack.entry(header, onnextentry) }) } var onstat = function (err, filename, stat) { if (err) return pack.destroy(err) if (!filename) { if (opts.finalize !== false) pack.finalize() return finish(pack) } if (stat.isSocket()) return onnextentry() // tar does not support sockets... var header = { name: normalize(filename), mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, mtime: stat.mtime, size: stat.size, type: 'file', uid: stat.uid, gid: stat.gid } if (stat.isDirectory()) { header.size = 0 header.type = 'directory' header = map(header) || header return pack.entry(header, onnextentry) } if (stat.isSymbolicLink()) { header.size = 0 header.type = 'symlink' header = map(header) || header return onsymlink(filename, header) } // TODO: add fifo etc... header = map(header) || header if (!stat.isFile()) { if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) return onnextentry() } var entry = pack.entry(header, onnextentry) if (!entry) return var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header) rs.on('error', function (err) { // always forward errors on destroy entry.destroy(err) }) pump(rs, entry) } var onnextentry = function (err) { if (err) return pack.destroy(err) statNext(onstat) } onnextentry() return pack } var head = function (list) { return list.length ? list[list.length - 1] : null } var processGetuid = function () { return process.getuid ? process.getuid() : -1 } var processUmask = function () { return process.umask ? process.umask() : 0 } exports.extract = function (cwd, opts) { if (!cwd) cwd = '.' if (!opts) opts = {} var xfs = opts.fs || fs var ignore = opts.ignore || opts.filter || noop var map = opts.map || noop var mapStream = opts.mapStream || echo var own = opts.chown !== false && !win32 && processGetuid() === 0 var extract = opts.extract || tar.extract() var stack = [] var now = new Date() var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 var strict = opts.strict !== false if (opts.strip) map = strip(map, opts.strip) if (opts.readable) { dmode |= parseInt(555, 8) fmode |= parseInt(444, 8) } if (opts.writable) { dmode |= parseInt(333, 8) fmode |= parseInt(222, 8) } var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry var top while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() if (!top) return cb() xfs.utimes(top[0], now, top[1], cb) } var utimes = function (name, header, cb) { if (opts.utimes === false) return cb() if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? xfs.utimes(name, now, header.mtime, function (err) { if (err) return cb(err) utimesParent(name, cb) }) } var chperm = function (name, header, cb) { var link = header.type === 'symlink' var chmod = link ? xfs.lchmod : xfs.chmod var chown = link ? xfs.lchown : xfs.chown if (!chmod) return cb() var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask chmod(name, mode, function (err) { if (err) return cb(err) if (!own) return cb() if (!chown) return cb() chown(name, header.uid, header.gid, cb) }) } extract.on('entry', function (header, stream, next) { header = map(header) || header header.name = normalize(header.name) var name = path.join(cwd, path.join('/', header.name)) if (ignore(name, header)) { stream.resume() return next() } var stat = function (err) { if (err) return next(err) utimes(name, header, function (err) { if (err) return next(err) if (win32) return next() chperm(name, header, next) }) } var onsymlink = function () { if (win32) return next() // skip symlinks on win for now before it can be tested xfs.unlink(name, function () { xfs.symlink(header.linkname, name, stat) }) } var onlink = function () { if (win32) return next() // skip links on win for now before it can be tested xfs.unlink(name, function () { var srcpath = path.join(cwd, path.join('/', header.linkname)) xfs.link(srcpath, name, function (err) { if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { stream = xfs.createReadStream(srcpath) return onfile() } stat(err) }) }) } var onfile = function () { var ws = xfs.createWriteStream(name) var rs = mapStream(stream, header) ws.on('error', function (err) { // always forward errors on destroy rs.destroy(err) }) pump(rs, ws, function (err) { if (err) return next(err) ws.on('close', stat) }) } if (header.type === 'directory') { stack.push([name, header.mtime]) return mkdirfix(name, { fs: xfs, own: own, uid: header.uid, gid: header.gid }, stat) } var dir = path.dirname(name) validate(xfs, dir, path.join(cwd, '.'), function (err, valid) { if (err) return next(err) if (!valid) return next(new Error(dir + ' is not a valid path')) mkdirfix(dir, { fs: xfs, own: own, uid: header.uid, gid: header.gid }, function (err) { if (err) return next(err) switch (header.type) { case 'file': return onfile() case 'link': return onlink() case 'symlink': return onsymlink() } if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) stream.resume() next() }) }) }) if (opts.finish) extract.on('finish', opts.finish) return extract } function validate (fs, name, root, cb) { if (name === root) return cb(null, true) fs.lstat(name, function (err, st) { if (err && err.code !== 'ENOENT') return cb(err) if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb) cb(null, false) }) } function mkdirfix (name, opts, cb) { mkdirp(name, {fs: opts.fs}, function (err, made) { if (!err && made && opts.own) { chownr(made, opts.uid, opts.gid, cb) } else { cb(err) } }) }
"use strict"; // local import of the exported AngularPage class var angularPage_1 = require('./angularPage'); // The jasmine typings are brought in via DefinitelyTyped ambient typings. describe('angularjs homepage', function () { it('should greet the named user', function () { var angularHomepage = new angularPage_1.AngularHomepage(); angularHomepage.get(); angularHomepage.setName('Julie'); expect(angularHomepage.getGreeting()).toEqual('Hello Julie!'); }); });
import answer from './answer'; var answer2 = answer; export default answer2;
import { Quaternion } from '../math/Quaternion'; import { Vector3 } from '../math/Vector3'; import { Matrix4 } from '../math/Matrix4'; import { EventDispatcher } from './EventDispatcher'; import { Euler } from '../math/Euler'; import { Layers } from './Layers'; import { Matrix3 } from '../math/Matrix3'; import { _Math } from '../math/Math'; /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author elephantatwork / www.elephantatwork.ch */ var object3DId = 0; function Object3D() { Object.defineProperty( this, 'id', { value: object3DId ++ } ); this.uuid = _Math.generateUUID(); this.name = ''; this.type = 'Object3D'; this.parent = null; this.children = []; this.up = Object3D.DefaultUp.clone(); var position = new Vector3(); var rotation = new Euler(); var quaternion = new Quaternion(); var scale = new Vector3( 1, 1, 1 ); function onRotationChange() { quaternion.setFromEuler( rotation, false ); } function onQuaternionChange() { rotation.setFromQuaternion( quaternion, undefined, false ); } rotation.onChange( onRotationChange ); quaternion.onChange( onQuaternionChange ); Object.defineProperties( this, { position: { enumerable: true, value: position }, rotation: { enumerable: true, value: rotation }, quaternion: { enumerable: true, value: quaternion }, scale: { enumerable: true, value: scale }, modelViewMatrix: { value: new Matrix4() }, normalMatrix: { value: new Matrix3() } } ); this.matrix = new Matrix4(); this.matrixWorld = new Matrix4(); this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; this.matrixWorldNeedsUpdate = false; this.layers = new Layers(); this.visible = true; this.castShadow = false; this.receiveShadow = false; this.frustumCulled = true; this.renderOrder = 0; this.userData = {}; } Object3D.DefaultUp = new Vector3( 0, 1, 0 ); Object3D.DefaultMatrixAutoUpdate = true; Object.assign( Object3D.prototype, EventDispatcher.prototype, { isObject3D: true, onBeforeRender: function () {}, onAfterRender: function () {}, applyMatrix: function ( matrix ) { this.matrix.multiplyMatrices( matrix, this.matrix ); this.matrix.decompose( this.position, this.quaternion, this.scale ); }, applyQuaternion: function ( q ) { this.quaternion.premultiply( q ); return this; }, setRotationFromAxisAngle: function ( axis, angle ) { // assumes axis is normalized this.quaternion.setFromAxisAngle( axis, angle ); }, setRotationFromEuler: function ( euler ) { this.quaternion.setFromEuler( euler, true ); }, setRotationFromMatrix: function ( m ) { // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) this.quaternion.setFromRotationMatrix( m ); }, setRotationFromQuaternion: function ( q ) { // assumes q is normalized this.quaternion.copy( q ); }, rotateOnAxis: function () { // rotate object on axis in object space // axis is assumed to be normalized var q1 = new Quaternion(); return function rotateOnAxis( axis, angle ) { q1.setFromAxisAngle( axis, angle ); this.quaternion.multiply( q1 ); return this; }; }(), rotateX: function () { var v1 = new Vector3( 1, 0, 0 ); return function rotateX( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), rotateY: function () { var v1 = new Vector3( 0, 1, 0 ); return function rotateY( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), rotateZ: function () { var v1 = new Vector3( 0, 0, 1 ); return function rotateZ( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), translateOnAxis: function () { // translate object by distance along axis in object space // axis is assumed to be normalized var v1 = new Vector3(); return function translateOnAxis( axis, distance ) { v1.copy( axis ).applyQuaternion( this.quaternion ); this.position.add( v1.multiplyScalar( distance ) ); return this; }; }(), translateX: function () { var v1 = new Vector3( 1, 0, 0 ); return function translateX( distance ) { return this.translateOnAxis( v1, distance ); }; }(), translateY: function () { var v1 = new Vector3( 0, 1, 0 ); return function translateY( distance ) { return this.translateOnAxis( v1, distance ); }; }(), translateZ: function () { var v1 = new Vector3( 0, 0, 1 ); return function translateZ( distance ) { return this.translateOnAxis( v1, distance ); }; }(), localToWorld: function ( vector ) { return vector.applyMatrix4( this.matrixWorld ); }, worldToLocal: function () { var m1 = new Matrix4(); return function worldToLocal( vector ) { return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) ); }; }(), lookAt: function () { // This method does not support objects with rotated and/or translated parent(s) var m1 = new Matrix4(); return function lookAt( vector ) { if ( this.isCamera ) { m1.lookAt( this.position, vector, this.up ); } else { m1.lookAt( vector, this.position, this.up ); } this.quaternion.setFromRotationMatrix( m1 ); }; }(), add: function ( object ) { if ( arguments.length > 1 ) { for ( var i = 0; i < arguments.length; i ++ ) { this.add( arguments[ i ] ); } return this; } if ( object === this ) { console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); return this; } if ( ( object && object.isObject3D ) ) { if ( object.parent !== null ) { object.parent.remove( object ); } object.parent = this; object.dispatchEvent( { type: 'added' } ); this.children.push( object ); } else { console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); } return this; }, remove: function ( object ) { if ( arguments.length > 1 ) { for ( var i = 0; i < arguments.length; i ++ ) { this.remove( arguments[ i ] ); } return this; } var index = this.children.indexOf( object ); if ( index !== - 1 ) { object.parent = null; object.dispatchEvent( { type: 'removed' } ); this.children.splice( index, 1 ); } return this; }, getObjectById: function ( id ) { return this.getObjectByProperty( 'id', id ); }, getObjectByName: function ( name ) { return this.getObjectByProperty( 'name', name ); }, getObjectByProperty: function ( name, value ) { if ( this[ name ] === value ) return this; for ( var i = 0, l = this.children.length; i < l; i ++ ) { var child = this.children[ i ]; var object = child.getObjectByProperty( name, value ); if ( object !== undefined ) { return object; } } return undefined; }, getWorldPosition: function ( optionalTarget ) { var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); return result.setFromMatrixPosition( this.matrixWorld ); }, getWorldQuaternion: function () { var position = new Vector3(); var scale = new Vector3(); return function getWorldQuaternion( optionalTarget ) { var result = optionalTarget || new Quaternion(); this.updateMatrixWorld( true ); this.matrixWorld.decompose( position, result, scale ); return result; }; }(), getWorldRotation: function () { var quaternion = new Quaternion(); return function getWorldRotation( optionalTarget ) { var result = optionalTarget || new Euler(); this.getWorldQuaternion( quaternion ); return result.setFromQuaternion( quaternion, this.rotation.order, false ); }; }(), getWorldScale: function () { var position = new Vector3(); var quaternion = new Quaternion(); return function getWorldScale( optionalTarget ) { var result = optionalTarget || new Vector3(); this.updateMatrixWorld( true ); this.matrixWorld.decompose( position, quaternion, result ); return result; }; }(), getWorldDirection: function () { var quaternion = new Quaternion(); return function getWorldDirection( optionalTarget ) { var result = optionalTarget || new Vector3(); this.getWorldQuaternion( quaternion ); return result.set( 0, 0, 1 ).applyQuaternion( quaternion ); }; }(), raycast: function () {}, traverse: function ( callback ) { callback( this ); var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].traverse( callback ); } }, traverseVisible: function ( callback ) { if ( this.visible === false ) return; callback( this ); var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].traverseVisible( callback ); } }, traverseAncestors: function ( callback ) { var parent = this.parent; if ( parent !== null ) { callback( parent ); parent.traverseAncestors( callback ); } }, updateMatrix: function () { this.matrix.compose( this.position, this.quaternion, this.scale ); this.matrixWorldNeedsUpdate = true; }, updateMatrixWorld: function ( force ) { if ( this.matrixAutoUpdate ) this.updateMatrix(); if ( this.matrixWorldNeedsUpdate || force ) { if ( this.parent === null ) { this.matrixWorld.copy( this.matrix ); } else { this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); } this.matrixWorldNeedsUpdate = false; force = true; } // update children var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].updateMatrixWorld( force ); } }, toJSON: function ( meta ) { // meta is '' when called from JSON.stringify var isRootObject = ( meta === undefined || meta === '' ); var output = {}; // meta is a hash used to collect geometries, materials. // not providing it implies that this is the root object // being serialized. if ( isRootObject ) { // initialize meta obj meta = { geometries: {}, materials: {}, textures: {}, images: {} }; output.metadata = { version: 4.5, type: 'Object', generator: 'Object3D.toJSON' }; } // standard Object3D serialization var object = {}; object.uuid = this.uuid; object.type = this.type; if ( this.name !== '' ) object.name = this.name; if ( this.castShadow === true ) object.castShadow = true; if ( this.receiveShadow === true ) object.receiveShadow = true; if ( this.visible === false ) object.visible = false; if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData; object.matrix = this.matrix.toArray(); // function serialize( library, element ) { if ( library[ element.uuid ] === undefined ) { library[ element.uuid ] = element.toJSON( meta ); } return element.uuid; } if ( this.geometry !== undefined ) { object.geometry = serialize( meta.geometries, this.geometry ); } if ( this.material !== undefined ) { if ( Array.isArray( this.material ) ) { var uuids = []; for ( var i = 0, l = this.material.length; i < l; i ++ ) { uuids.push( serialize( meta.materials, this.material[ i ] ) ); } object.material = uuids; } else { object.material = serialize( meta.materials, this.material ); } } // if ( this.children.length > 0 ) { object.children = []; for ( var i = 0; i < this.children.length; i ++ ) { object.children.push( this.children[ i ].toJSON( meta ).object ); } } if ( isRootObject ) { var geometries = extractFromCache( meta.geometries ); var materials = extractFromCache( meta.materials ); var textures = extractFromCache( meta.textures ); var images = extractFromCache( meta.images ); if ( geometries.length > 0 ) output.geometries = geometries; if ( materials.length > 0 ) output.materials = materials; if ( textures.length > 0 ) output.textures = textures; if ( images.length > 0 ) output.images = images; } output.object = object; return output; // extract data from the cache hash // remove metadata on each item // and return as array function extractFromCache( cache ) { var values = []; for ( var key in cache ) { var data = cache[ key ]; delete data.metadata; values.push( data ); } return values; } }, clone: function ( recursive ) { return new this.constructor().copy( this, recursive ); }, copy: function ( source, recursive ) { if ( recursive === undefined ) recursive = true; this.name = source.name; this.up.copy( source.up ); this.position.copy( source.position ); this.quaternion.copy( source.quaternion ); this.scale.copy( source.scale ); this.matrix.copy( source.matrix ); this.matrixWorld.copy( source.matrixWorld ); this.matrixAutoUpdate = source.matrixAutoUpdate; this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; this.layers.mask = source.layers.mask; this.visible = source.visible; this.castShadow = source.castShadow; this.receiveShadow = source.receiveShadow; this.frustumCulled = source.frustumCulled; this.renderOrder = source.renderOrder; this.userData = JSON.parse( JSON.stringify( source.userData ) ); if ( recursive === true ) { for ( var i = 0; i < source.children.length; i ++ ) { var child = source.children[ i ]; this.add( child.clone() ); } } return this; } } ); export { Object3D };
export default window['%testCafeAutomation%'];
// sensible server which advertises itself via Bonjour // NODE INCLUDES var dgram = require ("dgram"); var fs = require ("fs"); var http = require ("http"); var os = require ("os"); var url = require ("url"); // REGULAR JS INCLUDES // assume that sensible.js lives in the same directory as our mainline var code = fs.readFileSync (require ("path").dirname (process.argv [1]) + "/sensible.js"); eval (code.toString ()); // MAINLINE sensible.ApplicationFactory.createApplication ( function (inError) { if (inError) { console.error ("error during sensible application startup"); console.error (inError); } else { console.log ("sensible application startup"); } } ); // called just before sensible.Application.start() sensible.node.Application.prototype.onBeforeStart = function (inCallback) { console.log ("node.Application.onBeforeStart()"); inCallback (); } // called just after sensible.Application.start() sensible.node.Application.prototype.onAfterStart = function (inCallback) { console.log ("node.Application.onAfterStart()"); inCallback (); }
/** * @fileoverview Restrict usage of duplicate imports. * @author Simen Bekkhus * @copyright 2016 Simen Bekkhus. All rights reserved. * See LICENSE file in root directory for full license. */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ /** * Returns the name of the module imported or re-exported. * * @param {ASTNode} node - A node to get. * @returns {string} the name of the module, or empty string if no name. */ function getValue(node) { if (node && node.source && node.source.value) { return node.source.value.trim(); } return ""; } /** * Checks if the name of the import or export exists in the given array, and reports if so. * * @param {RuleContext} context - The ESLint rule context object. * @param {ASTNode} node - A node to get. * @param {string} value - The name of the imported or exported module. * @param {string[]} array - The array containing other imports or exports in the file. * @param {string} message - A message to be reported after the name of the module * * @returns {void} No return value */ function checkAndReport(context, node, value, array, message) { if (array.indexOf(value) !== -1) { context.report({ node: node, message: "'{{module}}' " + message, data: {module: value} }); } } /** * @callback nodeCallback * @param {ASTNode} node - A node to handle. */ /** * Returns a function handling the imports of a given file * * @param {RuleContext} context - The ESLint rule context object. * @param {boolean} includeExports - Whether or not to check for exports in addition to imports. * @param {string[]} importsInFile - The array containing other imports in the file. * @param {string[]} exportsInFile - The array containing other exports in the file. * * @returns {nodeCallback} A function passed to ESLint to handle the statement. */ function handleImports(context, includeExports, importsInFile, exportsInFile) { return function(node) { var value = getValue(node); if (value) { checkAndReport(context, node, value, importsInFile, "import is duplicated."); if (includeExports) { checkAndReport(context, node, value, exportsInFile, "import is duplicated as export."); } importsInFile.push(value); } }; } /** * Returns a function handling the exports of a given file * * @param {RuleContext} context - The ESLint rule context object. * @param {string[]} importsInFile - The array containing other imports in the file. * @param {string[]} exportsInFile - The array containing other exports in the file. * * @returns {nodeCallback} A function passed to ESLint to handle the statement. */ function handleExports(context, importsInFile, exportsInFile) { return function(node) { var value = getValue(node); if (value) { checkAndReport(context, node, value, exportsInFile, "export is duplicated."); checkAndReport(context, node, value, importsInFile, "export is duplicated as import."); exportsInFile.push(value); } }; } module.exports = function(context) { var includeExports = (context.options[0] || {}).includeExports, importsInFile = [], exportsInFile = []; var handlers = { "ImportDeclaration": handleImports(context, includeExports, importsInFile, exportsInFile) }; if (includeExports) { handlers.ExportNamedDeclaration = handleExports(context, importsInFile, exportsInFile); handlers.ExportAllDeclaration = handleExports(context, importsInFile, exportsInFile); } return handlers; }; module.exports.schema = [{ "type": "object", "properties": { "includeExports": { "type": "boolean" } }, "additionalProperties": false }];
import{generateUtilityClass,generateUtilityClasses}from"@material-ui/unstyled";export function getCardActionAreaUtilityClass(t){return generateUtilityClass("MuiCardActionArea",t)};var cardActionAreaClasses=generateUtilityClasses("MuiCardActionArea",["root","focusVisible","focusHighlight"]);export default cardActionAreaClasses;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var strings={prefixAgo:null,prefixFromNow:null,suffixAgo:"",suffixFromNow:"",seconds:"1m",minute:"1m",minutes:"%dm",hour:"1h",hours:"%dh",day:"1g",days:"%dg",month:"1me",months:"%dme",year:"1a",years:"%da",wordSeparator:" "},_default=strings;exports.default=_default;
// This is not the set of all possible signals. // // It IS, however, the set of all signals that trigger // an exit on either Linux or BSD systems. Linux is a // superset of the signal names supported on BSD, and // the unknown signals just fail to register, so we can // catch that easily enough. // // Don't bother with SIGKILL. It's uncatchable, which // means that we can't fire any callbacks anyway. // // If a user does happen to register a handler on a non- // fatal signal like SIGWINCH or something, and then // exit, it'll end up firing `process.emit('exit')`, so // the handler will be fired anyway. // // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised // artificially, inherently leave the process in a // state from which it is not safe to try and enter JS // listeners. module.exports = [ 'SIGABRT', 'SIGALRM', 'SIGHUP', 'SIGINT', 'SIGTERM' ] if (process.platform !== 'win32') { module.exports.push( 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT' // should detect profiler and enable/disable accordingly. // see #21 // 'SIGPROF' ) } if (process.platform === 'linux') { module.exports.push( 'SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT', 'SIGUNUSED' ) }
import { css, StyleSheet } from 'aphrodite/no-important'; import React, { PropTypes } from 'react'; import octicons from './octicons'; import colors from './colors'; import sizes from './sizes'; import styles from './styles'; const classes = StyleSheet.create(styles); // FIXME static octicon classes leaning on Elemental to avoid duplicate // font and CSS; inflating the project size function Glyph ({ aphroditeStyles, className, color, component: Component, name, size, style, ...props }) { const colorIsValidType = Object.keys(colors).includes(color); props.className = css( classes.glyph, colorIsValidType && classes['color__' + color], classes['size__' + size], aphroditeStyles ) + ` ${octicons[name]}`; if (className) { props.className += (' ' + className); } // support random color strings props.style = { color: !colorIsValidType ? color : null, ...style, }; return <Component {...props} />; }; Glyph.propTypes = { aphroditeStyles: PropTypes.shape({ _definition: PropTypes.object, _name: PropTypes.string, }), color: PropTypes.oneOfType([ PropTypes.oneOf(Object.keys(colors)), PropTypes.string, // support random color strings ]), name: PropTypes.oneOf(Object.keys(octicons)).isRequired, size: PropTypes.oneOf(Object.keys(sizes)), }; Glyph.defaultProps = { component: 'i', color: 'inherit', size: 'small', }; module.exports = Glyph;
"function"==typeof jQuery&&jQuery(document).ready(function(e){function n(){!1!==s?o():t()}function o(){r=new google.maps.LatLng(s[0],s[1]),a()}function t(){var e=new google.maps.Geocoder;e.geocode({address:d},function(e,n){n==google.maps.GeocoderStatus.OK&&(r=e[0].geometry.location,a())})}function a(){var n={zoom:parseInt(tribeEventsSingleMap.zoom),center:r,mapTypeId:google.maps.MapTypeId.ROADMAP};p.map=new google.maps.Map(i,n);var o={map:p.map,title:g,position:r};e("body").trigger("map-created.tribe",[p.map,i,n]),"undefined"!==tribeEventsSingleMap.pin_url&&tribeEventsSingleMap.pin_url&&(o.icon=tribeEventsSingleMap.pin_url),new google.maps.Marker(o)}var i,r,p,d,s,g;"undefined"!=typeof tribeEventsSingleMap&&e.each(tribeEventsSingleMap.addresses,function(e,o){i=document.getElementById("tribe-events-gmap-"+e),null!==i&&(p="undefined"!=typeof o?o:{},d="undefined"!=typeof o.address&&o.address,s="undefined"!=typeof o.coords&&o.coords,g=o.title,n())})});
angular.module('merchello.plugins.braintree').controller('Merchello.Plugins.GatewayProviders.Dialogs.PaymentMethodAddEditController', ['$scope', 'braintreeProviderSettingsBuilder', function($scope, braintreeProviderSettingsBuilder) { $scope.providerSettings = {}; function init() { var json = JSON.parse($scope.dialogData.provider.extendedData.getValue('braintreeProviderSettings')); $scope.providerSettings = braintreeProviderSettingsBuilder.transform(json); $scope.$watch(function () { return $scope.providerSettings; }, function (newValue, oldValue) { $scope.dialogData.provider.extendedData.setValue('braintreeProviderSettings', angular.toJson(newValue)); }, true); } // initialize the controller init(); }]);
(function () { 'use strict'; function ContentEditController($rootScope, $scope, $routeParams, $q, $timeout, $window, $location, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, treeService, fileManager, formHelper, umbRequestHelper, keyboardService, umbModelMapper, editorState, $http, eventsService, relationResource) { var evts = []; //setup scope vars $scope.defaultButton = null; $scope.subButtons = []; $scope.page = {}; $scope.page.loading = false; $scope.page.menu = {}; $scope.page.menu.currentNode = null; $scope.page.menu.currentSection = appState.getSectionState("currentSection"); $scope.page.listViewPath = null; $scope.page.isNew = $scope.isNew ? true : false; $scope.page.buttonGroupState = "init"; $scope.allowOpen = true; function init(content) { createButtons(content); editorState.set($scope.content); //We fetch all ancestors of the node to generate the footer breadcrumb navigation if (!$scope.page.isNew) { if (content.parentId && content.parentId !== -1) { entityResource.getAncestors(content.id, "document") .then(function (anc) { $scope.ancestors = anc; }); } } evts.push(eventsService.on("editors.content.changePublishDate", function (event, args) { createButtons(args.node); })); evts.push(eventsService.on("editors.content.changeUnpublishDate", function (event, args) { createButtons(args.node); })); // We don't get the info tab from the server from version 7.8 so we need to manually add it contentEditingHelper.addInfoTab($scope.content.tabs); } function getNode() { $scope.page.loading = true; //we are editing so get the content item from the server $scope.getMethod()($scope.contentId) .then(function (data) { $scope.content = data; if (data.isChildOfListView && data.trashed === false) { $scope.page.listViewPath = ($routeParams.page) ? "/content/content/edit/" + data.parentId + "?page=" + $routeParams.page : "/content/content/edit/" + data.parentId; } init($scope.content); //in one particular special case, after we've created a new item we redirect back to the edit // route but there might be server validation errors in the collection which we need to display // after the redirect, so we will bind all subscriptions which will show the server validation errors // if there are any and then clear them so the collection no longer persists them. serverValidationManager.executeAndClearAllSubscriptions(); syncTreeNode($scope.content, data.path, true); resetLastListPageNumber($scope.content); eventsService.emit("content.loaded", { content: $scope.content }); $scope.page.loading = false; }); } function createButtons(content) { $scope.page.buttonGroupState = "init"; var buttons = contentEditingHelper.configureContentEditorButtons({ create: $scope.page.isNew, content: content, methods: { saveAndPublish: $scope.saveAndPublish, sendToPublish: $scope.sendToPublish, save: $scope.save, unPublish: $scope.unPublish } }); $scope.defaultButton = buttons.defaultButton; $scope.subButtons = buttons.subButtons; } /** Syncs the content item to it's tree node - this occurs on first load and after saving */ function syncTreeNode(content, path, initialLoad) { if (!$scope.content.isChildOfListView) { navigationService.syncTree({ tree: $scope.treeAlias, path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) { $scope.page.menu.currentNode = syncArgs.node; }); } else if (initialLoad === true) { //it's a child item, just sync the ui node to the parent navigationService.syncTree({ tree: $scope.treeAlias, path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true }); //if this is a child of a list view and it's the initial load of the editor, we need to get the tree node // from the server so that we can load in the actions menu. umbRequestHelper.resourcePromise( $http.get(content.treeNodeUrl), 'Failed to retrieve data for child node ' + content.id).then(function (node) { $scope.page.menu.currentNode = node; }); } } // This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish function performSave(args) { var deferred = $q.defer(); $scope.page.buttonGroupState = "busy"; eventsService.emit("content.saving", { content: $scope.content, action: args.action }); contentEditingHelper.contentEditorPerformSave({ statusMessage: args.statusMessage, saveMethod: args.saveMethod, scope: $scope, content: $scope.content, action: args.action }).then(function (data) { //success init($scope.content); syncTreeNode($scope.content, data.path); $scope.page.buttonGroupState = "success"; deferred.resolve(data); eventsService.emit("content.saved", { content: $scope.content, action: args.action }); }, function (err) { //error if (err) { editorState.set($scope.content); } $scope.page.buttonGroupState = "error"; deferred.reject(err); }); return deferred.promise; } function resetLastListPageNumber(content) { // We're using rootScope to store the page number for list views, so if returning to the list // we can restore the page. If we've moved on to edit a piece of content that's not the list or it's children // we should remove this so as not to confuse if navigating to a different list if (!content.isChildOfListView && !content.isContainer) { $rootScope.lastListViewPageViewed = null; } } if ($scope.page.isNew) { $scope.page.loading = true; //we are creating so get an empty content item $scope.getScaffoldMethod()() .then(function (data) { $scope.content = data; init($scope.content); resetLastListPageNumber($scope.content); $scope.page.loading = false; eventsService.emit("content.newReady", { content: $scope.content }); }); } else { getNode(); } $scope.unPublish = function () { // raising the event triggers the confirmation dialog if (!notificationsService.hasView()) { notificationsService.add({ view: "confirmunpublish" }); } $scope.page.buttonGroupState = "busy"; // actioning the dialog raises the confirmUnpublish event, act on it here var actioned = $rootScope.$on("content.confirmUnpublish", function(event, confirmed) { if (confirmed && formHelper.submitForm({ scope: $scope, statusMessage: "Unpublishing...", skipValidation: true })) { eventsService.emit("content.unpublishing", { content: $scope.content }); contentResource.unPublish($scope.content.id) .then(function (data) { formHelper.resetForm({ scope: $scope, notifications: data.notifications }); contentEditingHelper.handleSuccessfulSave({ scope: $scope, savedContent: data, rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data) }); init($scope.content); syncTreeNode($scope.content, data.path); $scope.page.buttonGroupState = "success"; eventsService.emit("content.unpublished", { content: $scope.content }); }, function(err) { formHelper.showNotifications(err.data); $scope.page.buttonGroupState = 'error'; }); } else { $scope.page.buttonGroupState = "init"; } // unsubscribe to avoid queueing notifications // listener is re-bound when the unpublish button is clicked so it is created just-in-time actioned(); }); }; $scope.sendToPublish = function () { return performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending...", action: "sendToPublish" }); }; $scope.saveAndPublish = function () { return performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing...", action: "publish" }); }; $scope.save = function () { return performSave({ saveMethod: $scope.saveMethod(), statusMessage: "Saving...", action: "save" }); }; $scope.preview = function (content) { if (!$scope.busy) { // Chromes popup blocker will kick in if a window is opened // without the initial scoped request. This trick will fix that. // var previewWindow = $window.open('preview/?init=true&id=' + content.id, 'umbpreview'); // Build the correct path so both /#/ and #/ work. var redirect = Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath + '/preview/?id=' + content.id; //The user cannot save if they don't have access to do that, in which case we just want to preview //and that's it otherwise they'll get an unauthorized access message if (!_.contains(content.allowedActions, "A")) { previewWindow.location.href = redirect; } else { $scope.save().then(function (data) { previewWindow.location.href = redirect; }); } } }; $scope.restore = function (content) { $scope.page.buttonRestore = "busy"; relationResource.getByChildId(content.id, "relateParentDocumentOnDelete").then(function (data) { var relation = null; var target = null; var error = { headline: "Cannot automatically restore this item", content: "Use the Move menu item to move it manually"}; if (data.length == 0) { notificationsService.error(error.headline, "There is no 'restore' relation found for this node. Use the Move menu item to move it manually."); $scope.page.buttonRestore = "error"; return; } relation = data[0]; if (relation.parentId == -1) { target = { id: -1, name: "Root" }; moveNode(content, target); } else { contentResource.getById(relation.parentId).then(function (data) { target = data; // make sure the target item isn't in the recycle bin if(target.path.indexOf("-20") !== -1) { notificationsService.error(error.headline, "The item you want to restore it under (" + target.name + ") is in the recycle bin. Use the Move menu item to move the item manually."); $scope.page.buttonRestore = "error"; return; } moveNode(content, target); }, function (err) { $scope.page.buttonRestore = "error"; notificationsService.error(error.headline, error.content); }); } }, function (err) { $scope.page.buttonRestore = "error"; notificationsService.error(error.headline, error.content); }); }; function moveNode(node, target) { contentResource.move({ "parentId": target.id, "id": node.id }) .then(function (path) { // remove the node that we're working on if($scope.page.menu.currentNode) { treeService.removeNode($scope.page.menu.currentNode); } // sync the destination node navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false }); $scope.page.buttonRestore = "success"; notificationsService.success("Successfully restored " + node.name + " to " + target.name); // reload the node getNode(); }, function (err) { $scope.page.buttonRestore = "error"; notificationsService.error("Cannot automatically restore this item", err); }); } //ensure to unregister from all events! $scope.$on('$destroy', function () { for (var e in evts) { eventsService.unsubscribe(evts[e]); } }); } function createDirective() { var directive = { restrict: 'E', replace: true, templateUrl: 'views/components/content/edit.html', controller: 'Umbraco.Editors.Content.EditorDirectiveController', scope: { contentId: "=", isNew: "=?", treeAlias: "@", page: "=?", saveMethod: "&", getMethod: "&", getScaffoldMethod: "&?" } }; return directive; } angular.module('umbraco.directives').controller('Umbraco.Editors.Content.EditorDirectiveController', ContentEditController); angular.module('umbraco.directives').directive('contentEditor', createDirective); })();
var tns = (function (){ // keys if (!Object.keys) { Object.keys = function (object) { var keys = []; for (var name in object) { if (Object.prototype.hasOwnProperty.call(object, name)) { keys.push(name); } } return keys; }; } // ChildNode.remove (function () { "use strict"; if(!("remove" in Element.prototype)){ Element.prototype.remove = function(){ if(this.parentNode) { this.parentNode.removeChild(this); } }; } })(); var win = window; var raf = win.requestAnimationFrame || win.webkitRequestAnimationFrame || win.mozRequestAnimationFrame || win.msRequestAnimationFrame || function(cb) { return setTimeout(cb, 16); }; var win$1 = window; var caf = win$1.cancelAnimationFrame || win$1.mozCancelAnimationFrame || function(id){ clearTimeout(id); }; function extend() { var obj, name, copy, target = arguments[0] || {}, i = 1, length = arguments.length; for (; i < length; i++) { if ((obj = arguments[i]) !== null) { for (name in obj) { copy = obj[name]; if (target === copy) { continue; } else if (copy !== undefined) { target[name] = copy; } } } } return target; } function checkStorageValue (value) { return ['true', 'false'].indexOf(value) >= 0 ? JSON.parse(value) : value; } function setLocalStorage(key, value) { localStorage.setItem(key, value); return value; } function getSlideId() { var id = window.tnsId; window.tnsId = !id ? 1 : id + 1; return 'tns' + window.tnsId; } function getBody () { var doc = document, body = doc.body; if (!body) { body = doc.createElement('body'); body.fake = true; } return body; } var docElement = document.documentElement; function setFakeBody (body) { var docOverflow = ''; if (body.fake) { docOverflow = docElement.style.overflow; //avoid crashing IE8, if background image is used body.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible body.style.overflow = docElement.style.overflow = 'hidden'; docElement.appendChild(body); } return docOverflow; } function resetFakeBody (body, docOverflow) { if (body.fake) { body.remove(); docElement.style.overflow = docOverflow; // Trigger layout so kinetic scrolling isn't disabled in iOS6+ // eslint-disable-next-line docElement.offsetHeight; } } // get css-calc function calc() { var doc = document, body = getBody(), docOverflow = setFakeBody(body), div = doc.createElement('div'), result = false; body.appendChild(div); try { var vals = ['calc(10px)', '-moz-calc(10px)', '-webkit-calc(10px)'], val; for (var i = 0; i < 3; i++) { val = vals[i]; div.style.width = val; if (div.offsetWidth === 10) { result = val.replace('(10px)', ''); break; } } } catch (e) {} body.fake ? resetFakeBody(body, docOverflow) : div.remove(); return result; } // get subpixel support value function subpixelLayout() { var doc = document, body = getBody(), docOverflow = setFakeBody(body), parent = doc.createElement('div'), child1 = doc.createElement('div'), child2, supported; parent.style.cssText = 'width: 10px'; child1.style.cssText = 'float: left; width: 5.5px; height: 10px;'; child2 = child1.cloneNode(true); parent.appendChild(child1); parent.appendChild(child2); body.appendChild(parent); supported = child1.offsetTop !== child2.offsetTop; body.fake ? resetFakeBody(body, docOverflow) : parent.remove(); return supported; } function mediaquerySupport () { var doc = document, body = getBody(), docOverflow = setFakeBody(body), div = doc.createElement('div'), style = doc.createElement('style'), rule = '@media all and (min-width:1px){.tns-mq-test{position:absolute}}', position; style.type = 'text/css'; div.className = 'tns-mq-test'; body.appendChild(style); body.appendChild(div); if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.appendChild(doc.createTextNode(rule)); } position = window.getComputedStyle ? window.getComputedStyle(div).position : div.currentStyle['position']; body.fake ? resetFakeBody(body, docOverflow) : div.remove(); return position === "absolute"; } // create and append style sheet function createStyleSheet (media) { // Create the <style> tag var style = document.createElement("style"); // style.setAttribute("type", "text/css"); // Add a media (and/or media query) here if you'd like! // style.setAttribute("media", "screen") // style.setAttribute("media", "only screen and (max-width : 1024px)") if (media) { style.setAttribute("media", media); } // WebKit hack :( // style.appendChild(document.createTextNode("")); // Add the <style> element to the page document.querySelector('head').appendChild(style); return style.sheet ? style.sheet : style.styleSheet; } // cross browsers addRule method function addCSSRule(sheet, selector, rules, index) { // return raf(function() { 'insertRule' in sheet ? sheet.insertRule(selector + '{' + rules + '}', index) : sheet.addRule(selector, rules, index); // }); } function getCssRulesLength(sheet) { var rule = ('insertRule' in sheet) ? sheet.cssRules : sheet.rules; return rule.length; } function toDegree (y, x) { return Math.atan2(y, x) * (180 / Math.PI); } function getTouchDirection(angle, range) { var direction = false, gap = Math.abs(90 - Math.abs(angle)); if (gap >= 90 - range) { direction = 'horizontal'; } else if (gap <= range) { direction = 'vertical'; } return direction; } // https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/ function forEachNodeList (arr, callback, scope) { for (var i = 0, l = arr.length; i < l; i++) { callback.call(scope, arr[i], i); } } var classListSupport = 'classList' in document.createElement('_'); var hasClass = classListSupport ? function (el, str) { return el.classList.contains(str); } : function (el, str) { return el.className.indexOf(str) >= 0; }; var addClass = classListSupport ? function (el, str) { if (!hasClass(el, str)) { el.classList.add(str); } } : function (el, str) { if (!hasClass(el, str)) { el.className += ' ' + str; } }; var removeClass = classListSupport ? function (el, str) { if (hasClass(el, str)) { el.classList.remove(str); } } : function (el, str) { if (hasClass(el, str)) { el.className = el.className.replace(str, ''); } }; function hasAttr(el, attr) { return el.hasAttribute(attr); } function getAttr(el, attr) { return el.getAttribute(attr); } function isNodeList(el) { // Only NodeList has the "item()" function return typeof el.item !== "undefined"; } function setAttrs(els, attrs) { els = (isNodeList(els) || els instanceof Array) ? els : [els]; if (Object.prototype.toString.call(attrs) !== '[object Object]') { return; } for (var i = els.length; i--;) { for(var key in attrs) { els[i].setAttribute(key, attrs[key]); } } } function removeAttrs(els, attrs) { els = (isNodeList(els) || els instanceof Array) ? els : [els]; attrs = (attrs instanceof Array) ? attrs : [attrs]; var attrLength = attrs.length; for (var i = els.length; i--;) { for (var j = attrLength; j--;) { els[i].removeAttribute(attrs[j]); } } } function removeElementStyles(el) { el.style.cssText = ''; } function arrayFromNodeList (nl) { var arr = []; for (var i = 0, l = nl.length; i < l; i++) { arr.push(nl[i]); } return arr; } function hideElement(el) { if (!hasAttr(el, 'hidden')) { setAttrs(el, {'hidden': ''}); } } function showElement(el) { if (hasAttr(el, 'hidden')) { removeAttrs(el, 'hidden'); } } function isVisible(el) { return el.offsetWidth > 0 && el.offsetHeight > 0; } function whichProperty(props){ if (typeof props === 'string') { var arr = [props], Props = props.charAt(0).toUpperCase() + props.substr(1), prefixes = ['Webkit', 'Moz', 'ms', 'O']; prefixes.forEach(function(prefix) { if (prefix !== 'ms' || props === 'transform') { arr.push(prefix + Props); } }); props = arr; } var el = document.createElement('fakeelement'), len = props.length; for(var i = 0; i < props.length; i++){ var prop = props[i]; if( el.style[prop] !== undefined ){ return prop; } } return false; // explicit for ie9- } function has3D(tf){ if (!window.getComputedStyle) { return false; } var doc = document, body = getBody(), docOverflow = setFakeBody(body), el = doc.createElement('p'), has3d, cssTF = tf.length > 9 ? '-' + tf.slice(0, -9).toLowerCase() + '-' : ''; cssTF += 'transform'; // Add it to the body to get the computed style body.insertBefore(el, null); el.style[tf] = 'translate3d(1px,1px,1px)'; has3d = window.getComputedStyle(el).getPropertyValue(cssTF); body.fake ? resetFakeBody(body, docOverflow) : el.remove(); return (has3d !== undefined && has3d.length > 0 && has3d !== "none"); } // get transitionend, animationend based on transitionDuration // @propin: string // @propOut: string, first-letter uppercase // Usage: getEndProperty('WebkitTransitionDuration', 'Transition') => webkitTransitionEnd function getEndProperty(propIn, propOut) { var endProp = false; if (/^Webkit/.test(propIn)) { endProp = 'webkit' + propOut + 'End'; } else if (/^O/.test(propIn)) { endProp = 'o' + propOut + 'End'; } else if (propIn) { endProp = propOut.toLowerCase() + 'end'; } return endProp; } // Test via a getter in the options object to see if the passive property is accessed var supportsPassive = false; try { var opts = Object.defineProperty({}, 'passive', { get: function() { supportsPassive = true; } }); window.addEventListener("test", null, opts); } catch (e) {} var passiveOption = supportsPassive ? { passive: true } : false; function addEvents(el, obj) { for (var prop in obj) { var option = (prop === 'touchstart' || prop === 'touchmove') ? passiveOption : false; el.addEventListener(prop, obj[prop], option); } } function removeEvents(el, obj) { for (var prop in obj) { var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 ? passiveOption : false; el.removeEventListener(prop, obj[prop], option); } } function Events() { return { topics: {}, on: function (eventName, fn) { this.topics[eventName] = this.topics[eventName] || []; this.topics[eventName].push(fn); }, off: function(eventName, fn) { if (this.topics[eventName]) { for (var i = 0; i < this.topics[eventName].length; i++) { if (this.topics[eventName][i] === fn) { this.topics[eventName].splice(i, 1); break; } } } }, emit: function (eventName, data) { if (this.topics[eventName]) { this.topics[eventName].forEach(function(fn) { fn(data); }); } } }; } function jsTransform(element, attr, prefix, postfix, to, duration, callback) { var tick = Math.min(duration, 10), unit = (to.indexOf('%') >= 0) ? '%' : 'px', to = to.replace(unit, ''), from = Number(element.style[attr].replace(prefix, '').replace(postfix, '').replace(unit, '')), positionTick = (to - from) / duration * tick, running; setTimeout(moveElement, tick); function moveElement() { duration -= tick; from += positionTick; element.style[attr] = prefix + from + unit + postfix; if (duration > 0) { setTimeout(moveElement, tick); } else { callback(); } } } // Format: IIFE var tns = function(options) { options = extend({ container: '.slider', mode: 'carousel', axis: 'horizontal', items: 1, gutter: 0, edgePadding: 0, fixedWidth: false, fixedWidthViewportWidth: false, slideBy: 1, controls: true, controlsText: ['prev', 'next'], controlsContainer: false, prevButton: false, nextButton: false, nav: true, navContainer: false, navAsThumbnails: false, arrowKeys: false, speed: 300, autoplay: false, autoplayTimeout: 5000, autoplayDirection: 'forward', autoplayText: ['start', 'stop'], autoplayHoverPause: false, autoplayButton: false, autoplayButtonOutput: true, autoplayResetOnVisibility: true, // animateIn: 'tns-fadeIn', // animateOut: 'tns-fadeOut', // animateNormal: 'tns-normal', // animateDelay: false, loop: true, rewind: false, autoHeight: false, responsive: false, lazyload: false, touch: true, mouseDrag: false, swipeAngle: 15, nested: false, freezable: true, // startIndex: 0, onInit: false, useLocalStorage: true }, options || {}); var doc = document, win = window, KEYS = { ENTER: 13, SPACE: 32, PAGEUP: 33, PAGEDOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }, CALC, SUBPIXEL, CSSMQ, TRANSFORM, HAS3D, TRANSITIONDURATION, TRANSITIONDELAY, ANIMATIONDURATION, ANIMATIONDELAY, TRANSITIONEND, ANIMATIONEND, localStorageAccess = true; if (options.useLocalStorage) { // check browser version and local storage // if browser upgraded, // 1. delete browser ralated data from local storage and // 2. recheck these options and save them to local storage var browserInfo = navigator.userAgent, tnsStorage = {}; // tC => calc // tSP => subpixel // tMQ => mediaquery // tTf => transform // tTDu => transitionDuration // tTDe => transitionDelay // tADu => animationDuration // tADe => animationDelay // tTE => transitionEnd // tAE => animationEnd try { tnsStorage = localStorage; // remove storage when browser version changes if (tnsStorage['tnsApp'] && tnsStorage['tnsApp'] !== browserInfo) { ['tC', 'tSP', 'tMQ', 'tTf', 't3D', 'tTDu', 'tTDe', 'tADu', 'tADe', 'tTE', 'tAE'].forEach(function(item) { tnsStorage.removeItem(item); }); } // update browserInfo tnsStorage['tnsApp'] = browserInfo; } catch(e) { localStorageAccess = false; } // reset tnsStorage when localStorage is null (on some versions of Chrome Mobile #134) // https://stackoverflow.com/questions/8701015/html-localstorage-is-null-on-android-when-using-webview if (!localStorage) { tnsStorage = {}; localStorageAccess = false; } // get browser related data from local storage if they exist // otherwise, run the functions again and save these data to local storage // checkStorageValue() convert non-string value to its original value: 'true' > true if (localStorageAccess) { if (tnsStorage['tC']) { CALC = checkStorageValue(tnsStorage['tC']); SUBPIXEL = checkStorageValue(tnsStorage['tSP']); CSSMQ = checkStorageValue(tnsStorage['tMQ']); TRANSFORM = checkStorageValue(tnsStorage['tTf']); HAS3D = checkStorageValue(tnsStorage['t3D']); TRANSITIONDURATION = checkStorageValue(tnsStorage['tTDu']); TRANSITIONDELAY = checkStorageValue(tnsStorage['tTDe']); ANIMATIONDURATION = checkStorageValue(tnsStorage['tADu']); ANIMATIONDELAY = checkStorageValue(tnsStorage['tADe']); TRANSITIONEND = checkStorageValue(tnsStorage['tTE']); ANIMATIONEND = checkStorageValue(tnsStorage['tAE']); } else { CALC = setLocalStorage('tC', calc()); SUBPIXEL = setLocalStorage('tSP', subpixelLayout()); CSSMQ = setLocalStorage('tMQ', mediaquerySupport()); TRANSFORM = setLocalStorage('tTf', whichProperty('transform')); HAS3D = setLocalStorage('t3D', has3D(TRANSFORM)); TRANSITIONDURATION = setLocalStorage('tTDu', whichProperty('transitionDuration')); TRANSITIONDELAY = setLocalStorage('tTDe', whichProperty('transitionDelay')); ANIMATIONDURATION = setLocalStorage('tADu', whichProperty('animationDuration')); ANIMATIONDELAY = setLocalStorage('tADe', whichProperty('animationDelay')); TRANSITIONEND = setLocalStorage('tTE', getEndProperty(TRANSITIONDURATION, 'Transition')); ANIMATIONEND = setLocalStorage('tAE', getEndProperty(ANIMATIONDURATION, 'Animation')); } } } else { localStorageAccess = false; } if (!localStorageAccess) { CALC = calc(); SUBPIXEL = subpixelLayout(); CSSMQ = mediaquerySupport(); TRANSFORM = whichProperty('transform'); HAS3D = has3D(TRANSFORM); TRANSITIONDURATION = whichProperty('transitionDuration'); TRANSITIONDELAY = whichProperty('transitionDelay'); ANIMATIONDURATION = whichProperty('animationDuration'); ANIMATIONDELAY = whichProperty('animationDelay'); TRANSITIONEND = getEndProperty(TRANSITIONDURATION, 'Transition'); ANIMATIONEND = getEndProperty(ANIMATIONDURATION, 'Animation'); } // reset SUBPIXEL for IE8 if (!CSSMQ) { SUBPIXEL = false; } // get element nodes from selectors var supportConsoleWarn = win.console && typeof win.console.warn === "function"; var list = ['container', 'controlsContainer', 'prevButton', 'nextButton', 'navContainer', 'autoplayButton']; for (var i = list.length; i--;) { var item = list[i]; if (typeof options[item] === 'string') { var el = doc.querySelector(options[item]); if (el && el.nodeName) { options[item] = el; } else { if (supportConsoleWarn) { console.warn('Can\'t find', options[item]); } return; } } } // make sure at least 1 slide if (options.container.children && options.container.children.length < 1) { if (supportConsoleWarn) { console.warn('No slides found in', options.container); } return; } // update responsive // from: { // 300: 2, // 800: { // loop: false // } // } // to: { // 300: { // items: 2 // }, // 800: { // loop: false // } // } if (options.responsive) { var resTem = {}, res = options.responsive; for(var key in res) { var val = res[key]; resTem[key] = typeof val === 'number' ? {items: val} : val; } options.responsive = resTem; resTem = null; // apply responsive[0] to options and remove it if (0 in options.responsive) { options = extend(options, options.responsive[0]); delete options.responsive[0]; } } // === define and set variables === var carousel = options.mode === 'carousel' ? true : false; if (!carousel) { options.axis = 'horizontal'; // options.rewind = false; // options.loop = true; options.edgePadding = false; var animateIn = 'tns-fadeIn', animateOut = 'tns-fadeOut', animateDelay = false, animateNormal = options.animateNormal || 'tns-normal'; if (TRANSITIONEND && ANIMATIONEND) { animateIn = options.animateIn || animateIn; animateOut = options.animateOut || animateOut; animateDelay = options.animateDelay || animateDelay; } } var horizontal = options.axis === 'horizontal' ? true : false, outerWrapper = doc.createElement('div'), innerWrapper = doc.createElement('div'), container = options.container, containerParent = container.parentNode, slideItems = container.children, slideCount = slideItems.length, vpInner, responsive = options.responsive, responsiveItems = [], breakpoints = false, breakpointZone = 0, windowWidth = getWindowWidth(), isOn; if (options.fixedWidth) { var vpOuter = getViewportWidth(containerParent); } if (responsive) { breakpoints = Object.keys(responsive) .map(function (x) { return parseInt(x); }) .sort(function (a, b) { return a - b; }); // get all responsive items breakpoints.forEach(function(bp) { responsiveItems = responsiveItems.concat(Object.keys(responsive[bp])); }); // remove duplicated items var arr = []; responsiveItems.forEach(function (item) { if (arr.indexOf(item) < 0) { arr.push(item); } }); responsiveItems = arr; setBreakpointZone(); } var items = getOption('items'), slideBy = getOption('slideBy') === 'page' ? items : getOption('slideBy'), nested = options.nested, gutter = getOption('gutter'), edgePadding = getOption('edgePadding'), fixedWidth = getOption('fixedWidth'), fixedWidthViewportWidth = options.fixedWidthViewportWidth, arrowKeys = getOption('arrowKeys'), speed = getOption('speed'), rewind = options.rewind, loop = rewind ? false : options.loop, autoHeight = getOption('autoHeight'), sheet = createStyleSheet(), lazyload = options.lazyload, slideOffsetTops, // collection of slide offset tops slideItemsOut = [], hasEdgePadding = checkOption('edgePadding'), cloneCount = loop ? getCloneCountForLoop() : 0, slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2, hasRightDeadZone = fixedWidth && !loop && !edgePadding ? true : false, updateIndexBeforeTransform = (!carousel || !loop) ? true : false, // transform transformAttr = horizontal ? 'left' : 'top', transformPrefix = '', transformPostfix = '', // index startIndex = getOption('startIndex'), index = startIndex ? updateStartIndex(startIndex) : !carousel ? 0 : cloneCount, indexCached = index, indexMin = 0, indexMax = getIndexMax(), // resize resizeTimer, swipeAngle = options.swipeAngle, moveDirectionExpected = swipeAngle ? '?' : true, running = false, onInit = options.onInit, events = new Events(), // id, class containerIdCached = container.id, classContainer = ' tns-slider tns-' + options.mode, slideId = container.id || getSlideId(), disable = getOption('disable'), freezable = options.freezable, freeze = disable ? true : freezable ? slideCount <= items : false, frozen, importantStr = nested === 'inner' ? ' !important' : '', controlsEvents = { 'click': onControlsClick, 'keydown': onControlsKeydown }, navEvents = { 'click': onNavClick, 'keydown': onNavKeydown }, hoverEvents = { 'mouseover': mouseoverPause, 'mouseout': mouseoutRestart }, visibilityEvent = {'visibilitychange': onVisibilityChange}, docmentKeydownEvent = {'keydown': onDocumentKeydown}, touchEvents = { 'touchstart': onPanStart, 'touchmove': onPanMove, 'touchend': onPanEnd, 'touchcancel': onPanEnd }, dragEvents = { 'mousedown': onPanStart, 'mousemove': onPanMove, 'mouseup': onPanEnd, 'mouseleave': onPanEnd }, hasControls = checkOption('controls'), hasNav = checkOption('nav'), navAsThumbnails = options.navAsThumbnails, hasAutoplay = checkOption('autoplay'), hasTouch = checkOption('touch'), hasMouseDrag = checkOption('mouseDrag'), slideActiveClass = 'tns-slide-active', imgCompleteClass = 'tns-complete', imgEvents = { 'load': imgLoadedOrError, 'error': imgLoadedOrError }, imgsComplete; // controls if (hasControls) { var controls = getOption('controls'), controlsText = getOption('controlsText'), controlsContainer = options.controlsContainer, prevButton = options.prevButton, nextButton = options.nextButton, prevIsButton, nextIsButton; } // nav if (hasNav) { var nav = getOption('nav'), navContainer = options.navContainer, navItems, visibleNavIndexes = [], visibleNavIndexesCached = visibleNavIndexes, navClicked = -1, navCurrentIndex = getAbsIndex(), navCurrentIndexCached = navCurrentIndex, navActiveClass = 'tns-nav-active'; } // autoplay if (hasAutoplay) { var autoplay = getOption('autoplay'), autoplayTimeout = getOption('autoplayTimeout'), autoplayDirection = options.autoplayDirection === 'forward' ? 1 : -1, autoplayText = getOption('autoplayText'), autoplayHoverPause = getOption('autoplayHoverPause'), autoplayButton = options.autoplayButton, autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'), autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'], autoplayTimer, animating, autoplayHoverPaused, autoplayUserPaused, autoplayVisibilityPaused; } if (hasTouch || hasMouseDrag) { var initPosition = {}, lastPosition = {}, translateInit, disX, disY, panStart = false, rafIndex = 0, getDist = horizontal ? function(a, b) { return a.x - b.x; } : function(a, b) { return a.y - b.y; }; } // touch if (hasTouch) { var touch = getOption('touch'); } // mouse drag if (hasMouseDrag) { var mouseDrag = getOption('mouseDrag'); } // disable slider when slidecount <= items if (freeze) { controls = nav = touch = mouseDrag = arrowKeys = autoplay = autoplayHoverPause = autoplayResetOnVisibility = false; } if (TRANSFORM) { transformAttr = TRANSFORM; transformPrefix = 'translate'; if (HAS3D) { transformPrefix += horizontal ? '3d(' : '3d(0px, '; transformPostfix = horizontal ? ', 0px, 0px)' : ', 0px)'; } else { transformPrefix += horizontal ? 'X(' : 'Y('; transformPostfix = ')'; } } // === COMMON FUNCTIONS === // function getIndexMax () { return carousel || loop ? Math.max(0, slideCountNew - items) : slideCountNew - 1; } function updateStartIndex (indexTem) { indexTem = indexTem%slideCount; if (indexTem < 0) { indexTem += slideCount; } indexTem = Math.min(indexTem, slideCountNew - items); return indexTem; } function getAbsIndex (i) { if (i === undefined) { i = index; } if (carousel) { while (i < cloneCount) { i += slideCount; } i -= cloneCount; } return i ? i%slideCount : i; } function getItemsMax () { if (fixedWidth && !fixedWidthViewportWidth) { return slideCount - 1; } else { var str = fixedWidth ? 'fixedWidth' : 'items', arr = []; if (fixedWidth || options[str] < slideCount) { arr.push(options[str]); } if (breakpoints && responsiveItems.indexOf(str) >= 0) { breakpoints.forEach(function(bp) { var tem = responsive[bp][str]; if (tem && (fixedWidth || tem < slideCount)) { arr.push(tem); } }); } if (!arr.length) { arr.push(0); } return fixedWidth ? Math.ceil(fixedWidthViewportWidth / Math.min.apply(null, arr)) : Math.max.apply(null, arr); } } function getCloneCountForLoop () { var itemsMax = getItemsMax(), result = carousel ? Math.ceil((itemsMax * 5 - slideCount)/2) : (itemsMax * 4 - slideCount); result = Math.max(itemsMax, result); return hasEdgePadding ? result + 1 : result; } function getWindowWidth () { return win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth; } function getViewportWidth (el) { return el.clientWidth || getViewportWidth(el.parentNode); } function checkOption (item) { var result = options[item]; if (!result && breakpoints && responsiveItems.indexOf(item) >= 0) { breakpoints.forEach(function (bp) { if (responsive[bp][item]) { result = true; } }); } return result; } function getOption (item, viewport) { viewport = viewport ? viewport : windowWidth; var obj = { slideBy: 'page', edgePadding: false }, result; if (!carousel && item in obj) { result = obj[item]; } else { if (item === 'items' && getOption('fixedWidth')) { result = Math.floor(vpOuter / (getOption('fixedWidth') + getOption('gutter'))); } else if (item === 'autoHeight' && nested === 'outer') { result = true; } else { result = options[item]; if (breakpoints && responsiveItems.indexOf(item) >= 0) { for (var i = 0, len = breakpoints.length; i < len; i++) { var bp = breakpoints[i]; if (viewport >= bp) { if (item in responsive[bp]) { result = responsive[bp][item]; } } else { break; } } } } } if (item === 'slideBy' && result === 'page') { result = getOption('items'); } return result; } function getSlideMarginLeft (i) { var str = CALC ? CALC + '(' + i * 100 + '% / ' + slideCountNew + ')' : i * 100 / slideCountNew + '%'; return str; } function getInnerWrapperStyles (edgePaddingTem, gutterTem, fixedWidthTem, speedTem) { var str = ''; if (edgePaddingTem) { var gap = edgePaddingTem; if (gutterTem) { gap += gutterTem; } if (fixedWidthTem) { str = 'margin: 0px ' + (vpOuter%(fixedWidthTem + gutterTem) + gutterTem) / 2 + 'px;'; } else { str = horizontal ? 'margin: 0 ' + edgePaddingTem + 'px 0 ' + gap + 'px;' : 'padding: ' + gap + 'px 0 ' + edgePaddingTem + 'px 0;'; } } else if (gutterTem && !fixedWidthTem) { var gutterTemUnit = '-' + gutterTem + 'px', dir = horizontal ? gutterTemUnit + ' 0 0' : '0 ' + gutterTemUnit + ' 0'; str = 'margin: 0 ' + dir + ';'; } if (TRANSITIONDURATION && speedTem) { str += getTrsnsitionDurationStyle(speedTem); } return str; } function getContainerWidth (fixedWidthTem, gutterTem, itemsTem) { var str; if (fixedWidthTem) { str = (fixedWidthTem + gutterTem) * slideCountNew + 'px'; } else { str = CALC ? CALC + '(' + slideCountNew * 100 + '% / ' + itemsTem + ')' : slideCountNew * 100 / itemsTem + '%'; } return str; } function getSlideWidthStyle (fixedWidthTem, gutterTem, itemsTem) { var str = ''; if (horizontal) { str = 'width:'; if (fixedWidthTem) { str += (fixedWidthTem + gutterTem) + 'px'; } else { var dividend = carousel ? slideCountNew : itemsTem; str += CALC ? CALC + '(100% / ' + dividend + ')' : 100 / dividend + '%'; } str += importantStr + ';'; } return str; } function getSlideGutterStyle (gutterTem) { var str = ''; // gutter maybe interger || 0 // so can't use 'if (gutter)' if (gutterTem !== false) { var prop = horizontal ? 'padding-' : 'margin-', dir = horizontal ? 'right' : 'bottom'; str = prop + dir + ': ' + gutterTem + 'px;'; } return str; } function getCSSPrefix (name, num) { var prefix = name.substring(0, name.length - num).toLowerCase(); if (prefix) { prefix = '-' + prefix + '-'; } return prefix; } function getTrsnsitionDurationStyle (speed) { return getCSSPrefix(TRANSITIONDURATION, 18) + 'transition-duration:' + speed / 1000 + 's;'; } function getAnimationDurationStyle (speed) { return getCSSPrefix(ANIMATIONDURATION, 17) + 'animation-duration:' + speed / 1000 + 's;'; } (function sliderInit () { // First thing first, wrap container with 'outerWrapper > innerWrapper', // to get the correct view width outerWrapper.appendChild(innerWrapper); containerParent.insertBefore(outerWrapper, container); innerWrapper.appendChild(container); vpInner = getViewportWidth(innerWrapper); var classOuter = 'tns-outer', classInner = 'tns-inner', hasGutter = checkOption('gutter'); if (carousel) { if (horizontal) { if (checkOption('edgePadding') || hasGutter && !options.fixedWidth) { classOuter += ' tns-ovh'; } else { classInner += ' tns-ovh'; } } else { classInner += ' tns-ovh'; } } else if (hasGutter) { classOuter += ' tns-ovh'; } outerWrapper.className = classOuter; innerWrapper.className = classInner; innerWrapper.id = slideId + '-iw'; if (autoHeight) { innerWrapper.className += ' tns-ah'; } // set container properties if (container.id === '') { container.id = slideId; } classContainer += SUBPIXEL ? ' tns-subpixel' : ' tns-no-subpixel'; classContainer += CALC ? ' tns-calc' : ' tns-no-calc'; if (carousel) { classContainer += ' tns-' + options.axis; } container.className += classContainer; // add event if (carousel && TRANSITIONEND) { var eve = {}; eve[TRANSITIONEND] = onTransitionEnd; addEvents(container, eve); } // delete datas after init classOuter = classInner = null; // add id, class, aria attributes // before clone slides for (var x = 0; x < slideCount; x++) { var item = slideItems[x]; if (!item.id) { item.id = slideId + '-item' + x; } addClass(item, 'tns-item'); if (!carousel && animateNormal) { addClass(item, animateNormal); } setAttrs(item, { 'aria-hidden': 'true', 'tabindex': '-1' }); } // clone slides if (loop || edgePadding) { var fragmentBefore = doc.createDocumentFragment(), fragmentAfter = doc.createDocumentFragment(); for (var j = cloneCount; j--;) { var num = j%slideCount, cloneFirst = slideItems[num].cloneNode(true); removeAttrs(cloneFirst, 'id'); fragmentAfter.insertBefore(cloneFirst, fragmentAfter.firstChild); if (carousel) { var cloneLast = slideItems[slideCount - 1 - num].cloneNode(true); removeAttrs(cloneLast, 'id'); fragmentBefore.appendChild(cloneLast); } } container.insertBefore(fragmentBefore, container.firstChild); container.appendChild(fragmentAfter); slideItems = container.children; } // add image events if (checkOption('autoHeight') || !carousel) { var imgs = container.querySelectorAll('img'); // check all image complete status // add complete class if true forEachNodeList(imgs, function(img) { addEvents(img, imgEvents); var src = img.src; img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; img.src = src; }); // set imgsComplete to true // when all images are compulete (loaded or error) raf(function(){ checkImagesLoaded(arrayFromNodeList(imgs), function() { imgsComplete = true; }); }); } // activate visible slides // add aria attrs // set animation classes and left value for gallery slider // use slide count when slides are fewer than items for (var i = index, l = index + Math.min(slideCount, items); i < l; i++) { var item = slideItems[i]; setAttrs(item, {'aria-hidden': 'false'}); removeAttrs(item, ['tabindex']); addClass(item, slideActiveClass); if (!carousel) { item.style.left = (i - index) * 100 / items + '%'; addClass(item, animateIn); removeClass(item, animateNormal); } } if (carousel && horizontal) { // set font-size rules // for modern browsers if (SUBPIXEL) { // set slides font-size first addCSSRule(sheet, '#' + slideId + ' > .tns-item', 'font-size:' + win.getComputedStyle(slideItems[0]).fontSize + ';', getCssRulesLength(sheet)); addCSSRule(sheet, '#' + slideId, 'font-size:0;', getCssRulesLength(sheet)); // slide left margin // for IE8 & webkit browsers (no subpixel) } else { forEachNodeList(slideItems, function (slide, i) { slide.style.marginLeft = getSlideMarginLeft(i); }); } } // all browsers which support CSS transitions support CSS media queries if (CSSMQ) { // inner wrapper styles var str = getInnerWrapperStyles(options.edgePadding, options.gutter, options.fixedWidth, options.speed); addCSSRule(sheet, '#' + slideId + '-iw', str, getCssRulesLength(sheet)); // container styles if (carousel) { str = horizontal ? 'width:' + getContainerWidth(options.fixedWidth, options.gutter, options.items) + ';' : ''; if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); } addCSSRule(sheet, '#' + slideId, str, getCssRulesLength(sheet)); } // slide styles if (horizontal || options.gutter) { str = getSlideWidthStyle(options.fixedWidth, options.gutter, options.items) + getSlideGutterStyle(options.gutter); // set gallery items transition-duration if (!carousel) { if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); } if (ANIMATIONDURATION) { str += getAnimationDurationStyle(speed); } } addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet)); } // non CSS mediaqueries: IE8 // ## update inner wrapper, container, slides if needed // set inline styles for inner wrapper & container // insert stylesheet (one line) for slides only (since slides are many) } else { // inner wrapper styles innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth); // container styles if (carousel && horizontal) { container.style.width = getContainerWidth(fixedWidth, gutter, items); } // slide styles if (horizontal || gutter) { var str = getSlideWidthStyle(fixedWidth, gutter, items) + getSlideGutterStyle(gutter); // append to the last line addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet)); } } if (!horizontal && !disable) { getSlideOffsetTops(); updateContentWrapperHeight(); } // media queries if (responsive && CSSMQ) { breakpoints.forEach(function(bp) { var opts = responsive[bp], str = '', innerWrapperStr = '', containerStr = '', slideStr = '', itemsBP = getOption('items', bp), fixedWidthBP = getOption('fixedWidth', bp), speedBP = getOption('speed', bp), edgePaddingBP = getOption('edgePadding', bp), gutterBP = getOption('gutter', bp); // inner wrapper string if ('edgePadding' in opts || 'gutter' in opts) { innerWrapperStr = '#' + slideId + '-iw{' + getInnerWrapperStyles(edgePaddingBP, gutterBP, fixedWidthBP, speedBP) + '}'; } // container string if (carousel && horizontal && ('fixedWidth' in opts || 'gutter' in opts || 'items' in opts)) { containerStr = 'width:' + getContainerWidth(fixedWidthBP, gutterBP, itemsBP) + ';'; } if (TRANSITIONDURATION && 'speed' in opts) { containerStr += getTrsnsitionDurationStyle(speedBP); } if (containerStr) { containerStr = '#' + slideId + '{' + containerStr + '}'; } // slide string if ('fixedWidth' in opts || checkOption('fixedWidth') && 'gutter' in opts || !carousel && 'items' in opts) { slideStr += getSlideWidthStyle(fixedWidthBP, gutterBP, itemsBP); } if ('gutter' in opts) { slideStr += getSlideGutterStyle(gutterBP); } // set gallery items transition-duration if (!carousel && 'speed' in opts) { if (TRANSITIONDURATION) { slideStr += getTrsnsitionDurationStyle(speedBP); } if (ANIMATIONDURATION) { slideStr += getAnimationDurationStyle(speedBP); } } if (slideStr) { slideStr = '#' + slideId + ' > .tns-item{' + slideStr + '}'; } // add up str = innerWrapperStr + containerStr + slideStr; if (str) { sheet.insertRule('@media (min-width: ' + bp / 16 + 'em) {' + str + '}', sheet.cssRules.length); } }); } // set container transform property if (carousel && !disable) { doContainerTransformSilent(); } // == msInit == // for IE10 if (navigator.msMaxTouchPoints) { addClass(container, 'ms-touch'); addEvents(container, {'scroll': ie10Scroll}); setSnapInterval(); } // == navInit == if (hasNav) { var initIndex = !carousel ? 0 : cloneCount; // customized nav // will not hide the navs in case they're thumbnails if (navContainer) { setAttrs(navContainer, {'aria-label': 'Carousel Pagination'}); navItems = navContainer.children; forEachNodeList(navItems, function (item, i) { setAttrs(item, { 'data-nav': i, 'tabindex': '-1', 'aria-selected': 'false', 'aria-controls': slideItems[initIndex + i].id, }); }); // generated nav } else { var navHtml = '', hiddenStr = navAsThumbnails ? '' : 'hidden'; for (var i = 0; i < slideCount; i++) { // hide nav items by default navHtml += '<button data-nav="' + i +'" tabindex="-1" aria-selected="false" aria-controls="' + slideItems[initIndex + i].id + '" ' + hiddenStr + ' type="button"></button>'; } navHtml = '<div class="tns-nav" aria-label="Carousel Pagination">' + navHtml + '</div>'; outerWrapper.insertAdjacentHTML('afterbegin', navHtml); navContainer = outerWrapper.querySelector('.tns-nav'); navItems = navContainer.children; } updateNavVisibility(); // add transition if (TRANSITIONDURATION) { var prefix = TRANSITIONDURATION.substring(0, TRANSITIONDURATION.length - 18).toLowerCase(), str = 'transition: all ' + speed / 1000 + 's'; if (prefix) { str = '-' + prefix + '-' + str; } addCSSRule(sheet, '[aria-controls^=' + slideId + '-item]', str, getCssRulesLength(sheet)); } setAttrs(navItems[navCurrentIndex], {'tabindex': '0', 'aria-selected': 'true'}); addClass(navItems[navCurrentIndex], navActiveClass); // add events addEvents(navContainer, navEvents); if (!nav) { hideElement(navContainer); } } // == autoplayInit == if (hasAutoplay) { var txt = autoplay ? 'stop' : 'start'; if (autoplayButton) { setAttrs(autoplayButton, {'data-action': txt}); } else if (options.autoplayButtonOutput) { innerWrapper.insertAdjacentHTML('beforebegin', '<button data-action="' + txt + '" type="button">' + autoplayHtmlStrings[0] + txt + autoplayHtmlStrings[1] + autoplayText[0] + '</button>'); autoplayButton = outerWrapper.querySelector('[data-action]'); } // add event if (autoplayButton) { addEvents(autoplayButton, {'click': toggleAutoplay}); } if (!autoplay) { if (autoplayButton) { hideElement(autoplayButton); } } else { startAutoplay(); if (autoplayHoverPause) { addEvents(container, hoverEvents); } if (autoplayResetOnVisibility) { addEvents(container, visibilityEvent); } } } // == controlsInit == if (hasControls) { if (controlsContainer || (prevButton && nextButton)) { if (controlsContainer) { prevButton = controlsContainer.children[0]; nextButton = controlsContainer.children[1]; setAttrs(controlsContainer, { 'aria-label': 'Carousel Navigation', 'tabindex': '0' }); setAttrs(controlsContainer.children, { 'aria-controls': slideId, 'tabindex': '-1', }); } setAttrs(prevButton, {'data-controls' : 'prev'}); setAttrs(nextButton, {'data-controls' : 'next'}); } else { outerWrapper.insertAdjacentHTML('afterbegin', '<div class="tns-controls" aria-label="Carousel Navigation" tabindex="0"><button data-controls="prev" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[0] + '</button><button data-controls="next" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[1] + '</button></div>'); controlsContainer = outerWrapper.querySelector('.tns-controls'); prevButton = controlsContainer.children[0]; nextButton = controlsContainer.children[1]; } prevIsButton = isButton(prevButton); nextIsButton = isButton(nextButton); updateControlsStatus(); // add events if (controlsContainer) { addEvents(controlsContainer, controlsEvents); } else { addEvents(prevButton, controlsEvents); addEvents(nextButton, controlsEvents); } if (!controls) { hideElement(controlsContainer); } } // if (!navigator.msMaxTouchPoints) { if (carousel) { if (touch) { addEvents(container, touchEvents); } if (mouseDrag) { addEvents(container, dragEvents); } } // } if (arrowKeys) { addEvents(doc, docmentKeydownEvent); } if (nested === 'inner') { events.on('outerResized', function () { resizeTasks(); events.emit('innerLoaded', info()); }); } else { addEvents(win, {'resize': onResize}); } if (nested === 'outer') { events.on('innerLoaded', runAutoHeight); } else if ((autoHeight || !carousel) && !disable) { runAutoHeight(); } lazyLoad(); toggleSlideDisplayAndEdgePadding(); updateFixedWidthInnerWrapperStyle(); events.on('indexChanged', additionalUpdates); if (typeof onInit === 'function') { onInit(info()); } if (nested === 'inner') { events.emit('innerLoaded', info()); } if (disable) { disableSlider(true); } isOn = true; })(); // === ON RESIZE === function onResize (e) { raf(function(){ resizeTasks(getEvent(e)); }); } function resizeTasks (e) { if (!isOn) { return; } windowWidth = getWindowWidth(); if (nested === 'outer') { events.emit('outerResized', info(e)); } var breakpointZoneTem = breakpointZone, indexTem = index, itemsTem = items, freezeTem = freeze, needContainerTransform = false; if (fixedWidth) { vpOuter = getViewportWidth(outerWrapper); } vpInner = getViewportWidth(innerWrapper); if (breakpoints) { setBreakpointZone(); } // things do when breakpoint zone change if (breakpointZoneTem !== breakpointZone || fixedWidth) { var slideByTem = slideBy, arrowKeysTem = arrowKeys, autoHeightTem = autoHeight, fixedWidthTem = fixedWidth, edgePaddingTem = edgePadding, gutterTem = gutter, disableTem = disable; // update variables items = getOption('items'); slideBy = getOption('slideBy'); disable = getOption('disable'); freeze = disable ? true : freezable ? slideCount <= items : false; if (items !== itemsTem) { indexMax = getIndexMax(); // check index before transform in case // slider reach the right edge then items become bigger updateIndex(); } if (disable !== disableTem) { disableSlider(disable); } if (freeze !== freezeTem) { // reset index to initial status if (freeze) { index = !carousel ? 0 : cloneCount; } toggleSlideDisplayAndEdgePadding(); } if (breakpointZoneTem !== breakpointZone) { speed = getOption('speed'); edgePadding = getOption('edgePadding'); gutter = getOption('gutter'); fixedWidth = getOption('fixedWidth'); if (!disable && fixedWidth !== fixedWidthTem) { needContainerTransform = true; } autoHeight = getOption('autoHeight'); if (autoHeight !== autoHeightTem) { if (!autoHeight) { innerWrapper.style.height = ''; } } } arrowKeys = freeze ? false : getOption('arrowKeys'); if (arrowKeys !== arrowKeysTem) { arrowKeys ? addEvents(doc, docmentKeydownEvent) : removeEvents(doc, docmentKeydownEvent); } if (hasControls) { var controlsTem = controls, controlsTextTem = controlsText; controls = freeze ? false : getOption('controls'); controlsText = getOption('controlsText'); if (controls !== controlsTem) { controls ? showElement(controlsContainer) : hideElement(controlsContainer); } if (controlsText !== controlsTextTem) { prevButton.innerHTML = controlsText[0]; nextButton.innerHTML = controlsText[1]; } } if (hasNav) { var navTem = nav; nav = freeze ? false : getOption('nav'); if (nav !== navTem) { if (nav) { showElement(navContainer); updateNavVisibility(); } else { hideElement(navContainer); } } } if (hasTouch) { var touchTem = touch; touch = freeze ? false : getOption('touch'); if (touch !== touchTem && carousel) { touch ? addEvents(container, touchEvents) : removeEvents(container, touchEvents); } } if (hasMouseDrag) { var mouseDragTem = mouseDrag; mouseDrag = freeze ? false : getOption('mouseDrag'); if (mouseDrag !== mouseDragTem && carousel) { mouseDrag ? addEvents(container, dragEvents) : removeEvents(container, dragEvents); } } if (hasAutoplay) { var autoplayTem = autoplay, autoplayHoverPauseTem = autoplayHoverPause, autoplayResetOnVisibilityTem = autoplayResetOnVisibility, autoplayTextTem = autoplayText; if (freeze) { autoplay = autoplayHoverPause = autoplayResetOnVisibility = false; } else { autoplay = getOption('autoplay'); if (autoplay) { autoplayHoverPause = getOption('autoplayHoverPause'); autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'); } else { autoplayHoverPause = autoplayResetOnVisibility = false; } } autoplayText = getOption('autoplayText'); autoplayTimeout = getOption('autoplayTimeout'); if (autoplay !== autoplayTem) { if (autoplay) { if (autoplayButton) { showElement(autoplayButton); } if (!animating && !autoplayUserPaused) { startAutoplay(); } } else { if (autoplayButton) { hideElement(autoplayButton); } if (animating) { stopAutoplay(); } } } if (autoplayHoverPause !== autoplayHoverPauseTem) { autoplayHoverPause ? addEvents(container, hoverEvents) : removeEvents(container, hoverEvents); } if (autoplayResetOnVisibility !== autoplayResetOnVisibilityTem) { autoplayResetOnVisibility ? addEvents(doc, visibilityEvent) : removeEvents(doc, visibilityEvent); } if (autoplayButton && autoplayText !== autoplayTextTem) { var i = autoplay ? 1 : 0, html = autoplayButton.innerHTML, len = html.length - autoplayTextTem[i].length; if (html.substring(len) === autoplayTextTem[i]) { autoplayButton.innerHTML = html.substring(0, len) + autoplayText[i]; } } } // IE8 // ## update inner wrapper, container, slides if needed // set inline styles for inner wrapper & container // insert stylesheet (one line) for slides only (since slides are many) if (!CSSMQ) { // inner wrapper styles if (!freeze && (edgePadding !== edgePaddingTem || gutter !== gutterTem)) { innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth); } // container styles if (carousel && horizontal && (fixedWidth !== fixedWidthTem || gutter !== gutterTem || items !== itemsTem)) { container.style.width = getContainerWidth(fixedWidth, gutter, items); } // slide styles if (horizontal && (items !== itemsTem || gutter !== gutterTem || fixedWidth != fixedWidthTem)) { var str = getSlideWidthStyle(fixedWidth, gutter, items) + getSlideGutterStyle(gutter); // remove the last line and // add new styles sheet.removeRule(getCssRulesLength(sheet) - 1); addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet)); } if (!fixedWidth) { needContainerTransform = true; } } if (index !== indexTem) { events.emit('indexChanged', info()); needContainerTransform = true; } if (items !== itemsTem) { additionalUpdates(); updateSlidePosition(); if (navigator.msMaxTouchPoints) { setSnapInterval(); } } } // things always do regardless of breakpoint zone changing if (!horizontal && !disable) { getSlideOffsetTops(); updateContentWrapperHeight(); needContainerTransform = true; } if (needContainerTransform) { doContainerTransformSilent(); indexCached = index; } updateFixedWidthInnerWrapperStyle(true); // auto height if ((autoHeight || !carousel) && !disable) { runAutoHeight(); } } // === INITIALIZATION FUNCTIONS === // function setBreakpointZone () { breakpointZone = 0; breakpoints.forEach(function(bp, i) { if (windowWidth >= bp) { breakpointZone = i + 1; } }); } function loopNumber (num, min, max) { return index >= indexMin && index <= indexMax ? index : index > indexMax ? index - slideCount : index + slideCount; } function cutindexber (index, min, indexMax) { return index >= indexMin && index <= indexMax ? index : index > indexMax ? indexMax : indexMin; } // (slideBy, indexMin, indexMax) => index var updateIndex = (function () { return loop ? carousel ? // loop + carousel function () { var leftEdge = indexMin, rightEdge = indexMax; leftEdge += slideBy; rightEdge -= slideBy; // adjust edges when edge padding is true // or fixed-width slider with extra space on the right side if (edgePadding) { leftEdge += 1; rightEdge -= 1; } else if (fixedWidth) { var gt = gutter ? gutter : 0; if (vpOuter%(fixedWidth + gt) > gt) { rightEdge -= 1; } } if (cloneCount) { if (index > rightEdge) { index -= slideCount; } else if (index < leftEdge) { index += slideCount; } } } : // loop + gallery function() { if (index > indexMax) { while (index >= indexMin + slideCount) { index -= slideCount; } } else if (index < indexMin) { while (index <= indexMax - slideCount) { index += slideCount; } } } : // non-loop function() { index = (index >= indexMin && index <= indexMax) ? index : index > indexMax ? indexMax : indexMin; }; })(); function toggleSlideDisplayAndEdgePadding () { // if (cloneCount) { // if (fixedWidth && cloneCount) { var str = 'tns-transparent'; if (freeze) { if (!frozen) { // remove edge padding from inner wrapper if (edgePadding) { innerWrapper.style.margin = '0px'; } // add class tns-transparent to cloned slides if (cloneCount) { for (var i = cloneCount; i--;) { if (carousel) { addClass(slideItems[i], str); } addClass(slideItems[slideCountNew - i - 1], str); } } frozen = true; } } else if (frozen) { // restore edge padding for inner wrapper // for mordern browsers if (edgePadding && !fixedWidth && CSSMQ) { innerWrapper.style.margin = ''; } // remove class tns-transparent to cloned slides if (cloneCount) { for (var i = cloneCount; i--;) { if (carousel) { removeClass(slideItems[i], str); } removeClass(slideItems[slideCountNew - i - 1], str); } } frozen = false; } // } } function updateFixedWidthInnerWrapperStyle (resize) { if (fixedWidth && edgePadding) { // remove edge padding when freeze or viewport narrower than one slide if (freeze || vpOuter <= (fixedWidth + gutter)) { if (innerWrapper.style.margin !== '0px') { innerWrapper.style.margin = '0px'; } // update edge padding on resize } else if (resize) { innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth); } } } function disableSlider (disable) { var len = slideItems.length; if (disable) { sheet.disabled = true; container.className = container.className.replace(classContainer.substring(1), ''); removeElementStyles(container); if (loop) { for (var j = cloneCount; j--;) { if (carousel) { hideElement(slideItems[j]); } hideElement(slideItems[len - j - 1]); } } // vertical slider if (!horizontal || !carousel) { removeElementStyles(innerWrapper); } // gallery if (!carousel) { for (var i = index, l = index + slideCount; i < l; i++) { var item = slideItems[i]; removeElementStyles(item); removeClass(item, animateIn); removeClass(item, animateNormal); } } } else { sheet.disabled = false; container.className += classContainer; // vertical slider: get offsetTops before container transform if (!horizontal) { getSlideOffsetTops(); } doContainerTransformSilent(); if (loop) { for (var j = cloneCount; j--;) { if (carousel) { showElement(slideItems[j]); } showElement(slideItems[len - j - 1]); } } // gallery if (!carousel) { for (var i = index, l = index + slideCount; i < l; i++) { var item = slideItems[i], classN = i < index + items ? animateIn : animateNormal; item.style.left = (i - index) * 100 / items + '%'; addClass(item, classN); } } } } // lazyload function lazyLoad () { if (lazyload && !disable) { var i = index, len = index + items; if (edgePadding) { i -=1; len +=1; } i = Math.max(i, 0); len = Math.min(len, slideCountNew); for(; i < len; i++) { forEachNodeList(slideItems[i].querySelectorAll('.tns-lazy-img'), function (img) { // stop propagationl transitionend event to container var eve = {}; eve[TRANSITIONEND] = function (e) { e.stopPropagation(); }; addEvents(img, eve); if (!hasClass(img, 'loaded')) { img.src = getAttr(img, 'data-src'); addClass(img, 'loaded'); } }); } } } function imgLoadedOrError (e) { var img = getTarget(e); addClass(img, imgCompleteClass); removeEvents(img, imgEvents); } function getImageArray (slideStart, slideRange) { var imgs = []; for (var i = slideStart, l = slideStart + slideRange; i < l; i++) { forEachNodeList(slideItems[i].querySelectorAll('img'), function (img) { imgs.push(img); }); } return imgs; } // check if all visible images are loaded // and update container height if it's done function runAutoHeight () { var imgs = autoHeight ? getImageArray(index, items) : getImageArray(cloneCount, slideCount); raf(function(){ checkImagesLoaded(imgs, updateInnerWrapperHeight); }); } function checkImagesLoaded (imgs, cb) { // directly execute callback function if all images are complete if (imgsComplete) { return cb(); } // check selected image classes otherwise imgs.forEach(function (img, index) { if (hasClass(img, imgCompleteClass)) { imgs.splice(index, 1); } }); // execute callback function if selected images are all complete if (!imgs.length) { return cb(); } // otherwise execute this functiona again raf(function(){ checkImagesLoaded(imgs, cb); }); } function additionalUpdates () { lazyLoad(); updateSlideStatus(); updateControlsStatus(); updateNavVisibility(); updateNavStatus(); } function getMaxSlideHeight (slideStart, slideRange) { var heights = []; for (var i = slideStart, l = slideStart + slideRange; i < l; i++) { heights.push(slideItems[i].offsetHeight); } return Math.max.apply(null, heights); } // update inner wrapper height // 1. get the max-height of the visible slides // 2. set transitionDuration to speed // 3. update inner wrapper height to max-height // 4. set transitionDuration to 0s after transition done function updateInnerWrapperHeight () { var maxHeight = autoHeight ? getMaxSlideHeight(index, items) : getMaxSlideHeight(cloneCount, slideCount); if (innerWrapper.style.height !== maxHeight) { innerWrapper.style.height = maxHeight + 'px'; } } // get the distance from the top edge of the first slide to each slide // (init) => slideOffsetTops function getSlideOffsetTops () { slideOffsetTops = [0]; var topFirst = slideItems[0].getBoundingClientRect().top, attr; for (var i = 1; i < slideCountNew; i++) { attr = slideItems[i].getBoundingClientRect().top; slideOffsetTops.push(attr - topFirst); } } // set snapInterval (for IE10) function setSnapInterval () { outerWrapper.style.msScrollSnapPointsX = 'snapInterval(0%, ' + (100 / items) + '%)'; } // update slide function updateSlideStatus () { var l = index + Math.min(slideCount, items); for (var i = slideCountNew; i--;) { var item = slideItems[i]; // visible slides if (i >= index && i < l) { if (hasAttr(item, 'tabindex')) { setAttrs(item, {'aria-hidden': 'false'}); removeAttrs(item, ['tabindex']); addClass(item, slideActiveClass); } // hidden slides } else { if (!hasAttr(item, 'tabindex')) { setAttrs(item, { 'aria-hidden': 'true', 'tabindex': '-1' }); } if (hasClass(item, slideActiveClass)) { removeClass(item, slideActiveClass); } } } } // gallery: update slide position function updateSlidePosition () { if (!carousel) { var l = index + Math.min(slideCount, items); for (var i = slideCountNew; i--;) { var item = slideItems[i]; if (i >= index && i < l) { // add transitions to visible slides when adjusting their positions addClass(item, 'tns-moving'); item.style.left = (i - index) * 100 / items + '%'; addClass(item, animateIn); removeClass(item, animateNormal); } else if (item.style.left) { item.style.left = ''; addClass(item, animateNormal); removeClass(item, animateIn); } // remove outlet animation removeClass(item, animateOut); } // removing '.tns-moving' setTimeout(function() { forEachNodeList(slideItems, function(el) { removeClass(el, 'tns-moving'); }); }, 300); } } // set tabindex & aria-selected on Nav function updateNavStatus () { // get current nav if (nav) { navCurrentIndex = navClicked !== -1 ? navClicked : getAbsIndex(); navClicked = -1; if (navCurrentIndex !== navCurrentIndexCached) { var navPrev = navItems[navCurrentIndexCached], navCurrent = navItems[navCurrentIndex]; setAttrs(navPrev, { 'tabindex': '-1', 'aria-selected': 'false' }); setAttrs(navCurrent, { 'tabindex': '0', 'aria-selected': 'true' }); removeClass(navPrev, navActiveClass); addClass(navCurrent, navActiveClass); } } } function getLowerCaseNodeName (el) { return el.nodeName.toLowerCase(); } function isButton (el) { return getLowerCaseNodeName(el) === 'button'; } function isAriaDisabled (el) { return el.getAttribute('aria-disabled') === 'true'; } function disEnableElement (isButton, el, val) { if (isButton) { el.disabled = val; } else { el.setAttribute('aria-disabled', val.toString()); } } // set 'disabled' to true on controls when reach the edges function updateControlsStatus () { if (!controls || rewind || loop) { return; } var prevDisabled = (prevIsButton) ? prevButton.disabled : isAriaDisabled(prevButton), nextDisabled = (nextIsButton) ? nextButton.disabled : isAriaDisabled(nextButton), disablePrev = (index === indexMin) ? true : false, disableNext = (!rewind && index === indexMax) ? true : false; if (disablePrev && !prevDisabled) { disEnableElement(prevIsButton, prevButton, true); } if (!disablePrev && prevDisabled) { disEnableElement(prevIsButton, prevButton, false); } if (disableNext && !nextDisabled) { disEnableElement(nextIsButton, nextButton, true); } if (!disableNext && nextDisabled) { disEnableElement(nextIsButton, nextButton, false); } } // set duration function resetDuration (el, str) { if (TRANSITIONDURATION) { el.style[TRANSITIONDURATION] = str; } } function getContainerTransformValue () { var val; if (horizontal) { if (fixedWidth) { val = - (fixedWidth + gutter) * index + 'px'; } else { var denominator = TRANSFORM ? slideCountNew : items; val = - index * 100 / denominator + '%'; } } else { val = - slideOffsetTops[index] + 'px'; } return val; } function doContainerTransformSilent (val) { resetDuration(container, '0s'); doContainerTransform(val); setTimeout(function() { resetDuration(container, ''); }, 0); } function doContainerTransform (val, test) { if (!val) { val = getContainerTransformValue(); } container.style[transformAttr] = transformPrefix + val + transformPostfix; } function animateSlide (number, classOut, classIn, isOut) { var l = number + items; if (!loop) { l = Math.min(l, slideCountNew); } for (var i = number; i < l; i++) { var item = slideItems[i]; // set item positions if (!isOut) { item.style.left = (i - index) * 100 / items + '%'; } if (animateDelay && TRANSITIONDELAY) { item.style[TRANSITIONDELAY] = item.style[ANIMATIONDELAY] = animateDelay * (i - number) / 1000 + 's'; } removeClass(item, classOut); addClass(item, classIn); if (isOut) { slideItemsOut.push(item); } } } // make transfer after click/drag: // 1. change 'transform' property for mordern browsers // 2. change 'left' property for legacy browsers var transformCore = (function () { return carousel ? function (duration, distance) { if (!distance) { distance = getContainerTransformValue(); } // constrain the distance when non-loop no-edgePadding fixedWidth reaches the right edge if (hasRightDeadZone && index === indexMax) { distance = - ((fixedWidth + gutter) * slideCountNew - vpInner) + 'px'; } if (TRANSITIONDURATION || !duration) { // for morden browsers with non-zero duration or // zero duration for all browsers doContainerTransform(distance); // run fallback function manually // when duration is 0 / container is hidden if (!duration || !isVisible(container)) { onTransitionEnd(); } } else { // for old browser with non-zero duration jsTransform(container, transformAttr, transformPrefix, transformPostfix, distance, speed, onTransitionEnd); } if (!horizontal) { updateContentWrapperHeight(); } } : function (duration) { slideItemsOut = []; var eve = {}; eve[TRANSITIONEND] = eve[ANIMATIONEND] = onTransitionEnd; removeEvents(slideItems[indexCached], eve); addEvents(slideItems[index], eve); animateSlide(indexCached, animateIn, animateOut, true); animateSlide(index, animateNormal, animateIn); // run fallback function manually // when transition or animation not supported / duration is 0 if (!TRANSITIONEND || !ANIMATIONEND || !duration) { onTransitionEnd(); } }; })(); function doTransform (duration, distance) { // check duration is defined and is a number if (isNaN(duration)) { duration = speed; } // if container is hidden, set duration to 0 // to fix an issue where browser doesn't fire ontransitionend on hidden element if (animating && !isVisible(container)) { duration = 0; } transformCore(duration, distance); } function render (e, sliderMoved) { if (updateIndexBeforeTransform) { updateIndex(); } // render when slider was moved (touch or drag) even though index may not change if (index !== indexCached || sliderMoved) { // events events.emit('indexChanged', info()); events.emit('transitionStart', info()); // pause autoplay when click or keydown from user if (animating && e && ['click', 'keydown'].indexOf(e.type) >= 0) { stopAutoplay(); } running = true; doTransform(); } } /* * Transfer prefixed properties to the same format * CSS: -Webkit-Transform => webkittransform * JS: WebkitTransform => webkittransform * @param {string} str - property * */ function strTrans (str) { return str.toLowerCase().replace(/-/g, ''); } // AFTER TRANSFORM // Things need to be done after a transfer: // 1. check index // 2. add classes to visible slide // 3. disable controls buttons when reach the first/last slide in non-loop slider // 4. update nav status // 5. lazyload images // 6. update container height function onTransitionEnd (event) { // check running on gallery mode // make sure trantionend/animationend events run only once if (carousel || running) { events.emit('transitionEnd', info(event)); if (!carousel && slideItemsOut.length > 0) { for (var i = 0; i < slideItemsOut.length; i++) { var item = slideItemsOut[i]; // set item positions item.style.left = ''; if (ANIMATIONDELAY && TRANSITIONDELAY) { item.style[ANIMATIONDELAY] = ''; item.style[TRANSITIONDELAY] = ''; } removeClass(item, animateOut); addClass(item, animateNormal); } } /* update slides, nav, controls after checking ... * => legacy browsers who don't support 'event' * have to check event first, otherwise event.target will cause an error * => or 'gallery' mode: * + event target is slide item * => or 'carousel' mode: * + event target is container, * + event.property is the same with transform attribute */ if (!event || !carousel && event.target.parentNode === container || event.target === container && strTrans(event.propertyName) === strTrans(transformAttr)) { if (!updateIndexBeforeTransform) { var indexTem = index; updateIndex(); if (index !== indexTem) { events.emit('indexChanged', info()); doContainerTransformSilent(); } } if (autoHeight) { runAutoHeight(); } if (nested === 'inner') { events.emit('innerLoaded', info()); } running = false; navCurrentIndexCached = navCurrentIndex; indexCached = index; } } } // # ACTIONS function goTo (targetIndex, e) { if (freeze) { return; } // prev slideBy if (targetIndex === 'prev') { onControlsClick(e, -1); // next slideBy } else if (targetIndex === 'next') { onControlsClick(e, 1); // go to exact slide } else { if (running) { onTransitionEnd(); } // } else if (!running) { var absIndex = getAbsIndex(), indexGap = 0; if (absIndex < 0) { absIndex += slideCount; } if (targetIndex === 'first') { indexGap = - absIndex; } else if (targetIndex === 'last') { indexGap = carousel ? slideCount - items - absIndex : slideCount - 1 - absIndex; } else { if (typeof targetIndex !== 'number') { targetIndex = parseInt(targetIndex); } if (!isNaN(targetIndex)) { var absTargetIndex = getAbsIndex(targetIndex); if (absTargetIndex < 0) { absTargetIndex += slideCount; } indexGap = absTargetIndex - absIndex; } } index += indexGap; // if index is changed, start rendering if (getAbsIndex(index) !== getAbsIndex(indexCached)) { render(e); } } } // on controls click function onControlsClick (e, dir) { // if (!running) { if (running) { onTransitionEnd(); } var passEventObject; if (!dir) { e = getEvent(e); var target = e.target || e.srcElement; while (target !== controlsContainer && [prevButton, nextButton].indexOf(target) < 0) { target = target.parentNode; } var targetIn = [prevButton, nextButton].indexOf(target); if (targetIn >= 0) { passEventObject = true; dir = targetIn === 0 ? -1 : 1; } } if (rewind) { if (index === indexMin && dir === -1) { goTo('last', e); return; } else if (index === indexMax && dir === 1) { goTo(0, e); return; } } if (dir) { index += slideBy * dir; // pass e when click control buttons or keydown render((passEventObject || (e && e.type === 'keydown')) ? e : null); } // } } // on nav click function onNavClick (e) { // if (!running) { if (running) { onTransitionEnd(); } e = getEvent(e); var target = e.target || e.srcElement, navIndex; // find the clicked nav item while (target !== navContainer && !hasAttr(target, 'data-nav')) { target = target.parentNode; } if (hasAttr(target, 'data-nav')) { navIndex = navClicked = [].indexOf.call(navItems, target); goTo(navIndex + cloneCount, e); } // } } // autoplay functions function setAutoplayTimer () { autoplayTimer = setInterval(function () { onControlsClick(null, autoplayDirection); }, autoplayTimeout); animating = true; } function stopAutoplayTimer () { clearInterval(autoplayTimer); animating = false; } function updateAutoplayButton (action, txt) { setAttrs(autoplayButton, {'data-action': action}); autoplayButton.innerHTML = autoplayHtmlStrings[0] + action + autoplayHtmlStrings[1] + txt; } function startAutoplay () { setAutoplayTimer(); if (autoplayButton) { updateAutoplayButton('stop', autoplayText[1]); } } function stopAutoplay () { stopAutoplayTimer(); if (autoplayButton) { updateAutoplayButton('start', autoplayText[0]); } } // programaitcally play/pause the slider function play () { if (autoplay && !animating) { startAutoplay(); autoplayUserPaused = false; } } function pause () { if (animating) { stopAutoplay(); autoplayUserPaused = true; } } function toggleAutoplay () { if (animating) { stopAutoplay(); autoplayUserPaused = true; } else { startAutoplay(); autoplayUserPaused = false; } } function onVisibilityChange () { if (doc.hidden) { if (animating) { stopAutoplayTimer(); autoplayVisibilityPaused = true; } } else if (autoplayVisibilityPaused) { setAutoplayTimer(); autoplayVisibilityPaused = false; } } function mouseoverPause () { if (animating) { stopAutoplayTimer(); autoplayHoverPaused = true; } } function mouseoutRestart () { if (autoplayHoverPaused) { setAutoplayTimer(); autoplayHoverPaused = false; } } // keydown events on document function onDocumentKeydown (e) { e = getEvent(e); switch(e.keyCode) { case KEYS.LEFT: onControlsClick(e, -1); break; case KEYS.RIGHT: onControlsClick(e, 1); } } // on key control function onControlsKeydown (e) { e = getEvent(e); var code = e.keyCode; switch (code) { case KEYS.LEFT: case KEYS.UP: case KEYS.PAGEUP: if (!prevButton.disabled) { onControlsClick(e, -1); } break; case KEYS.RIGHT: case KEYS.DOWN: case KEYS.PAGEDOWN: if (!nextButton.disabled) { onControlsClick(e, 1); } break; case KEYS.HOME: goTo(0, e); break; case KEYS.END: goTo(slideCount - 1, e); break; } } // set focus function setFocus (focus) { focus.focus(); } // on key nav function onNavKeydown (e) { var curElement = doc.activeElement; if (!hasAttr(curElement, 'data-nav')) { return; } e = getEvent(e); var code = e.keyCode, navIndex = [].indexOf.call(navItems, curElement), len = visibleNavIndexes.length, current = visibleNavIndexes.indexOf(navIndex); if (options.navContainer) { len = slideCount; current = navIndex; } function getNavIndex (num) { return options.navContainer ? num : visibleNavIndexes[num]; } switch(code) { case KEYS.LEFT: case KEYS.PAGEUP: if (current > 0) { setFocus(navItems[getNavIndex(current - 1)]); } break; case KEYS.UP: case KEYS.HOME: if (current > 0) { setFocus(navItems[getNavIndex(0)]); } break; case KEYS.RIGHT: case KEYS.PAGEDOWN: if (current < len - 1) { setFocus(navItems[getNavIndex(current + 1)]); } break; case KEYS.DOWN: case KEYS.END: if (current < len - 1) { setFocus(navItems[getNavIndex(len - 1)]); } break; // Can't use onNavClick here, // Because onNavClick require event.target as nav items case KEYS.ENTER: case KEYS.SPACE: navClicked = navIndex; goTo(navIndex + cloneCount, e); break; } } // IE10 scroll function function ie10Scroll () { transformCore(0, container.scrollLeft); indexCached = index; } function getEvent (e) { e = e || win.event; return isTouchEvent(e) ? e.changedTouches[0] : e; } function getTarget (e) { return e.target || win.event.srcElement; } function isTouchEvent (e) { return e.type.indexOf('touch') >= 0; } function preventDefaultBehavior (e) { e.preventDefault ? e.preventDefault() : e.returnValue = false; } function onPanStart (e) { if (running) { onTransitionEnd(); } panStart = true; caf(rafIndex); rafIndex = raf(function(){ panUpdate(e); }); var $ = getEvent(e); events.emit(isTouchEvent(e) ? 'touchStart' : 'dragStart', info(e)); if (!isTouchEvent(e) && ['img', 'a'].indexOf(getLowerCaseNodeName(getTarget(e))) >= 0) { preventDefaultBehavior(e); } lastPosition.x = initPosition.x = parseInt($.clientX); lastPosition.y = initPosition.y = parseInt($.clientY); translateInit = parseFloat(container.style[transformAttr].replace(transformPrefix, '').replace(transformPostfix, '')); resetDuration(container, '0s'); } function onPanMove (e) { if (panStart) { var $ = getEvent(e); lastPosition.x = parseInt($.clientX); lastPosition.y = parseInt($.clientY); } } function panUpdate (e) { if (!moveDirectionExpected) { panStart = false; return; } caf(rafIndex); if (panStart) { rafIndex = raf(function(){ panUpdate(e); }); } if ( moveDirectionExpected === '?' && lastPosition.x !== initPosition.x && lastPosition.y !== initPosition.y) { moveDirectionExpected = getTouchDirection(toDegree(lastPosition.y - initPosition.y, lastPosition.x - initPosition.x), swipeAngle) === options.axis; } if (moveDirectionExpected) { events.emit(isTouchEvent(e) ? 'touchMove' : 'dragMove', info(e)); var x = translateInit, dist = getDist(lastPosition, initPosition); if (!horizontal || fixedWidth) { x += dist; x += 'px'; } else { var percentageX = TRANSFORM ? dist * items * 100 / (vpInner * slideCountNew): dist * 100 / vpInner; x += percentageX; x += '%'; } container.style[transformAttr] = transformPrefix + x + transformPostfix; } } function onPanEnd (e) { if (swipeAngle) { moveDirectionExpected = '?'; } // reset if (panStart) { caf(rafIndex); resetDuration(container, ''); panStart = false; var $ = getEvent(e); lastPosition.x = parseInt($.clientX); lastPosition.y = parseInt($.clientY); var dist = getDist(lastPosition, initPosition); // initPosition = {x:0, y:0}; // reset positions // lastPosition = {x:0, y:0}; // reset positions if (Math.abs(dist) >= 5) { // drag vs click if (!isTouchEvent(e)) { // prevent "click" var target = getTarget(e); addEvents(target, {'click': function preventClick (e) { preventDefaultBehavior(e); removeEvents(target, {'click': preventClick}); }}); } rafIndex = raf(function() { events.emit(isTouchEvent(e) ? 'touchEnd' : 'dragEnd', info(e)); if (horizontal) { var indexMoved = - dist * items / vpInner; indexMoved = dist > 0 ? Math.floor(indexMoved) : Math.ceil(indexMoved); index += indexMoved; } else { var moved = - (translateInit + dist); if (moved <= 0) { index = indexMin; } else if (moved >= slideOffsetTops[slideOffsetTops.length - 1]) { index = indexMax; } else { var i = 0; do { i++; index = dist < 0 ? i + 1 : i; } while (i < slideCountNew && moved >= slideOffsetTops[i + 1]); } } render(e, dist); }); } } } // === RESIZE FUNCTIONS === // // (slideOffsetTops, index, items) => vertical_conentWrapper.height function updateContentWrapperHeight () { innerWrapper.style.height = slideOffsetTops[index + items] - slideOffsetTops[index] + 'px'; } /* * get nav item indexes per items * add 1 more if the nav items cann't cover all slides * [0, 1, 2, 3, 4] / 3 => [0, 3] */ function getVisibleNavIndex () { // reset visibleNavIndexes visibleNavIndexes = []; var absIndexMin = getAbsIndex()%items; while (absIndexMin < slideCount) { if (carousel && !loop && absIndexMin + items > slideCount) { absIndexMin = slideCount - items; } visibleNavIndexes.push(absIndexMin); absIndexMin += items; } // nav count * items < slide count means // some slides can not be displayed only by nav clicking if (loop && visibleNavIndexes.length * items < slideCount || !loop && visibleNavIndexes[0] > 0) { visibleNavIndexes.unshift(0); } } /* * 1. update visible nav items list * 2. add "hidden" attributes to previous visible nav items * 3. remove "hidden" attrubutes to new visible nav items */ function updateNavVisibility () { if (!nav || navAsThumbnails) { return; } getVisibleNavIndex(); if (visibleNavIndexes !== visibleNavIndexesCached) { forEachNodeList(navItems, function(el, i) { if (visibleNavIndexes.indexOf(i) < 0) { hideElement(el); } else { showElement(el); } }); // cache visible nav indexes visibleNavIndexesCached = visibleNavIndexes; } } function info (e) { return { container: container, slideItems: slideItems, navContainer: navContainer, navItems: navItems, controlsContainer: controlsContainer, hasControls: hasControls, prevButton: prevButton, nextButton: nextButton, items: items, slideBy: slideBy, cloneCount: cloneCount, slideCount: slideCount, slideCountNew: slideCountNew, index: index, indexCached: indexCached, navCurrentIndex: navCurrentIndex, navCurrentIndexCached: navCurrentIndexCached, visibleNavIndexes: visibleNavIndexes, visibleNavIndexesCached: visibleNavIndexesCached, sheet: sheet, event: e || {}, }; } return { getInfo: info, events: events, goTo: goTo, play: play, pause: pause, isOn: isOn, updateSliderHeight: updateInnerWrapperHeight, rebuild: function() { return tns(options); }, destroy: function () { // remove win event listeners removeEvents(win, {'resize': onResize}); // remove arrowKeys eventlistener removeEvents(doc, docmentKeydownEvent); // sheet sheet.disabled = true; // cloned items if (loop) { for (var j = cloneCount; j--;) { if (carousel) { slideItems[0].remove(); } slideItems[slideItems.length - 1].remove(); } } // Slide Items var slideClasses = ['tns-item', slideActiveClass]; if (!carousel) { slideClasses = slideClasses.concat('tns-normal', animateIn); } for (var i = slideCount; i--;) { var slide = slideItems[i]; if (slide.id.indexOf(slideId + '-item') >= 0) { slide.id = ''; } slideClasses.forEach(function(cl) { removeClass(slide, cl); }); } removeAttrs(slideItems, ['style', 'aria-hidden', 'tabindex']); slideItems = slideId = slideCount = slideCountNew = cloneCount = null; // controls if (controls) { removeEvents(controlsContainer, controlsEvents); if (options.controlsContainer) { removeAttrs(controlsContainer, ['aria-label', 'tabindex']); removeAttrs(controlsContainer.children, ['aria-controls', 'aria-disabled', 'tabindex']); } controlsContainer = prevButton = nextButton = null; } // nav if (nav) { removeEvents(navContainer, navEvents); if (options.navContainer) { removeAttrs(navContainer, ['aria-label']); removeAttrs(navItems, ['aria-selected', 'aria-controls', 'tabindex']); } navContainer = navItems = null; } // auto if (autoplay) { clearInterval(autoplayTimer); if (autoplayButton) { removeEvents(autoplayButton, {'click': toggleAutoplay}); } removeEvents(container, hoverEvents); removeEvents(container, visibilityEvent); if (options.autoplayButton) { removeAttrs(autoplayButton, ['data-action']); } } // container container.id = containerIdCached || ''; container.className = container.className.replace(classContainer, ''); removeElementStyles(container); if (carousel && TRANSITIONEND) { var eve = {}; eve[TRANSITIONEND] = onTransitionEnd; removeEvents(container, eve); } removeEvents(container, touchEvents); removeEvents(container, dragEvents); // outerWrapper containerParent.insertBefore(container, outerWrapper); outerWrapper.remove(); outerWrapper = innerWrapper = container = index = indexCached = items = slideBy = navCurrentIndex = navCurrentIndexCached = hasControls = visibleNavIndexes = visibleNavIndexesCached = this.getInfo = this.events = this.goTo = this.play = this.pause = this.destroy = null; this.isOn = isOn = false; } }; }; return tns; })();
function dec(target, name, descriptor) { assert(target); assert.equal(typeof name, "string"); assert.equal(typeof descriptor, "object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let value = descriptor.value; Object.assign(descriptor, { enumerable: name.indexOf("enum") !== -1, configurable: name.indexOf("conf") !== -1, writable: name.indexOf("write") !== -1, value: function(...args) { return "__" + value.apply(this, args) + "__"; }, }); } const inst = { @dec enumconfwrite(){ return 1; }, @dec enumconf(){ return 2; }, @dec enumwrite(){ return 3; }, @dec enum(){ return 4; }, @dec confwrite(){ return 5; }, @dec conf(){ return 6; }, @dec write(){ return 7; }, @dec _(){ return 8; }, } assert(inst.hasOwnProperty('decoratedProps')); assert.deepEqual(inst.decoratedProps, [ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(inst); assert(descs.enumconfwrite.enumerable); assert(descs.enumconfwrite.writable); assert(descs.enumconfwrite.configurable); assert.equal(inst.enumconfwrite(), "__1__"); assert(descs.enumconf.enumerable); assert.equal(descs.enumconf.writable, false); assert(descs.enumconf.configurable); assert.equal(inst.enumconf(), "__2__"); assert(descs.enumwrite.enumerable); assert(descs.enumwrite.writable); assert.equal(descs.enumwrite.configurable, false); assert.equal(inst.enumwrite(), "__3__"); assert(descs.enum.enumerable); assert.equal(descs.enum.writable, false); assert.equal(descs.enum.configurable, false); assert.equal(inst.enum(), "__4__"); assert.equal(descs.confwrite.enumerable, false); assert(descs.confwrite.writable); assert(descs.confwrite.configurable); assert.equal(inst.confwrite(), "__5__"); assert.equal(descs.conf.enumerable, false); assert.equal(descs.conf.writable, false); assert(descs.conf.configurable); assert.equal(inst.conf(), "__6__"); assert.equal(descs.write.enumerable, false); assert(descs.write.writable); assert.equal(descs.write.configurable, false); assert.equal(inst.write(), "__7__"); assert.equal(descs._.enumerable, false); assert.equal(descs._.writable, false); assert.equal(descs._.configurable, false); assert.equal(inst._(), "__8__");
/* Language: Lisp Description: Generic lisp syntax Author: Vasily Polovnyov <[email protected]> Category: lisp */ function lisp(hljs) { var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*'; var MEC_RE = '\\|[^]*?\\|'; var LISP_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?'; var LITERAL = { className: 'literal', begin: '\\b(t{1}|nil)\\b' }; var NUMBER = { className: 'number', variants: [ {begin: LISP_SIMPLE_NUMBER_RE, relevance: 0}, {begin: '#(b|B)[0-1]+(/[0-1]+)?'}, {begin: '#(o|O)[0-7]+(/[0-7]+)?'}, {begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'}, {begin: '#(c|C)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, end: '\\)'} ] }; var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}); var COMMENT = hljs.COMMENT( ';', '$', { relevance: 0 } ); var VARIABLE = { begin: '\\*', end: '\\*' }; var KEYWORD = { className: 'symbol', begin: '[:&]' + LISP_IDENT_RE }; var IDENT = { begin: LISP_IDENT_RE, relevance: 0 }; var MEC = { begin: MEC_RE }; var QUOTED_LIST = { begin: '\\(', end: '\\)', contains: ['self', LITERAL, STRING, NUMBER, IDENT] }; var QUOTED = { contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT], variants: [ { begin: '[\'`]\\(', end: '\\)' }, { begin: '\\(quote ', end: '\\)', keywords: {name: 'quote'} }, { begin: '\'' + MEC_RE } ] }; var QUOTED_ATOM = { variants: [ {begin: '\'' + LISP_IDENT_RE}, {begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'} ] }; var LIST = { begin: '\\(\\s*', end: '\\)' }; var BODY = { endsWithParent: true, relevance: 0 }; LIST.contains = [ { className: 'name', variants: [ { begin: LISP_IDENT_RE, relevance: 0, }, {begin: MEC_RE} ] }, BODY ]; BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT]; return { name: 'Lisp', illegal: /\S/, contains: [ NUMBER, hljs.SHEBANG(), LITERAL, STRING, COMMENT, QUOTED, QUOTED_ATOM, LIST, IDENT ] }; } module.exports = lisp;
define( //begin v1.x content { "field-quarter-short-relative+0": "detta kv.", "field-quarter-short-relative+1": "nästa kv.", "field-tue-relative+-1": "tisdag förra veckan", "field-year": "år", "field-wed-relative+0": "onsdag denna vecka", "field-wed-relative+1": "onsdag nästa vecka", "field-minute": "minut", "field-month-narrow-relative+-1": "förra mån.", "field-tue-narrow-relative+0": "denna tis.", "field-tue-narrow-relative+1": "nästa tis.", "field-thu-short-relative+0": "tors. denna vecka", "field-day-short-relative+-1": "i går", "field-thu-short-relative+1": "tors. nästa vecka", "field-day-relative+0": "i dag", "field-day-short-relative+-2": "i förrgår", "field-day-relative+1": "i morgon", "field-week-narrow-relative+0": "denna v.", "field-day-relative+2": "i övermorgon", "field-week-narrow-relative+1": "nästa v.", "field-wed-narrow-relative+-1": "förra ons.", "field-year-narrow": "år", "field-era-short": "era", "field-year-narrow-relative+0": "i år", "field-tue-relative+0": "tisdag denna vecka", "field-year-narrow-relative+1": "nästa år", "field-tue-relative+1": "tisdag nästa vecka", "field-weekdayOfMonth": "veckodag i månad", "field-second-short": "sek", "field-weekdayOfMonth-narrow": "veckodag i mån.", "field-week-relative+0": "denna vecka", "field-month-relative+0": "denna månad", "field-week-relative+1": "nästa vecka", "field-month-relative+1": "nästa månad", "field-sun-narrow-relative+0": "denna sön.", "field-mon-short-relative+0": "mån. denna vecka", "field-sun-narrow-relative+1": "nästa sön.", "field-mon-short-relative+1": "mån. nästa vecka", "field-second-relative+0": "nu", "field-weekOfMonth": "vecka i månaden", "field-month-short": "m", "field-day": "dag", "field-dayOfYear-short": "dag under året", "field-year-relative+-1": "i fjol", "field-sat-short-relative+-1": "lör. förra veckan", "field-hour-relative+0": "denna timme", "field-second-short-relative+0": "nu", "field-wed-relative+-1": "onsdag förra veckan", "field-sat-narrow-relative+-1": "förra lör.", "field-second": "sekund", "field-hour-short-relative+0": "denna timme", "field-quarter": "kvartal", "field-week-short": "v", "field-day-narrow-relative+0": "idag", "field-day-narrow-relative+1": "imorgon", "field-day-narrow-relative+2": "i övermorgon", "field-tue-short-relative+0": "tis. denna vecka", "field-tue-short-relative+1": "tis. nästa vecka", "field-month-short-relative+-1": "förra mån.", "field-mon-relative+-1": "måndag förra veckan", "field-month": "månad", "field-day-narrow": "dag", "field-minute-short": "min", "field-dayperiod": "fm/em", "field-sat-short-relative+0": "lör. denna vecka", "field-sat-short-relative+1": "lör. nästa vecka", "field-second-narrow": "s", "field-mon-relative+0": "måndag denna vecka", "field-mon-relative+1": "måndag nästa vecka", "field-day-narrow-relative+-1": "igår", "field-year-short": "år", "field-day-narrow-relative+-2": "i förrgår", "field-quarter-relative+-1": "förra kvartalet", "field-dayperiod-narrow": "fm/em", "field-week-narrow-relative+-1": "förra v.", "field-dayOfYear": "dag under året", "field-sat-relative+-1": "lördag förra veckan", "field-hour": "timme", "field-minute-narrow-relative+0": "denna minut", "field-month-relative+-1": "förra månaden", "field-quarter-short": "kv.", "field-sat-narrow-relative+0": "denna lör.", "field-fri-relative+0": "fredag denna vecka", "field-sat-narrow-relative+1": "nästa lör.", "field-fri-relative+1": "fredag nästa vecka", "field-month-narrow-relative+0": "denna mån.", "field-month-narrow-relative+1": "nästa mån.", "field-sun-short-relative+0": "sön. denna vecka", "field-sun-short-relative+1": "sön. nästa vecka", "field-week-relative+-1": "förra veckan", "field-quarter-short-relative+-1": "förra kv.", "field-minute-short-relative+0": "denna minut", "field-quarter-relative+0": "detta kvartal", "field-minute-relative+0": "denna minut", "field-quarter-relative+1": "nästa kvartal", "field-wed-short-relative+-1": "ons. förra veckan", "field-thu-short-relative+-1": "tors. förra veckan", "field-year-narrow-relative+-1": "i fjol", "field-thu-narrow-relative+-1": "förra tors.", "field-tue-narrow-relative+-1": "förra tis.", "field-weekOfMonth-short": "vk. i mån.", "field-wed-short-relative+0": "ons. denna vecka", "field-wed-short-relative+1": "ons. nästa vecka", "field-sun-relative+-1": "söndag förra veckan", "field-second-narrow-relative+0": "nu", "field-weekday": "veckodag", "field-day-short-relative+0": "i dag", "field-quarter-narrow-relative+0": "detta kv.", "field-sat-relative+0": "lördag denna vecka", "field-day-short-relative+1": "i morgon", "field-quarter-narrow-relative+1": "nästa kv.", "field-sat-relative+1": "lördag nästa vecka", "field-day-short-relative+2": "i övermorgon", "field-week-short-relative+0": "denna v.", "field-week-short-relative+1": "nästa v.", "field-dayOfYear-narrow": "dag under året", "field-month-short-relative+0": "denna mån.", "field-month-short-relative+1": "nästa mån.", "field-weekdayOfMonth-short": "veckodag i mån.", "field-zone-narrow": "tidszon", "field-thu-narrow-relative+0": "denna tors.", "field-thu-narrow-relative+1": "nästa tors.", "field-sun-narrow-relative+-1": "förra sön.", "field-mon-short-relative+-1": "mån. förra veckan", "field-thu-relative+0": "torsdag denna vecka", "field-thu-relative+1": "torsdag nästa vecka", "field-fri-short-relative+-1": "fre. förra veckan", "field-thu-relative+-1": "torsdag förra veckan", "field-week": "vecka", "field-wed-narrow-relative+0": "denna ons.", "field-wed-narrow-relative+1": "nästa ons.", "field-quarter-narrow-relative+-1": "förra kv.", "field-year-short-relative+0": "i år", "field-dayperiod-short": "fm/em", "field-year-short-relative+1": "nästa år", "field-fri-short-relative+0": "fre. denna vecka", "field-fri-short-relative+1": "fre. nästa vecka", "field-week-short-relative+-1": "förra v.", "field-hour-narrow-relative+0": "denna timme", "field-hour-short": "tim", "field-zone-short": "tidszon", "field-month-narrow": "mån", "field-hour-narrow": "h", "field-fri-narrow-relative+-1": "förra fre.", "field-year-relative+0": "i år", "field-year-relative+1": "nästa år", "field-era-narrow": "era", "field-fri-relative+-1": "fredag förra veckan", "field-tue-short-relative+-1": "tis. förra veckan", "field-minute-narrow": "m", "field-year-short-relative+-1": "i fjol", "field-zone": "tidszon", "field-weekOfMonth-narrow": "vk.i mån.", "field-weekday-narrow": "veckodag", "field-quarter-narrow": "kv.", "field-sun-short-relative+-1": "sön. förra veckan", "field-day-relative+-1": "i går", "field-day-relative+-2": "i förrgår", "field-weekday-short": "veckodag", "field-sun-relative+0": "söndag denna vecka", "field-sun-relative+1": "söndag nästa vecka", "field-day-short": "dag", "field-week-narrow": "v", "field-era": "era", "field-fri-narrow-relative+0": "denna fre.", "field-fri-narrow-relative+1": "nästa fre." } //end v1.x content );
version https://git-lfs.github.com/spec/v1 oid sha256:ff6a5c1204e476c89870c6f14e75db666fa26de9359f9d8c372ef779b55c8875 size 2736
function example(name, deps) { console.log('This is where fpscounter plugin code would execute in the node process.'); } module.exports = example;
// Node if (typeof module !== 'undefined' && module.exports) { var numeral = require('../../numeral'); var expect = require('chai').expect; var language = require('../../languages/th'); } describe('Language: th', function() { before(function() { numeral.language('th', language); numeral.language('th'); }); after(function() { numeral.reset(); }); describe('Number', function() { it('should format a number', function() { var tests = [ [10000,'0,0.0000','10,000.0000'], [10000.23,'0,0','10,000'], [-10000,'0,0.0','-10,000.0'], [10000.1234,'0.000','10000.123'], [-10000,'(0,0.0000)','(10,000.0000)'], [-0.23,'.00','-.23'], [-0.23,'(.00)','(.23)'], [0.23,'0.00000','0.23000'], [1230974,'0.0a','1.2ล้าน'], [1460,'0a','1พัน'], [-104000,'0a','-104พัน'], [1,'0o','1.'], [52,'0o','52.'], [23,'0o','23.'], [100,'0o','100.'], [1,'0[.]0','1'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Currency', function() { it('should format a currency', function() { var tests = [ [1000.234,'$0,0.00','฿1,000.23'], [-1000.234,'($0,0)','(฿1,000)'], [-1000.234,'$0.00','-฿1000.23'], [1230974,'($0.00a)','฿1.23ล้าน'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Percentages', function() { it('should format a percentages', function() { var tests = [ [1,'0%','100%'], [0.974878234,'0.000%','97.488%'], [-0.43,'0%','-43%'], [0.43,'(0.000%)','43.000%'] ]; for (var i = 0; i < tests.length; i++) { expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]); } }); }); describe('Unformat', function() { it('should unformat', function() { var tests = [ ['10,000.123',10000.123], ['(0.12345)',-0.12345], ['(฿1.23ล้าน)',-1230000], ['10พัน',10000], ['-10พัน',-10000], ['23.',23], ['฿10,000.00',10000], ['-76%',-0.76], ['2:23:57',8637] ]; for (var i = 0; i < tests.length; i++) { expect(numeral().unformat(tests[i][0])).to.equal(tests[i][1]); } }); }); });
'use strict'; var BigNumber = require('../../type/BigNumber'); var Range = require('../../type/Range'); var Index = require('../../type/Index'); var isNumber = require('../../util/number').isNumber; /** * Attach a transform function to math.index * Adds a property transform containing the transform function. * * This transform creates a one-based index instead of a zero-based index * @param {Object} math */ module.exports = function (math) { var transform = function () { var args = []; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number if (arg instanceof Range) { arg.start--; arg.end -= (arg.step > 0 ? 0 : 2); } else if (isNumber(arg)) { arg--; } else if (arg instanceof BigNumber) { arg = arg.toNumber() - 1; } else { throw new TypeError('Ranges must be a Number or Range'); } args[i] = arg; } var res = new Index(); Index.apply(res, args); return res; }; math.index.transform = transform; return transform; };
define("ace/snippets/typescript",["require","exports","module"],function(e,t,n){"use strict";t.snippetText="",t.scope="typescript"}); (function() { window.require(["ace/snippets/typescript"], function(m) { if (typeof module == "object") { module.exports = m; } }); })();
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("../../utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); /** * @ignore - internal component. */ var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" }), 'Star'); exports.default = _default;
KB.onClick('.accordion-toggle', function (e) { var sectionElement = KB.dom(e.target).parent('.accordion-section'); if (sectionElement) { KB.dom(sectionElement).toggleClass('accordion-collapsed'); } });
alert("foo!");
})(); Clazz._coreLoaded = true;
// Don't need this for our purposes module = function(){}; if(typeof equal != 'undefined') { equals = equal; } ok = function(actual, message) { equal(actual, true, message); } raises = function(fn, expected, message) { raisesError(fn, message); }; asyncTest = function(name, delay, fn) { test(name, fn); } start = function() { // Just pass through... } notStrictEqual = function(a, b, message) { equal(a === b, false, message); } var ensureArray = function(obj) { if(obj === null) { return []; } else if(Object.isArray(obj) && (!obj.indexOf || !obj.lastIndexOf)) { return obj.concat(); } else if(!Object.isArray(obj) && typeof obj == 'object') { return Array.prototype.slice.call(obj); } else { return obj; } } var CompatibleMethods = [ { module: Array.prototype, methods: [ { name: 'first', method: function(arr, n, guard){ if(guard) { return arr[0]; } return ensureArray(arr).first(n); } }, { name: 'last', method: function(arr, n, third){ // This is the same check that Underscore makes to hack // _.last to work with _.map if(third) n = 1; return ensureArray(arr).last(n); } }, { name: 'rest', method: function(arr, n, guard){ if(n === undefined) n = 1; if(guard) { return arr.slice(1); } return ensureArray(arr).from(n); } }, { name: 'compact', method: function(arr){ return ensureArray(arr).compact(true); } }, /* Object.extend is no longer compatible as it has conflict resolution now. { name: 'extend', method: function(){ return Object.SugarMethods['merge'].method.apply(this, arguments); } }, */ /* Array#flatten is no longer compatible as it has levels of flattening (not just deep/shallow) { name: 'flatten', method: function(arr){ return ensureArray(arr).flatten(); } }, */ { name: 'uniq', method: function(arr){ return ensureArray(arr).unique(); } }, { name: 'intersection', method: function(arr){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.intersect.apply(arr, args); } }, { name: 'union', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.union.apply(arr, args); } }, /* { name: 'difference', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.subtract.apply(arr, args); } }, */ { name: 'indexOf', method: function(arr, a){ return ensureArray(arr).indexOf(a); } }, { name: 'lastIndexOf', method: function(arr, a){ return ensureArray(arr).lastIndexOf(a); } }, { name: 'range', method: function(start, stop, step){ if(arguments.length == 1){ stop = arguments[0]; start = 0; } var shift = step < 0 ? 1 : -1; return start.upto(stop + shift, null, step); } }, // Collections // _.each -> Array#forEach OR Object.each // _.map -> Array#map // _.reduce -> Array#reduce // _.reduceRight -> Array#reduceRight // _.invoke is doing some strange tapdancing for passing methods directly... // _.sortedIndex ... no direct equivalent // _.toArray ... no direct equivalent for arguments... Array.create? // _.size ... no direct equivalent for objects... obj.keys().length? { name: 'detect', method: function(arr, fn, context){ return Array.SugarMethods['find'].method.call(arr, fn.bind(context)); } }, { name: 'select', method: function(arr, fn, context){ return Array.SugarMethods['findAll'].method.call(arr, fn.bind(context)); } }, { name: 'reject', method: function(arr, fn, context){ return Array.SugarMethods['exclude'].method.call(arr, fn.bind(context)); } }, { name: 'all', method: function(arr, fn, context){ return Array.SugarMethods['all'].method.call(arr, fn.bind(context)); } }, { name: 'any', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['some'].method.call(arr, fn.bind(context)); } }, /* { name: 'include', method: function(arr, val){ return Array.SugarMethods['has'].method.call(arr, val); } }, */ { name: 'pluck', method: function(arr, prop){ return Array.SugarMethods['map'].method.call(arr, prop); } }, { name: 'max', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['max'].method.call(arr, fn.bind(context))[0]; } }, { name: 'min', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['min'].method.call(arr, fn.bind(context))[0]; } }, { name: 'sortBy', method: function(arr, fn, context){ return Array.SugarMethods['sortBy'].method.call(arr, fn.bind(context)); } }, { name: 'groupBy', method: function(arr, fn){ return Array.SugarMethods['groupBy'].method.call(arr, fn); } }, // Objects // _.functions ... no direct equivalent // _.defaults ... no direct equivalent // _.tap ... no direct equivalent // _.isElement ... no direct equivalent // _.isArguments ... no direct equivalent // _.isNaN ... no direct equivalent // _.isNull ... no direct equivalent // _.isUndefined ... no direct equivalent { name: 'keys', method: function(){ return Object.SugarMethods['keys'].method.apply(this, arguments); } }, { name: 'values', method: function(){ return Object.SugarMethods['values'].method.apply(this, arguments); } }, { name: 'clone', method: function(){ return Object.SugarMethods['clone'].method.apply(this, arguments); } }, { name: 'isEqual', method: function(a, b){ if (a && a._chain) a = a._wrapped; if (b && b._chain) b = b._wrapped; if (a && a.isEqual) return a.isEqual(b); if (b && b.isEqual) return b.isEqual(a); return Object.SugarMethods['equal'].method.apply(this, arguments); } }, { name: 'isEmpty', method: function(){ return Object.SugarMethods['isEmpty'].method.apply(this, arguments); } }, { name: 'isArray', method: function(arr){ return Array.isArray(arr); } }, { name: 'isFunction', method: function(){ return Object.SugarMethods['isFunction'].method.apply(this, arguments); } }, { name: 'isString', method: function(){ return Object.SugarMethods['isString'].method.apply(this, arguments); } }, { name: 'isNumber', method: function(){ if(isNaN(arguments[0])) { // Sugar differs here as it's trying to stay aligned with Javascript and is // checking types only. return false; } return Object.SugarMethods['isNumber'].method.apply(this, arguments); } }, { name: 'isBoolean', method: function(){ return Object.SugarMethods['isBoolean'].method.apply(this, arguments); } }, { name: 'isDate', method: function(){ return Object.SugarMethods['isDate'].method.apply(this, arguments); } }, { name: 'isRegExp', method: function(){ return Object.SugarMethods['isRegExp'].method.apply(this, arguments); } }, // Functions // _.bindAll ... no direct equivalent (similar to bindAsEventListener??) // _.memoize ... no direct equivalent // _.debounce ... no direct equivalent // _.once ... no direct equivalent.. is this not similar to memoize? // _.wrap ... no direct equivalent.. // _.compose ... no direct equivalent.. math stuff { name: 'bind', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.bind.apply(fn, args); } }, { name: 'after', method: function(num, fn){ return Function.prototype.after.apply(fn, [num]); } }, { name: 'delay', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, args); } }, { name: 'defer', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, [1].concat(args)); } }, { name: 'throttle', method: function(fn, wait){ return Function.prototype.lazy.apply(fn, [wait]); } }, // Utility // _.noConflict ... no direct equivalent // _.identity ... no direct equivalent // _.mixin ... no direct equivalent // _.uniqueId ... no direct equivalent // _.template ... no direct equivalent // _.chain ... no direct equivalent // _.value ... no direct equivalent { name: 'times', method: function(n, fn){ return n.times(fn); } } ] } ]; var mapMethods = function() { var proto; CompatibleMethods.forEach(function(cm) { cm.methods.forEach(function(m) { _[m.name] = m.method; }); }); } mapMethods();
/*@preserve * Tempus Dominus Bootstrap4 v5.0.0-alpha13 (https://tempusdominus.github.io/bootstrap-4/) * Copyright 2016-2017 Jonathan Peterson * Licensed under MIT (https://github.com/tempusdominus/bootstrap-3/blob/master/LICENSE) */ if (typeof jQuery === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires jQuery. jQuery must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } +function ($) { var version = $.fn.jquery.split(' ')[0].split('.'); if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1) || (version[0] >= 4)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least jQuery v1.9.1 but less than v4.0.0'); } }(jQuery); if (typeof moment === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires moment.js. Moment.js must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } var version = moment.version.split('.') if ((version[0] <= 2 && version[1] < 17) || (version[0] >= 3)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least moment.js v2.17.0 but less than v3.0.0'); } +function () { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // ReSharper disable once InconsistentNaming var DateTimePicker = function ($, moment) { // ReSharper disable InconsistentNaming var NAME = 'datetimepicker', VERSION = '5.0.0-alpha7', DATA_KEY = '' + NAME, EVENT_KEY = '.' + DATA_KEY, EMIT_EVENT_KEY = DATA_KEY + '.', DATA_API_KEY = '.data-api', Selector = { DATA_TOGGLE: '[data-toggle="' + DATA_KEY + '"]' }, ClassName = { INPUT: NAME + '-input' }, Event = { CHANGE: 'change' + EVENT_KEY, BLUR: 'blur' + EVENT_KEY, KEYUP: 'keyup' + EVENT_KEY, KEYDOWN: 'keydown' + EVENT_KEY, FOCUS: 'focus' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY, //emitted UPDATE: EMIT_EVENT_KEY + 'update', ERROR: EMIT_EVENT_KEY + 'error', HIDE: EMIT_EVENT_KEY + 'hide', SHOW: EMIT_EVENT_KEY + 'show' }, Default = { timeZone: '', format: false, dayViewHeaderFormat: 'MMMM YYYY', extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, collapse: true, locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'fa fa-clock-o', date: 'fa fa-calendar', up: 'fa fa-arrow-up', down: 'fa fa-arrow-down', previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-calendar-check-o', clear: 'fa fa-delete', close: 'fa fa-times' }, tooltips: { today: 'Go to today', clear: 'Clear selection', close: 'Close the picker', selectMonth: 'Select Month', prevMonth: 'Previous Month', nextMonth: 'Next Month', selectYear: 'Select Year', prevYear: 'Previous Year', nextYear: 'Next Year', selectDecade: 'Select Decade', prevDecade: 'Previous Decade', nextDecade: 'Next Decade', prevCentury: 'Previous Century', nextCentury: 'Next Century', pickHour: 'Pick Hour', incrementHour: 'Increment Hour', decrementHour: 'Decrement Hour', pickMinute: 'Pick Minute', incrementMinute: 'Increment Minute', decrementMinute: 'Decrement Minute', pickSecond: 'Pick Second', incrementSecond: 'Increment Second', decrementSecond: 'Decrement Second', togglePeriod: 'Toggle Period', selectTime: 'Select Time', selectDate: 'Select Date' }, useStrict: false, sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', toolbarPlacement: 'default', buttons: { showToday: false, showClear: false, showClose: false }, widgetPositioning: { horizontal: 'auto', vertical: 'auto' }, widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, keyBinds: { up: function up() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } return true; }, down: function down() { if (!this.widget) { this.show(); return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } return true; }, 'control up': function controlUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } return true; }, 'control down': function controlDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } return true; }, left: function left() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'd')); } return true; }, right: function right() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'd')); } return true; }, pageUp: function pageUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'M')); } return true; }, pageDown: function pageDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'M')); } return true; }, enter: function enter() { this.hide(); return true; }, escape: function escape() { if (!this.widget) { return false; } this.hide(); return true; }, 'control space': function controlSpace() { if (!this.widget) { return false; } if (this.widget.find('.timepicker').is(':visible')) { this.widget.find('.btn[data-action="togglePeriod"]').click(); } return true; }, t: function t() { this.date(this.getMoment()); return true; }, 'delete': function _delete() { if (!this.widget) { return false; } this.clear(); return true; } }, debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, viewDate: false, allowMultidate: false, multidateSeparator: ',' }, DatePickerModes = [{ CLASS_NAME: 'days', NAV_FUNCTION: 'M', NAV_STEP: 1 }, { CLASS_NAME: 'months', NAV_FUNCTION: 'y', NAV_STEP: 1 }, { CLASS_NAME: 'years', NAV_FUNCTION: 'y', NAV_STEP: 10 }, { CLASS_NAME: 'decades', NAV_FUNCTION: 'y', NAV_STEP: 100 }], KeyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, ViewModes = ['times', 'days', 'months', 'years', 'decades'], keyState = {}, keyPressHandled = {}; var MinViewModeNumber = 0; // ReSharper restore InconsistentNaming // ReSharper disable once DeclarationHides // ReSharper disable once InconsistentNaming var DateTimePicker = function () { /** @namespace eData.dateOptions */ /** @namespace moment.tz */ function DateTimePicker(element, options) { _classCallCheck(this, DateTimePicker); this._options = this._getOptions(options); this._element = element; this._dates = []; this._datesFormatted = []; this._viewDate = null; this.unset = true; this.component = false; this.widget = false; this.use24Hours = null; this.actualFormat = null; this.parseFormats = null; this.currentViewMode = null; this._int(); } /** * @return {string} */ //private DateTimePicker.prototype._int = function _int() { var targetInput = this._element.data('target-input'); if (this._element.is('input')) { this.input = this._element; } else if (targetInput !== undefined) { if (targetInput === 'nearest') { this.input = this._element.find('input'); } else { this.input = $(targetInput); } } this._dates = []; this._dates[0] = this.getMoment(); this._viewDate = this.getMoment().clone(); $.extend(true, this._options, this._dataToOptions()); this.options(this._options); this._initFormatting(); if (this.input !== undefined && this.input.is('input') && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this._options.defaultDate && this.input !== undefined && this.input.attr('placeholder') === undefined) { this._setValue(this._options.defaultDate, 0); } if (this._options.inline) { this.show(); } }; DateTimePicker.prototype._update = function _update() { if (!this.widget) { return; } this._fillDate(); this._fillTime(); }; DateTimePicker.prototype._setValue = function _setValue(targetMoment, index) { var oldDate = this.unset ? null : this._dates[index]; var outpValue = ''; // case of calling setValue(null or false) if (!targetMoment) { if (!this._options.allowMultidate || this._dates.length === 1) { this.unset = true; this._dates = []; this._datesFormatted = []; } else { outpValue = this._element.data('date') + ','; outpValue = outpValue.replace(oldDate.format(this.actualFormat) + ',', '').replace(',,', '').replace(/,\s*$/, ''); this._dates.splice(index, 1); this._datesFormatted.splice(index, 1); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: false, oldDate: oldDate }); this._update(); return; } targetMoment = targetMoment.clone().locale(this._options.locale); if (this._hasTimeZone()) { targetMoment.tz(this._options.timeZone); } if (this._options.stepping !== 1) { targetMoment.minutes(Math.round(targetMoment.minutes() / this._options.stepping) * this._options.stepping).seconds(0); } if (this._isValid(targetMoment)) { this._dates[index] = targetMoment; this._datesFormatted[index] = targetMoment.format('YYYY-MM-DD'); this._viewDate = targetMoment.clone(); if (this._options.allowMultidate && this._dates.length > 1) { for (var i = 0; i < this._dates.length; i++) { outpValue += '' + this._dates[i].format(this.actualFormat) + this._options.multidateSeparator; } outpValue = outpValue.replace(/,\s*$/, ''); } else { outpValue = this._dates[index].format(this.actualFormat); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this.unset = false; this._update(); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: this._dates[index].clone(), oldDate: oldDate }); } else { if (!this._options.keepInvalid) { if (this.input !== undefined) { this.input.val('' + (this.unset ? '' : this._dates[index].format(this.actualFormat))); this.input.trigger('input'); } } else { this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: targetMoment, oldDate: oldDate }); } this._notifyEvent({ type: DateTimePicker.Event.ERROR, date: targetMoment, oldDate: oldDate }); } }; DateTimePicker.prototype._change = function _change(e) { var val = $(e.target).val().trim(), parsedDate = val ? this._parseInputDate(val) : null; this._setValue(parsedDate); e.stopImmediatePropagation(); return false; }; //noinspection JSMethodCanBeStatic DateTimePicker.prototype._getOptions = function _getOptions(options) { options = $.extend(true, {}, Default, options); return options; }; DateTimePicker.prototype._hasTimeZone = function _hasTimeZone() { return moment.tz !== undefined && this._options.timeZone !== undefined && this._options.timeZone !== null && this._options.timeZone !== ''; }; DateTimePicker.prototype._isEnabled = function _isEnabled(granularity) { if (typeof granularity !== 'string' || granularity.length > 1) { throw new TypeError('isEnabled expects a single character string parameter'); } switch (granularity) { case 'y': return this.actualFormat.indexOf('Y') !== -1; case 'M': return this.actualFormat.indexOf('M') !== -1; case 'd': return this.actualFormat.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return this.actualFormat.toLowerCase().indexOf('h') !== -1; case 'm': return this.actualFormat.indexOf('m') !== -1; case 's': return this.actualFormat.indexOf('s') !== -1; default: return false; } }; DateTimePicker.prototype._hasTime = function _hasTime() { return this._isEnabled('h') || this._isEnabled('m') || this._isEnabled('s'); }; DateTimePicker.prototype._hasDate = function _hasDate() { return this._isEnabled('y') || this._isEnabled('M') || this._isEnabled('d'); }; DateTimePicker.prototype._dataToOptions = function _dataToOptions() { var eData = this._element.data(); var dataOptions = {}; if (eData.dateOptions && eData.dateOptions instanceof Object) { dataOptions = $.extend(true, dataOptions, eData.dateOptions); } $.each(this._options, function (key) { var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); //todo data api key if (eData[attributeName] !== undefined) { dataOptions[key] = eData[attributeName]; } else { delete dataOptions[key]; } }); return dataOptions; }; DateTimePicker.prototype._notifyEvent = function _notifyEvent(e) { if (e.type === DateTimePicker.Event.CHANGE && e.date && e.date.isSame(e.oldDate) || !e.date && !e.oldDate) { return; } this._element.trigger(e); }; DateTimePicker.prototype._viewUpdate = function _viewUpdate(e) { if (e === 'y') { e = 'YYYY'; } this._notifyEvent({ type: DateTimePicker.Event.UPDATE, change: e, viewDate: this._viewDate.clone() }); }; DateTimePicker.prototype._showMode = function _showMode(dir) { if (!this.widget) { return; } if (dir) { this.currentViewMode = Math.max(MinViewModeNumber, Math.min(3, this.currentViewMode + dir)); } this.widget.find('.datepicker > div').hide().filter('.datepicker-' + DatePickerModes[this.currentViewMode].CLASS_NAME).show(); }; DateTimePicker.prototype._isInDisabledDates = function _isInDisabledDates(testDate) { return this._options.disabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInEnabledDates = function _isInEnabledDates(testDate) { return this._options.enabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInDisabledHours = function _isInDisabledHours(testDate) { return this._options.disabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isInEnabledHours = function _isInEnabledHours(testDate) { return this._options.enabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isValid = function _isValid(targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (this._options.disabledDates && granularity === 'd' && this._isInDisabledDates(targetMoment)) { return false; } if (this._options.enabledDates && granularity === 'd' && !this._isInEnabledDates(targetMoment)) { return false; } if (this._options.minDate && targetMoment.isBefore(this._options.minDate, granularity)) { return false; } if (this._options.maxDate && targetMoment.isAfter(this._options.maxDate, granularity)) { return false; } if (this._options.daysOfWeekDisabled && granularity === 'd' && this._options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (this._options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && this._isInDisabledHours(targetMoment)) { return false; } if (this._options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !this._isInEnabledHours(targetMoment)) { return false; } if (this._options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $.each(this._options.disabledTimeIntervals, function () { if (targetMoment.isBetween(this[0], this[1])) { found = true; return false; } }); if (found) { return false; } } return true; }; DateTimePicker.prototype._parseInputDate = function _parseInputDate(inputDate) { if (this._options.parseInputDate === undefined) { if (!moment.isMoment(inputDate)) { inputDate = this.getMoment(inputDate); } } else { inputDate = this._options.parseInputDate(inputDate); } //inputDate.locale(this.options.locale); return inputDate; }; DateTimePicker.prototype._keydown = function _keydown(e) { var handler = null, index = void 0, index2 = void 0, keyBindKeys = void 0, allModifiersPressed = void 0; var pressedKeys = [], pressedModifiers = {}, currentKey = e.which, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in this._options.keyBinds) { if (this._options.keyBinds.hasOwnProperty(index) && typeof this._options.keyBinds[index] === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && KeyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(KeyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = this._options.keyBinds[index]; break; } } } } if (handler) { if (handler.call(this.widget)) { e.stopPropagation(); e.preventDefault(); } } }; //noinspection JSMethodCanBeStatic,SpellCheckingInspection DateTimePicker.prototype._keyup = function _keyup(e) { keyState[e.which] = 'r'; if (keyPressHandled[e.which]) { keyPressHandled[e.which] = false; e.stopPropagation(); e.preventDefault(); } }; DateTimePicker.prototype._indexGivenDates = function _indexGivenDates(givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}, self = this; $.each(givenDatesArray, function () { var dDate = self._parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return Object.keys(givenDatesIndexed).length ? givenDatesIndexed : false; }; DateTimePicker.prototype._indexGivenHours = function _indexGivenHours(givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return Object.keys(givenHoursIndexed).length ? givenHoursIndexed : false; }; DateTimePicker.prototype._initFormatting = function _initFormatting() { var format = this._options.format || 'L LT', self = this; this.actualFormat = format.replace(/(\[[^\[]*])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { return self._dates[0].localeData().longDateFormat(formatInput) || formatInput; //todo taking the first date should be ok }); this.parseFormats = this._options.extraFormats ? this._options.extraFormats.slice() : []; if (this.parseFormats.indexOf(format) < 0 && this.parseFormats.indexOf(this.actualFormat) < 0) { this.parseFormats.push(this.actualFormat); } this.use24Hours = this.actualFormat.toLowerCase().indexOf('a') < 1 && this.actualFormat.replace(/\[.*?]/g, '').indexOf('h') < 1; if (this._isEnabled('y')) { MinViewModeNumber = 2; } if (this._isEnabled('M')) { MinViewModeNumber = 1; } if (this._isEnabled('d')) { MinViewModeNumber = 0; } this.currentViewMode = Math.max(MinViewModeNumber, this.currentViewMode); if (!this.unset) { this._setValue(this._dates[0], 0); } }; DateTimePicker.prototype._getLastPickedDate = function _getLastPickedDate() { return this._dates[this._getLastPickedDateIndex()]; }; DateTimePicker.prototype._getLastPickedDateIndex = function _getLastPickedDateIndex() { return this._dates.length - 1; }; //public DateTimePicker.prototype.getMoment = function getMoment(d) { var returnMoment = void 0; if (d === undefined || d === null) { returnMoment = moment(); //TODO should this use format? and locale? } else if (this._hasTimeZone()) { // There is a string to parse and a default time zone // parse with the tz function which takes a default time zone if it is not in the format string returnMoment = moment.tz(d, this.parseFormats, this._options.useStrict, this._options.timeZone); } else { returnMoment = moment(d, this.parseFormats, this._options.useStrict); } if (this._hasTimeZone()) { returnMoment.tz(this._options.timeZone); } return returnMoment; }; DateTimePicker.prototype.toggle = function toggle() { return this.widget ? this.hide() : this.show(); }; DateTimePicker.prototype.ignoreReadonly = function ignoreReadonly(_ignoreReadonly) { if (arguments.length === 0) { return this._options.ignoreReadonly; } if (typeof _ignoreReadonly !== 'boolean') { throw new TypeError('ignoreReadonly () expects a boolean parameter'); } this._options.ignoreReadonly = _ignoreReadonly; }; DateTimePicker.prototype.options = function options(newOptions) { if (arguments.length === 0) { return $.extend(true, {}, this._options); } if (!(newOptions instanceof Object)) { throw new TypeError('options() this.options parameter should be an object'); } $.extend(true, this._options, newOptions); var self = this; $.each(this._options, function (key, value) { if (self[key] !== undefined) { self[key](value); } }); }; DateTimePicker.prototype.date = function date(newDate, index) { index = index || 0; if (arguments.length === 0) { if (this.unset) { return null; } if (this._options.allowMultidate) { return this._dates.join(this._options.multidateSeparator); } else { return this._dates[index].clone(); } } if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); } this._setValue(newDate === null ? null : this._parseInputDate(newDate), index); }; DateTimePicker.prototype.format = function format(newFormat) { ///<summary>test su</summary> ///<param name="newFormat">info about para</param> ///<returns type="string|boolean">returns foo</returns> if (arguments.length === 0) { return this._options.format; } if (typeof newFormat !== 'string' && (typeof newFormat !== 'boolean' || newFormat !== false)) { throw new TypeError('format() expects a string or boolean:false parameter ' + newFormat); } this._options.format = newFormat; if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } }; DateTimePicker.prototype.timeZone = function timeZone(newZone) { if (arguments.length === 0) { return this._options.timeZone; } if (typeof newZone !== 'string') { throw new TypeError('newZone() expects a string parameter'); } this._options.timeZone = newZone; }; DateTimePicker.prototype.dayViewHeaderFormat = function dayViewHeaderFormat(newFormat) { if (arguments.length === 0) { return this._options.dayViewHeaderFormat; } if (typeof newFormat !== 'string') { throw new TypeError('dayViewHeaderFormat() expects a string parameter'); } this._options.dayViewHeaderFormat = newFormat; }; DateTimePicker.prototype.extraFormats = function extraFormats(formats) { if (arguments.length === 0) { return this._options.extraFormats; } if (formats !== false && !(formats instanceof Array)) { throw new TypeError('extraFormats() expects an array or false parameter'); } this._options.extraFormats = formats; if (this.parseFormats) { this._initFormatting(); // reinit formatting } }; DateTimePicker.prototype.disabledDates = function disabledDates(dates) { if (arguments.length === 0) { return this._options.disabledDates ? $.extend({}, this._options.disabledDates) : this._options.disabledDates; } if (!dates) { this._options.disabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('disabledDates() expects an array parameter'); } this._options.disabledDates = this._indexGivenDates(dates); this._options.enabledDates = false; this._update(); }; DateTimePicker.prototype.enabledDates = function enabledDates(dates) { if (arguments.length === 0) { return this._options.enabledDates ? $.extend({}, this._options.enabledDates) : this._options.enabledDates; } if (!dates) { this._options.enabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('enabledDates() expects an array parameter'); } this._options.enabledDates = this._indexGivenDates(dates); this._options.disabledDates = false; this._update(); }; DateTimePicker.prototype.daysOfWeekDisabled = function daysOfWeekDisabled(_daysOfWeekDisabled) { if (arguments.length === 0) { return this._options.daysOfWeekDisabled.splice(0); } if (typeof _daysOfWeekDisabled === 'boolean' && !_daysOfWeekDisabled) { this._options.daysOfWeekDisabled = false; this._update(); return true; } if (!(_daysOfWeekDisabled instanceof Array)) { throw new TypeError('daysOfWeekDisabled() expects an array parameter'); } this._options.daysOfWeekDisabled = _daysOfWeekDisabled.reduce(function (previousValue, currentValue) { currentValue = parseInt(currentValue, 10); if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { return previousValue; } if (previousValue.indexOf(currentValue) === -1) { previousValue.push(currentValue); } return previousValue; }, []).sort(); if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'd')) { this._dates[i].add(1, 'd'); if (tries === 31) { throw 'Tried 31 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.maxDate = function maxDate(_maxDate) { if (arguments.length === 0) { return this._options.maxDate ? this._options.maxDate.clone() : this._options.maxDate; } if (typeof _maxDate === 'boolean' && _maxDate === false) { this._options.maxDate = false; this._update(); return true; } if (typeof _maxDate === 'string') { if (_maxDate === 'now' || _maxDate === 'moment') { _maxDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_maxDate); if (!parsedDate.isValid()) { throw new TypeError('maxDate() Could not parse date parameter: ' + _maxDate); } if (this._options.minDate && parsedDate.isBefore(this._options.minDate)) { throw new TypeError('maxDate() date parameter is before this.options.minDate: ' + parsedDate.format(this.actualFormat)); } this._options.maxDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isAfter(_maxDate)) { this._setValue(this._options.maxDate, i); } } if (this._viewDate.isAfter(parsedDate)) { this._viewDate = parsedDate.clone().subtract(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.minDate = function minDate(_minDate) { if (arguments.length === 0) { return this._options.minDate ? this._options.minDate.clone() : this._options.minDate; } if (typeof _minDate === 'boolean' && _minDate === false) { this._options.minDate = false; this._update(); return true; } if (typeof _minDate === 'string') { if (_minDate === 'now' || _minDate === 'moment') { _minDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_minDate); if (!parsedDate.isValid()) { throw new TypeError('minDate() Could not parse date parameter: ' + _minDate); } if (this._options.maxDate && parsedDate.isAfter(this._options.maxDate)) { throw new TypeError('minDate() date parameter is after this.options.maxDate: ' + parsedDate.format(this.actualFormat)); } this._options.minDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isBefore(_minDate)) { this._setValue(this._options.minDate, i); } } if (this._viewDate.isBefore(parsedDate)) { this._viewDate = parsedDate.clone().add(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.defaultDate = function defaultDate(_defaultDate) { if (arguments.length === 0) { return this._options.defaultDate ? this._options.defaultDate.clone() : this._options.defaultDate; } if (!_defaultDate) { this._options.defaultDate = false; return true; } if (typeof _defaultDate === 'string') { if (_defaultDate === 'now' || _defaultDate === 'moment') { _defaultDate = this.getMoment(); } else { _defaultDate = this.getMoment(_defaultDate); } } var parsedDate = this._parseInputDate(_defaultDate); if (!parsedDate.isValid()) { throw new TypeError('defaultDate() Could not parse date parameter: ' + _defaultDate); } if (!this._isValid(parsedDate)) { throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); } this._options.defaultDate = parsedDate; if (this._options.defaultDate && this._options.inline || this.input !== undefined && this.input.val().trim() === '') { this._setValue(this._options.defaultDate, 0); } }; DateTimePicker.prototype.locale = function locale(_locale) { if (arguments.length === 0) { return this._options.locale; } if (!moment.localeData(_locale)) { throw new TypeError('locale() locale ' + _locale + ' is not loaded from moment locales!'); } for (var i = 0; i < this._dates.length; i++) { this._dates[i].locale(this._options.locale); } this._viewDate.locale(this._options.locale); if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.stepping = function stepping(_stepping) { if (arguments.length === 0) { return this._options.stepping; } _stepping = parseInt(_stepping, 10); if (isNaN(_stepping) || _stepping < 1) { _stepping = 1; } this._options.stepping = _stepping; }; DateTimePicker.prototype.useCurrent = function useCurrent(_useCurrent) { var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; if (arguments.length === 0) { return this._options.useCurrent; } if (typeof _useCurrent !== 'boolean' && typeof _useCurrent !== 'string') { throw new TypeError('useCurrent() expects a boolean or string parameter'); } if (typeof _useCurrent === 'string' && useCurrentOptions.indexOf(_useCurrent.toLowerCase()) === -1) { throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); } this._options.useCurrent = _useCurrent; }; DateTimePicker.prototype.collapse = function collapse(_collapse) { if (arguments.length === 0) { return this._options.collapse; } if (typeof _collapse !== 'boolean') { throw new TypeError('collapse() expects a boolean parameter'); } if (this._options.collapse === _collapse) { return true; } this._options.collapse = _collapse; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.icons = function icons(_icons) { if (arguments.length === 0) { return $.extend({}, this._options.icons); } if (!(_icons instanceof Object)) { throw new TypeError('icons() expects parameter to be an Object'); } $.extend(this._options.icons, _icons); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.tooltips = function tooltips(_tooltips) { if (arguments.length === 0) { return $.extend({}, this._options.tooltips); } if (!(_tooltips instanceof Object)) { throw new TypeError('tooltips() expects parameter to be an Object'); } $.extend(this._options.tooltips, _tooltips); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.useStrict = function useStrict(_useStrict) { if (arguments.length === 0) { return this._options.useStrict; } if (typeof _useStrict !== 'boolean') { throw new TypeError('useStrict() expects a boolean parameter'); } this._options.useStrict = _useStrict; }; DateTimePicker.prototype.sideBySide = function sideBySide(_sideBySide) { if (arguments.length === 0) { return this._options.sideBySide; } if (typeof _sideBySide !== 'boolean') { throw new TypeError('sideBySide() expects a boolean parameter'); } this._options.sideBySide = _sideBySide; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.viewMode = function viewMode(_viewMode) { if (arguments.length === 0) { return this._options.viewMode; } if (typeof _viewMode !== 'string') { throw new TypeError('viewMode() expects a string parameter'); } if (DateTimePicker.ViewModes.indexOf(_viewMode) === -1) { throw new TypeError('viewMode() parameter must be one of (' + DateTimePicker.ViewModes.join(', ') + ') value'); } this._options.viewMode = _viewMode; this.currentViewMode = Math.max(DateTimePicker.ViewModes.indexOf(_viewMode) - 1, DateTimePicker.MinViewModeNumber); this._showMode(); }; DateTimePicker.prototype.calendarWeeks = function calendarWeeks(_calendarWeeks) { if (arguments.length === 0) { return this._options.calendarWeeks; } if (typeof _calendarWeeks !== 'boolean') { throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); } this._options.calendarWeeks = _calendarWeeks; this._update(); }; DateTimePicker.prototype.buttons = function buttons(_buttons) { if (arguments.length === 0) { return $.extend({}, this._options.buttons); } if (!(_buttons instanceof Object)) { throw new TypeError('buttons() expects parameter to be an Object'); } $.extend(this._options.buttons, _buttons); if (typeof this._options.buttons.showToday !== 'boolean') { throw new TypeError('buttons.showToday expects a boolean parameter'); } if (typeof this._options.buttons.showClear !== 'boolean') { throw new TypeError('buttons.showClear expects a boolean parameter'); } if (typeof this._options.buttons.showClose !== 'boolean') { throw new TypeError('buttons.showClose expects a boolean parameter'); } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.keepOpen = function keepOpen(_keepOpen) { if (arguments.length === 0) { return this._options.keepOpen; } if (typeof _keepOpen !== 'boolean') { throw new TypeError('keepOpen() expects a boolean parameter'); } this._options.keepOpen = _keepOpen; }; DateTimePicker.prototype.focusOnShow = function focusOnShow(_focusOnShow) { if (arguments.length === 0) { return this._options.focusOnShow; } if (typeof _focusOnShow !== 'boolean') { throw new TypeError('focusOnShow() expects a boolean parameter'); } this._options.focusOnShow = _focusOnShow; }; DateTimePicker.prototype.inline = function inline(_inline) { if (arguments.length === 0) { return this._options.inline; } if (typeof _inline !== 'boolean') { throw new TypeError('inline() expects a boolean parameter'); } this._options.inline = _inline; }; DateTimePicker.prototype.clear = function clear() { this._setValue(null); //todo }; DateTimePicker.prototype.keyBinds = function keyBinds(_keyBinds) { if (arguments.length === 0) { return this._options.keyBinds; } this._options.keyBinds = _keyBinds; }; DateTimePicker.prototype.debug = function debug(_debug) { if (typeof _debug !== 'boolean') { throw new TypeError('debug() expects a boolean parameter'); } this._options.debug = _debug; }; DateTimePicker.prototype.allowInputToggle = function allowInputToggle(_allowInputToggle) { if (arguments.length === 0) { return this._options.allowInputToggle; } if (typeof _allowInputToggle !== 'boolean') { throw new TypeError('allowInputToggle() expects a boolean parameter'); } this._options.allowInputToggle = _allowInputToggle; }; DateTimePicker.prototype.keepInvalid = function keepInvalid(_keepInvalid) { if (arguments.length === 0) { return this._options.keepInvalid; } if (typeof _keepInvalid !== 'boolean') { throw new TypeError('keepInvalid() expects a boolean parameter'); } this._options.keepInvalid = _keepInvalid; }; DateTimePicker.prototype.datepickerInput = function datepickerInput(_datepickerInput) { if (arguments.length === 0) { return this._options.datepickerInput; } if (typeof _datepickerInput !== 'string') { throw new TypeError('datepickerInput() expects a string parameter'); } this._options.datepickerInput = _datepickerInput; }; DateTimePicker.prototype.parseInputDate = function parseInputDate(_parseInputDate2) { if (arguments.length === 0) { return this._options.parseInputDate; } if (typeof _parseInputDate2 !== 'function') { throw new TypeError('parseInputDate() should be as function'); } this._options.parseInputDate = _parseInputDate2; }; DateTimePicker.prototype.disabledTimeIntervals = function disabledTimeIntervals(_disabledTimeIntervals) { if (arguments.length === 0) { return this._options.disabledTimeIntervals ? $.extend({}, this._options.disabledTimeIntervals) : this._options.disabledTimeIntervals; } if (!_disabledTimeIntervals) { this._options.disabledTimeIntervals = false; this._update(); return true; } if (!(_disabledTimeIntervals instanceof Array)) { throw new TypeError('disabledTimeIntervals() expects an array parameter'); } this._options.disabledTimeIntervals = _disabledTimeIntervals; this._update(); }; DateTimePicker.prototype.disabledHours = function disabledHours(hours) { if (arguments.length === 0) { return this._options.disabledHours ? $.extend({}, this._options.disabledHours) : this._options.disabledHours; } if (!hours) { this._options.disabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('disabledHours() expects an array parameter'); } this._options.disabledHours = this._indexGivenHours(hours); this._options.enabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.enabledHours = function enabledHours(hours) { if (arguments.length === 0) { return this._options.enabledHours ? $.extend({}, this._options.enabledHours) : this._options.enabledHours; } if (!hours) { this._options.enabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('enabledHours() expects an array parameter'); } this._options.enabledHours = this._indexGivenHours(hours); this._options.disabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.viewDate = function viewDate(newDate) { if (arguments.length === 0) { return this._viewDate.clone(); } if (!newDate) { this._viewDate = (this._dates[0] || this.getMoment()).clone(); return true; } if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); } this._viewDate = this._parseInputDate(newDate); this._viewUpdate(); }; DateTimePicker.prototype.allowMultidate = function allowMultidate(_allowMultidate) { if (typeof _allowMultidate !== 'boolean') { throw new TypeError('allowMultidate() expects a boolean parameter'); } this._options.allowMultidate = _allowMultidate; }; DateTimePicker.prototype.multidateSeparator = function multidateSeparator(_multidateSeparator) { if (arguments.length === 0) { return this._options.multidateSeparator; } if (typeof _multidateSeparator !== 'string' || _multidateSeparator.length > 1) { throw new TypeError('multidateSeparator expects a single character string parameter'); } this._options.multidateSeparator = _multidateSeparator; }; _createClass(DateTimePicker, null, [{ key: 'NAME', get: function get() { return NAME; } /** * @return {string} */ }, { key: 'VERSION', get: function get() { return VERSION; } /** * @return {string} */ }, { key: 'DATA_KEY', get: function get() { return DATA_KEY; } /** * @return {string} */ }, { key: 'EVENT_KEY', get: function get() { return EVENT_KEY; } /** * @return {string} */ }, { key: 'DATA_API_KEY', get: function get() { return DATA_API_KEY; } }, { key: 'DatePickerModes', get: function get() { return DatePickerModes; } }, { key: 'ViewModes', get: function get() { return ViewModes; } /** * @return {number} */ }, { key: 'MinViewModeNumber', get: function get() { return MinViewModeNumber; } }, { key: 'Event', get: function get() { return Event; } }, { key: 'Selector', get: function get() { return Selector; } }, { key: 'Default', get: function get() { return Default; } }, { key: 'ClassName', get: function get() { return ClassName; } }]); return DateTimePicker; }(); return DateTimePicker; }(jQuery, moment); //noinspection JSUnusedGlobalSymbols /* global DateTimePicker */ var TempusDominusBootstrap4 = function ($) { // eslint-disable-line no-unused-vars // ReSharper disable once InconsistentNaming var JQUERY_NO_CONFLICT = $.fn[DateTimePicker.NAME], verticalModes = ['top', 'bottom', 'auto'], horizontalModes = ['left', 'right', 'auto'], toolbarPlacements = ['default', 'top', 'bottom'], getSelectorFromElement = function getSelectorFromElement($element) { var selector = $element.data('target'), $selector = void 0; if (!selector) { selector = $element.attr('href') || ''; selector = /^#[a-z]/i.test(selector) ? selector : null; } $selector = $(selector); if ($selector.length === 0) { return $selector; } if (!$selector.data(DateTimePicker.DATA_KEY)) { $.extend({}, $selector.data(), $(this).data()); } return $selector; }; // ReSharper disable once InconsistentNaming var TempusDominusBootstrap4 = function (_DateTimePicker) { _inherits(TempusDominusBootstrap4, _DateTimePicker); function TempusDominusBootstrap4(element, options) { _classCallCheck(this, TempusDominusBootstrap4); var _this = _possibleConstructorReturn(this, _DateTimePicker.call(this, element, options)); _this._init(); return _this; } TempusDominusBootstrap4.prototype._init = function _init() { if (this._element.hasClass('input-group')) { // in case there is more then one 'input-group-addon' Issue #48 var datepickerButton = this._element.find('.datepickerbutton'); if (datepickerButton.length === 0) { this.component = this._element.find('.input-group-addon'); } else { this.component = datepickerButton; } } }; TempusDominusBootstrap4.prototype._getDatePickerTemplate = function _getDatePickerTemplate() { var headTemplate = $('<thead>').append($('<tr>').append($('<th>').addClass('prev').attr('data-action', 'previous').append($('<span>').addClass(this._options.icons.previous))).append($('<th>').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', '' + (this._options.calendarWeeks ? '6' : '5'))).append($('<th>').addClass('next').attr('data-action', 'next').append($('<span>').addClass(this._options.icons.next)))), contTemplate = $('<tbody>').append($('<tr>').append($('<td>').attr('colspan', '' + (this._options.calendarWeeks ? '8' : '7')))); return [$('<div>').addClass('datepicker-days').append($('<table>').addClass('table table-sm').append(headTemplate).append($('<tbody>'))), $('<div>').addClass('datepicker-months').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-years').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-decades').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone()))]; }; TempusDominusBootstrap4.prototype._getTimePickerMainTemplate = function _getTimePickerMainTemplate() { var topRow = $('<tr>'), middleRow = $('<tr>'), bottomRow = $('<tr>'); if (this._isEnabled('h')) { topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementHour }).addClass('btn').attr('data-action', 'incrementHours').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-hour').attr({ 'data-time-component': 'hours', 'title': this._options.tooltips.pickHour }).attr('data-action', 'showHours'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementHour }).addClass('btn').attr('data-action', 'decrementHours').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('m')) { if (this._isEnabled('h')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementMinute }).addClass('btn').attr('data-action', 'incrementMinutes').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-minute').attr({ 'data-time-component': 'minutes', 'title': this._options.tooltips.pickMinute }).attr('data-action', 'showMinutes'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementMinute }).addClass('btn').attr('data-action', 'decrementMinutes').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('s')) { if (this._isEnabled('m')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementSecond }).addClass('btn').attr('data-action', 'incrementSeconds').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-second').attr({ 'data-time-component': 'seconds', 'title': this._options.tooltips.pickSecond }).attr('data-action', 'showSeconds'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementSecond }).addClass('btn').attr('data-action', 'decrementSeconds').append($('<span>').addClass(this._options.icons.down)))); } if (!this.use24Hours) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').append($('<button>').addClass('btn btn-primary').attr({ 'data-action': 'togglePeriod', tabindex: '-1', 'title': this._options.tooltips.togglePeriod }))); bottomRow.append($('<td>').addClass('separator')); } return $('<div>').addClass('timepicker-picker').append($('<table>').addClass('table-condensed').append([topRow, middleRow, bottomRow])); }; TempusDominusBootstrap4.prototype._getTimePickerTemplate = function _getTimePickerTemplate() { var hoursView = $('<div>').addClass('timepicker-hours').append($('<table>').addClass('table-condensed')), minutesView = $('<div>').addClass('timepicker-minutes').append($('<table>').addClass('table-condensed')), secondsView = $('<div>').addClass('timepicker-seconds').append($('<table>').addClass('table-condensed')), ret = [this._getTimePickerMainTemplate()]; if (this._isEnabled('h')) { ret.push(hoursView); } if (this._isEnabled('m')) { ret.push(minutesView); } if (this._isEnabled('s')) { ret.push(secondsView); } return ret; }; TempusDominusBootstrap4.prototype._getToolbar = function _getToolbar() { var row = []; if (this._options.buttons.showToday) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'today', 'title': this._options.tooltips.today }).append($('<span>').addClass(this._options.icons.today)))); } if (!this._options.sideBySide && this._hasDate() && this._hasTime()) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'togglePicker', 'title': this._options.tooltips.selectTime }).append($('<span>').addClass(this._options.icons.time)))); } if (this._options.buttons.showClear) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'clear', 'title': this._options.tooltips.clear }).append($('<span>').addClass(this._options.icons.clear)))); } if (this._options.buttons.showClose) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'close', 'title': this._options.tooltips.close }).append($('<span>').addClass(this._options.icons.close)))); } return row.length === 0 ? '' : $('<table>').addClass('table-condensed').append($('<tbody>').append($('<tr>').append(row))); }; TempusDominusBootstrap4.prototype._getTemplate = function _getTemplate() { var template = $('<div>').addClass('bootstrap-datetimepicker-widget dropdown-menu'), dateView = $('<div>').addClass('datepicker').append(this._getDatePickerTemplate()), timeView = $('<div>').addClass('timepicker').append(this._getTimePickerTemplate()), content = $('<ul>').addClass('list-unstyled'), toolbar = $('<li>').addClass('picker-switch' + (this._options.collapse ? ' accordion-toggle' : '')).append(this._getToolbar()); if (this._options.inline) { template.removeClass('dropdown-menu'); } if (this.use24Hours) { template.addClass('usetwentyfour'); } if (this._isEnabled('s') && !this.use24Hours) { template.addClass('wider'); } if (this._options.sideBySide && this._hasDate() && this._hasTime()) { template.addClass('timepicker-sbs'); if (this._options.toolbarPlacement === 'top') { template.append(toolbar); } template.append($('<div>').addClass('row').append(dateView.addClass('col-md-6')).append(timeView.addClass('col-md-6'))); if (this._options.toolbarPlacement === 'bottom' || this._options.toolbarPlacement === 'default') { template.append(toolbar); } return template; } if (this._options.toolbarPlacement === 'top') { content.append(toolbar); } if (this._hasDate()) { content.append($('<li>').addClass(this._options.collapse && this._hasTime() ? 'collapse' : '').addClass(this._options.collapse && this._hasTime() && this._options.viewMode === 'time' ? '' : 'show').append(dateView)); } if (this._options.toolbarPlacement === 'default') { content.append(toolbar); } if (this._hasTime()) { content.append($('<li>').addClass(this._options.collapse && this._hasDate() ? 'collapse' : '').addClass(this._options.collapse && this._hasDate() && this._options.viewMode === 'time' ? 'show' : '').append(timeView)); } if (this._options.toolbarPlacement === 'bottom') { content.append(toolbar); } return template.append(content); }; TempusDominusBootstrap4.prototype._place = function _place(e) { var self = e && e.data && e.data.picker || this, vertical = self._options.widgetPositioning.vertical, horizontal = self._options.widgetPositioning.horizontal, parent = void 0; var position = (self.component || self._element).position(), offset = (self.component || self._element).offset(); if (self._options.widgetParent) { parent = self._options.widgetParent.append(self.widget); } else if (self._element.is('input')) { parent = self._element.after(self.widget).parent(); } else if (self._options.inline) { parent = self._element.append(self.widget); return; } else { parent = self._element; self._element.children().first().after(self.widget); } // Top and bottom logic if (vertical === 'auto') { //noinspection JSValidateTypes if (offset.top + self.widget.height() * 1.5 >= $(window).height() + $(window).scrollTop() && self.widget.height() + self._element.outerHeight() < offset.top) { vertical = 'top'; } else { vertical = 'bottom'; } } // Left and right logic if (horizontal === 'auto') { if (parent.width() < offset.left + self.widget.outerWidth() / 2 && offset.left + self.widget.outerWidth() > $(window).width()) { horizontal = 'right'; } else { horizontal = 'left'; } } if (vertical === 'top') { self.widget.addClass('top').removeClass('bottom'); } else { self.widget.addClass('bottom').removeClass('top'); } if (horizontal === 'right') { self.widget.addClass('float-right'); } else { self.widget.removeClass('float-right'); } // find the first parent element that has a relative css positioning if (parent.css('position') !== 'relative') { parent = parent.parents().filter(function () { return $(this).css('position') === 'relative'; }).first(); } if (parent.length === 0) { throw new Error('datetimepicker component should be placed within a relative positioned container'); } self.widget.css({ top: vertical === 'top' ? 'auto' : position.top + self._element.outerHeight() + 'px', bottom: vertical === 'top' ? parent.outerHeight() - (parent === self._element ? 0 : position.top) + 'px' : 'auto', left: horizontal === 'left' ? (parent === self._element ? 0 : position.left) + 'px' : 'auto', right: horizontal === 'left' ? 'auto' : parent.outerWidth() - self._element.outerWidth() - (parent === self._element ? 0 : position.left) + 'px' }); }; TempusDominusBootstrap4.prototype._fillDow = function _fillDow() { var row = $('<tr>'), currentDate = this._viewDate.clone().startOf('w').startOf('d'); if (this._options.calendarWeeks === true) { row.append($('<th>').addClass('cw').text('#')); } while (currentDate.isBefore(this._viewDate.clone().endOf('w'))) { row.append($('<th>').addClass('dow').text(currentDate.format('dd'))); currentDate.add(1, 'd'); } this.widget.find('.datepicker-days thead').append(row); }; TempusDominusBootstrap4.prototype._fillMonths = function _fillMonths() { var spans = [], monthsShort = this._viewDate.clone().startOf('y').startOf('d'); while (monthsShort.isSame(this._viewDate, 'y')) { spans.push($('<span>').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM'))); monthsShort.add(1, 'M'); } this.widget.find('.datepicker-months td').empty().append(spans); }; TempusDominusBootstrap4.prototype._updateMonths = function _updateMonths() { var monthsView = this.widget.find('.datepicker-months'), monthsViewHeader = monthsView.find('th'), months = monthsView.find('tbody').find('span'), self = this; monthsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevYear); monthsViewHeader.eq(1).attr('title', this._options.tooltips.selectYear); monthsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextYear); monthsView.find('.disabled').removeClass('disabled'); if (!this._isValid(this._viewDate.clone().subtract(1, 'y'), 'y')) { monthsViewHeader.eq(0).addClass('disabled'); } monthsViewHeader.eq(1).text(this._viewDate.year()); if (!this._isValid(this._viewDate.clone().add(1, 'y'), 'y')) { monthsViewHeader.eq(2).addClass('disabled'); } months.removeClass('active'); if (this._getLastPickedDate().isSame(this._viewDate, 'y') && !this.unset) { months.eq(this._getLastPickedDate().month()).addClass('active'); } months.each(function (index) { if (!self._isValid(self._viewDate.clone().month(index), 'M')) { $(this).addClass('disabled'); } }); }; TempusDominusBootstrap4.prototype._getStartEndYear = function _getStartEndYear(factor, year) { var step = factor / 10, startYear = Math.floor(year / factor) * factor, endYear = startYear + step * 9, focusValue = Math.floor(year / step) * step; return [startYear, endYear, focusValue]; }; TempusDominusBootstrap4.prototype._updateYears = function _updateYears() { var yearsView = this.widget.find('.datepicker-years'), yearsViewHeader = yearsView.find('th'), yearCaps = this._getStartEndYear(10, this._viewDate.year()), startYear = this._viewDate.clone().year(yearCaps[0]), endYear = this._viewDate.clone().year(yearCaps[1]); var html = ''; yearsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevDecade); yearsViewHeader.eq(1).attr('title', this._options.tooltips.selectDecade); yearsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextDecade); yearsView.find('.disabled').removeClass('disabled'); if (this._options.minDate && this._options.minDate.isAfter(startYear, 'y')) { yearsViewHeader.eq(0).addClass('disabled'); } yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endYear, 'y')) { yearsViewHeader.eq(2).addClass('disabled'); } html += '<span data-action="selectYear" class="year old">' + (startYear.year() - 1) + '</span>'; while (!startYear.isAfter(endYear, 'y')) { html += '<span data-action="selectYear" class="year' + (startYear.isSame(this._getLastPickedDate(), 'y') && !this.unset ? ' active' : '') + (!this._isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } html += '<span data-action="selectYear" class="year old">' + startYear.year() + '</span>'; yearsView.find('td').html(html); }; TempusDominusBootstrap4.prototype._updateDecades = function _updateDecades() { var decadesView = this.widget.find('.datepicker-decades'), decadesViewHeader = decadesView.find('th'), yearCaps = this._getStartEndYear(100, this._viewDate.year()), startDecade = this._viewDate.clone().year(yearCaps[0]), endDecade = this._viewDate.clone().year(yearCaps[1]); var minDateDecade = false, maxDateDecade = false, endDecadeYear = void 0, html = ''; decadesViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevCentury); decadesViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextCentury); decadesView.find('.disabled').removeClass('disabled'); if (startDecade.year() === 0 || this._options.minDate && this._options.minDate.isAfter(startDecade, 'y')) { decadesViewHeader.eq(0).addClass('disabled'); } decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endDecade, 'y')) { decadesViewHeader.eq(2).addClass('disabled'); } if (startDecade.year() - 10 < 0) { html += '<span>&nbsp;</span>'; } else { html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() - 10) + '</span>'; } while (!startDecade.isAfter(endDecade, 'y')) { endDecadeYear = startDecade.year() + 11; minDateDecade = this._options.minDate && this._options.minDate.isAfter(startDecade, 'y') && this._options.minDate.year() <= endDecadeYear; maxDateDecade = this._options.maxDate && this._options.maxDate.isAfter(startDecade, 'y') && this._options.maxDate.year() <= endDecadeYear; html += '<span data-action="selectDecade" class="decade' + (this._getLastPickedDate().isAfter(startDecade) && this._getLastPickedDate().year() <= endDecadeYear ? ' active' : '') + (!this._isValid(startDecade, 'y') && !minDateDecade && !maxDateDecade ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; startDecade.add(10, 'y'); } html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; decadesView.find('td').html(html); }; TempusDominusBootstrap4.prototype._fillDate = function _fillDate() { var daysView = this.widget.find('.datepicker-days'), daysViewHeader = daysView.find('th'), html = []; var currentDate = void 0, row = void 0, clsName = void 0, i = void 0; if (!this._hasDate()) { return; } daysViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevMonth); daysViewHeader.eq(1).attr('title', this._options.tooltips.selectMonth); daysViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextMonth); daysView.find('.disabled').removeClass('disabled'); daysViewHeader.eq(1).text(this._viewDate.format(this._options.dayViewHeaderFormat)); if (!this._isValid(this._viewDate.clone().subtract(1, 'M'), 'M')) { daysViewHeader.eq(0).addClass('disabled'); } if (!this._isValid(this._viewDate.clone().add(1, 'M'), 'M')) { daysViewHeader.eq(2).addClass('disabled'); } currentDate = this._viewDate.clone().startOf('M').startOf('w').startOf('d'); for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) if (currentDate.weekday() === 0) { row = $('<tr>'); if (this._options.calendarWeeks) { row.append('<td class="cw">' + currentDate.week() + '</td>'); } html.push(row); } clsName = ''; if (currentDate.isBefore(this._viewDate, 'M')) { clsName += ' old'; } if (currentDate.isAfter(this._viewDate, 'M')) { clsName += ' new'; } if (this._options.allowMultidate) { var index = this._datesFormatted.indexOf(currentDate.format('YYYY-MM-DD')); if (index !== -1) { if (currentDate.isSame(this._datesFormatted[index], 'd') && !this.unset) { clsName += ' active'; } } } else { if (currentDate.isSame(this._getLastPickedDate(), 'd') && !this.unset) { clsName += ' active'; } } if (!this._isValid(currentDate, 'd')) { clsName += ' disabled'; } if (currentDate.isSame(this.getMoment(), 'd')) { clsName += ' today'; } if (currentDate.day() === 0 || currentDate.day() === 6) { clsName += ' weekend'; } row.append('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="day' + clsName + '">' + currentDate.date() + '</td>'); currentDate.add(1, 'd'); } daysView.find('tbody').empty().append(html); this._updateMonths(); this._updateYears(); this._updateDecades(); }; TempusDominusBootstrap4.prototype._fillHours = function _fillHours() { var table = this.widget.find('.timepicker-hours table'), currentHour = this._viewDate.clone().startOf('d'), html = []; var row = $('<tr>'); if (this._viewDate.hour() > 11 && !this.use24Hours) { currentHour.hour(12); } while (currentHour.isSame(this._viewDate, 'd') && (this.use24Hours || this._viewDate.hour() < 12 && currentHour.hour() < 12 || this._viewDate.hour() > 11)) { if (currentHour.hour() % 4 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectHour" class="hour' + (!this._isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(this.use24Hours ? 'HH' : 'hh') + '</td>'); currentHour.add(1, 'h'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillMinutes = function _fillMinutes() { var table = this.widget.find('.timepicker-minutes table'), currentMinute = this._viewDate.clone().startOf('h'), html = [], step = this._options.stepping === 1 ? 5 : this._options.stepping; var row = $('<tr>'); while (this._viewDate.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectMinute" class="minute' + (!this._isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'); currentMinute.add(step, 'm'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillSeconds = function _fillSeconds() { var table = this.widget.find('.timepicker-seconds table'), currentSecond = this._viewDate.clone().startOf('m'), html = []; var row = $('<tr>'); while (this._viewDate.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectSecond" class="second' + (!this._isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'); currentSecond.add(5, 's'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillTime = function _fillTime() { var toggle = void 0, newDate = void 0; var timeComponents = this.widget.find('.timepicker span[data-time-component]'); if (!this.use24Hours) { toggle = this.widget.find('.timepicker [data-action=togglePeriod]'); newDate = this._getLastPickedDate().clone().add(this._getLastPickedDate().hours() >= 12 ? -12 : 12, 'h'); toggle.text(this._getLastPickedDate().format('A')); if (this._isValid(newDate, 'h')) { toggle.removeClass('disabled'); } else { toggle.addClass('disabled'); } } timeComponents.filter('[data-time-component=hours]').text(this._getLastPickedDate().format('' + (this.use24Hours ? 'HH' : 'hh'))); timeComponents.filter('[data-time-component=minutes]').text(this._getLastPickedDate().format('mm')); timeComponents.filter('[data-time-component=seconds]').text(this._getLastPickedDate().format('ss')); this._fillHours(); this._fillMinutes(); this._fillSeconds(); }; TempusDominusBootstrap4.prototype._doAction = function _doAction(e, action) { var lastPicked = this._getLastPickedDate(); if ($(e.currentTarget).is('.disabled')) { return false; } action = action || $(e.currentTarget).data('action'); switch (action) { case 'next': { var navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.add(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, navFnc); this._fillDate(); this._viewUpdate(navFnc); break; } case 'previous': { var _navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.subtract(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, _navFnc); this._fillDate(); this._viewUpdate(_navFnc); break; } case 'pickerSwitch': this._showMode(1); break; case 'selectMonth': { var month = $(e.target).closest('tbody').find('span').index($(e.target)); this._viewDate.month(month); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()).month(this._viewDate.month()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('M'); break; } case 'selectYear': { var year = parseInt($(e.target).text(), 10) || 0; this._viewDate.year(year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDecade': { var _year = parseInt($(e.target).data('selection'), 10) || 0; this._viewDate.year(_year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDay': { var day = this._viewDate.clone(); if ($(e.target).is('.old')) { day.subtract(1, 'M'); } if ($(e.target).is('.new')) { day.add(1, 'M'); } this._setValue(day.date(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); if (!this._hasTime() && !this._options.keepOpen && !this._options.inline) { this.hide(); } break; } case 'incrementHours': { var newDate = lastPicked.clone().add(1, 'h'); if (this._isValid(newDate, 'h')) { this._setValue(newDate, this._getLastPickedDateIndex()); } break; } case 'incrementMinutes': { var _newDate = lastPicked.clone().add(this._options.stepping, 'm'); if (this._isValid(_newDate, 'm')) { this._setValue(_newDate, this._getLastPickedDateIndex()); } break; } case 'incrementSeconds': { var _newDate2 = lastPicked.clone().add(1, 's'); if (this._isValid(_newDate2, 's')) { this._setValue(_newDate2, this._getLastPickedDateIndex()); } break; } case 'decrementHours': { var _newDate3 = lastPicked.clone().subtract(1, 'h'); if (this._isValid(_newDate3, 'h')) { this._setValue(_newDate3, this._getLastPickedDateIndex()); } break; } case 'decrementMinutes': { var _newDate4 = lastPicked.clone().subtract(this._options.stepping, 'm'); if (this._isValid(_newDate4, 'm')) { this._setValue(_newDate4, this._getLastPickedDateIndex()); } break; } case 'decrementSeconds': { var _newDate5 = lastPicked.clone().subtract(1, 's'); if (this._isValid(_newDate5, 's')) { this._setValue(_newDate5, this._getLastPickedDateIndex()); } break; } case 'togglePeriod': { this._setValue(lastPicked.clone().add(lastPicked.hours() >= 12 ? -12 : 12, 'h'), this._getLastPickedDateIndex()); break; } case 'togglePicker': { var $this = $(e.target), $link = $this.closest('a'), $parent = $this.closest('ul'), expanded = $parent.find('.show'), closed = $parent.find('.collapse:not(.show)'), $span = $this.is('span') ? $this : $this.find('span'); var collapseData = void 0; if (expanded && expanded.length) { collapseData = expanded.data('collapse'); if (collapseData && collapseData.transitioning) { return true; } if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it expanded.collapse('hide'); closed.collapse('show'); } else { // otherwise just toggle in class on the two views expanded.removeClass('show'); closed.addClass('show'); } $span.toggleClass(this._options.icons.time + ' ' + this._options.icons.date); if ($span.hasClass(this._options.icons.date)) { $link.attr('title', this._options.tooltips.selectDate); } else { $link.attr('title', this._options.tooltips.selectTime); } } } break; case 'showPicker': this.widget.find('.timepicker > div:not(.timepicker-picker)').hide(); this.widget.find('.timepicker .timepicker-picker').show(); break; case 'showHours': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-hours').show(); break; case 'showMinutes': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-minutes').show(); break; case 'showSeconds': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-seconds').show(); break; case 'selectHour': { var hour = parseInt($(e.target).text(), 10); if (!this.use24Hours) { if (lastPicked.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } this._setValue(lastPicked.clone().hours(hour), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; } case 'selectMinute': this._setValue(lastPicked.clone().minutes(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; case 'selectSecond': this._setValue(lastPicked.clone().seconds(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; case 'clear': this.clear(); break; case 'today': { var todaysDate = this.getMoment(); if (this._isValid(todaysDate, 'd')) { this._setValue(todaysDate, this._getLastPickedDateIndex()); } break; } } return false; }; //public TempusDominusBootstrap4.prototype.hide = function hide() { var transitioning = false; if (!this.widget) { return; } // Ignore event if in the middle of a picker transition this.widget.find('.collapse').each(function () { var collapseData = $(this).data('collapse'); if (collapseData && collapseData.transitioning) { transitioning = true; return false; } return true; }); if (transitioning) { return; } if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this.widget.hide(); $(window).off('resize', this._place()); this.widget.off('click', '[data-action]'); this.widget.off('mousedown', false); this.widget.remove(); this.widget = false; this._notifyEvent({ type: DateTimePicker.Event.HIDE, date: this._getLastPickedDate().clone() }); if (this.input !== undefined) { this.input.blur(); } this._viewDate = this._getLastPickedDate().clone(); }; TempusDominusBootstrap4.prototype.show = function show() { var currentMoment = void 0; var useCurrentGranularity = { 'year': function year(m) { return m.month(0).date(1).hours(0).seconds(0).minutes(0); }, 'month': function month(m) { return m.date(1).hours(0).seconds(0).minutes(0); }, 'day': function day(m) { return m.hours(0).seconds(0).minutes(0); }, 'hour': function hour(m) { return m.seconds(0).minutes(0); }, 'minute': function minute(m) { return m.seconds(0); } }; if (this.input !== undefined) { if (this.input.prop('disabled') || !this._options.ignoreReadonly && this.input.prop('readonly') || this.widget) { return; } if (this.input.val() !== undefined && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = useCurrentGranularity[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = useCurrentGranularity[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } this.widget = this._getTemplate(); this._fillDow(); this._fillMonths(); this.widget.find('.timepicker-hours').hide(); this.widget.find('.timepicker-minutes').hide(); this.widget.find('.timepicker-seconds').hide(); this._update(); this._showMode(); $(window).on('resize', { picker: this }, this._place); this.widget.on('click', '[data-action]', $.proxy(this._doAction, this)); // this handles clicks on the widget this.widget.on('mousedown', false); if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this._place(); this.widget.show(); if (this.input !== undefined && this._options.focusOnShow && !this.input.is(':focus')) { this.input.focus(); } this._notifyEvent({ type: DateTimePicker.Event.SHOW }); }; TempusDominusBootstrap4.prototype.destroy = function destroy() { this.hide(); //todo doc off? this._element.removeData(DateTimePicker.DATA_KEY); this._element.removeData('date'); }; TempusDominusBootstrap4.prototype.disable = function disable() { this.hide(); if (this.component && this.component.hasClass('btn')) { this.component.addClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', true); //todo disable this/comp if input is null } }; TempusDominusBootstrap4.prototype.enable = function enable() { if (this.component && this.component.hasClass('btn')) { this.component.removeClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', false); //todo enable comp/this if input is null } }; TempusDominusBootstrap4.prototype.toolbarPlacement = function toolbarPlacement(_toolbarPlacement) { if (arguments.length === 0) { return this._options.toolbarPlacement; } if (typeof _toolbarPlacement !== 'string') { throw new TypeError('toolbarPlacement() expects a string parameter'); } if (toolbarPlacements.indexOf(_toolbarPlacement) === -1) { throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); } this._options.toolbarPlacement = _toolbarPlacement; if (this.widget) { this.hide(); this.show(); } }; TempusDominusBootstrap4.prototype.widgetPositioning = function widgetPositioning(_widgetPositioning) { if (arguments.length === 0) { return $.extend({}, this._options.widgetPositioning); } if ({}.toString.call(_widgetPositioning) !== '[object Object]') { throw new TypeError('widgetPositioning() expects an object variable'); } if (_widgetPositioning.horizontal) { if (typeof _widgetPositioning.horizontal !== 'string') { throw new TypeError('widgetPositioning() horizontal variable must be a string'); } _widgetPositioning.horizontal = _widgetPositioning.horizontal.toLowerCase(); if (horizontalModes.indexOf(_widgetPositioning.horizontal) === -1) { throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); } this._options.widgetPositioning.horizontal = _widgetPositioning.horizontal; } if (_widgetPositioning.vertical) { if (typeof _widgetPositioning.vertical !== 'string') { throw new TypeError('widgetPositioning() vertical variable must be a string'); } _widgetPositioning.vertical = _widgetPositioning.vertical.toLowerCase(); if (verticalModes.indexOf(_widgetPositioning.vertical) === -1) { throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); } this._options.widgetPositioning.vertical = _widgetPositioning.vertical; } this._update(); }; TempusDominusBootstrap4.prototype.widgetParent = function widgetParent(_widgetParent) { if (arguments.length === 0) { return this._options.widgetParent; } if (typeof _widgetParent === 'string') { _widgetParent = $(_widgetParent); } if (_widgetParent !== null && typeof _widgetParent !== 'string' && !(_widgetParent instanceof $)) { throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); } this._options.widgetParent = _widgetParent; if (this.widget) { this.hide(); this.show(); } }; //static TempusDominusBootstrap4._jQueryHandleThis = function _jQueryHandleThis(me, option, argument) { var data = $(me).data(DateTimePicker.DATA_KEY); if ((typeof option === 'undefined' ? 'undefined' : _typeof(option)) === 'object') { $.extend({}, DateTimePicker.Default, option); } if (!data) { data = new TempusDominusBootstrap4($(me), option); $(me).data(DateTimePicker.DATA_KEY, data); } if (typeof option === 'string') { if (data[option] === undefined) { throw new Error('No method named "' + option + '"'); } if (argument === undefined) { return data[option](); } else { return data[option](argument); } } }; TempusDominusBootstrap4._jQueryInterface = function _jQueryInterface(option, argument) { if (this.length === 1) { return TempusDominusBootstrap4._jQueryHandleThis(this[0], option, argument); } return this.each(function () { TempusDominusBootstrap4._jQueryHandleThis(this, option, argument); }); }; return TempusDominusBootstrap4; }(DateTimePicker); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $(document).on(DateTimePicker.Event.CLICK_DATA_API, DateTimePicker.Selector.DATA_TOGGLE, function () { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, 'toggle'); }).on(DateTimePicker.Event.CHANGE, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_change', event); }).on(DateTimePicker.Event.BLUR, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (config._options.debug || window.debug) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, 'hide', event); }).on(DateTimePicker.Event.KEYDOWN, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_keydown', event); }).on(DateTimePicker.Event.KEYUP, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_keyup', event); }).on(DateTimePicker.Event.FOCUS, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (!config._options.allowInputToggle) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, config, event); }); $.fn[DateTimePicker.NAME] = TempusDominusBootstrap4._jQueryInterface; $.fn[DateTimePicker.NAME].Constructor = TempusDominusBootstrap4; $.fn[DateTimePicker.NAME].noConflict = function () { $.fn[DateTimePicker.NAME] = JQUERY_NO_CONFLICT; return TempusDominusBootstrap4._jQueryInterface; }; return TempusDominusBootstrap4; }(jQuery); }();
angular.module('ordercloud-address', []) .directive('ordercloudAddressForm', AddressFormDirective) .directive('ordercloudAddressInfo', AddressInfoDirective) .filter('address', AddressFilter) ; function AddressFormDirective(OCGeography) { return { restrict: 'E', scope: { address: '=', isbilling: '=' }, templateUrl: 'common/address/templates/address.form.tpl.html', link: function(scope) { scope.countries = OCGeography.Countries; scope.states = OCGeography.States; } }; } function AddressInfoDirective() { return { restrict: 'E', scope: { addressid: '@' }, templateUrl: 'common/address/templates/address.info.tpl.html', controller: 'AddressInfoCtrl', controllerAs: 'addressInfo' }; } function AddressFilter() { return function(address, option) { if (!address) return null; if (option === 'full') { var result = []; if (address.AddressName) { result.push(address.AddressName); } result.push((address.FirstName ? address.FirstName + ' ' : '') + address.LastName); result.push(address.Street1); if (address.Street2) { result.push(address.Street2); } result.push(address.City + ', ' + address.State + ' ' + address.Zip); return result.join('\n'); } else { return address.Street1 + (address.Street2 ? ', ' + address.Street2 : ''); } } }
// Approach: // // 1. Get the minimatch set // 2. For each pattern in the set, PROCESS(pattern, false) // 3. Store matches per-set, then uniq them // // PROCESS(pattern, inGlobStar) // Get the first [n] items from pattern that are all strings // Join these together. This is PREFIX. // If there is no more remaining, then stat(PREFIX) and // add to matches if it succeeds. END. // // If inGlobStar and PREFIX is symlink and points to dir // set ENTRIES = [] // else readdir(PREFIX) as ENTRIES // If fail, END // // with ENTRIES // If pattern[n] is GLOBSTAR // // handle the case where the globstar match is empty // // by pruning it out, and testing the resulting pattern // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) // // handle other cases. // for ENTRY in ENTRIES (not dotfiles) // // attach globstar + tail onto the entry // // Mark that this entry is a globstar match // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) // // else // not globstar // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) // Test ENTRY against pattern[n] // If fails, continue // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) // // Caveat: // Cache all stats and readdirs results to minimize syscall. Since all // we ever care about is existence and directory-ness, we can just keep // `true` for files, and [children,...] for directories, or `false` for // things that don't exist. module.exports = glob var rp = require('fs.realpath') var minimatch = require('minimatch') var Minimatch = minimatch.Minimatch var inherits = require('inherits') var EE = require('events').EventEmitter var path = require('path') var assert = require('assert') var isAbsolute = require('path-is-absolute') var globSync = require('./sync.js') var common = require('./common.js') var setopts = common.setopts var ownProp = common.ownProp var inflight = require('inflight') var util = require('util') var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored var once = require('once') function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} if (!options) options = {} if (options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return globSync(pattern, options) } return new Glob(pattern, options, cb) } glob.sync = globSync var GlobSync = glob.GlobSync = globSync.GlobSync // old api surface glob.glob = glob function extend (origin, add) { if (add === null || typeof add !== 'object') { return origin } var keys = Object.keys(add) var i = keys.length while (i--) { origin[keys[i]] = add[keys[i]] } return origin } glob.hasMagic = function (pattern, options_) { var options = extend({}, options_) options.noprocess = true var g = new Glob(pattern, options) var set = g.minimatch.set if (!pattern) return false if (set.length > 1) return true for (var j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') return true } return false } glob.Glob = Glob inherits(Glob, EE) function Glob (pattern, options, cb) { if (typeof options === 'function') { cb = options options = null } if (options && options.sync) { if (cb) throw new TypeError('callback provided to sync glob') return new GlobSync(pattern, options) } if (!(this instanceof Glob)) return new Glob(pattern, options, cb) setopts(this, pattern, options) this._didRealPath = false // process each pattern in the minimatch set var n = this.minimatch.set.length // The matches are stored as {<filename>: true,...} so that // duplicates are automagically pruned. // Later, we do an Object.keys() on these. // Keep them as a list so we can fill in when nonull is set. this.matches = new Array(n) if (typeof cb === 'function') { cb = once(cb) this.on('error', cb) this.on('end', function (matches) { cb(null, matches) }) } var self = this this._processing = 0 this._emitQueue = [] this._processQueue = [] this.paused = false if (this.noprocess) return this if (n === 0) return done() var sync = true for (var i = 0; i < n; i ++) { this._process(this.minimatch.set[i], i, false, done) } sync = false function done () { --self._processing if (self._processing <= 0) { if (sync) { process.nextTick(function () { self._finish() }) } else { self._finish() } } } } Glob.prototype._finish = function () { assert(this instanceof Glob) if (this.aborted) return if (this.realpath && !this._didRealpath) return this._realpath() common.finish(this) this.emit('end', this.found) } Glob.prototype._realpath = function () { if (this._didRealpath) return this._didRealpath = true var n = this.matches.length if (n === 0) return this._finish() var self = this for (var i = 0; i < this.matches.length; i++) this._realpathSet(i, next) function next () { if (--n === 0) self._finish() } } Glob.prototype._realpathSet = function (index, cb) { var matchset = this.matches[index] if (!matchset) return cb() var found = Object.keys(matchset) var self = this var n = found.length if (n === 0) return cb() var set = this.matches[index] = Object.create(null) found.forEach(function (p, i) { // If there's a problem with the stat, then it means that // one or more of the links in the realpath couldn't be // resolved. just return the abs value in that case. p = self._makeAbs(p) rp.realpath(p, self.realpathCache, function (er, real) { if (!er) set[real] = true else if (er.syscall === 'stat') set[p] = true else self.emit('error', er) // srsly wtf right here if (--n === 0) { self.matches[index] = set cb() } }) }) } Glob.prototype._mark = function (p) { return common.mark(this, p) } Glob.prototype._makeAbs = function (f) { return common.makeAbs(this, f) } Glob.prototype.abort = function () { this.aborted = true this.emit('abort') } Glob.prototype.pause = function () { if (!this.paused) { this.paused = true this.emit('pause') } } Glob.prototype.resume = function () { if (this.paused) { this.emit('resume') this.paused = false if (this._emitQueue.length) { var eq = this._emitQueue.slice(0) this._emitQueue.length = 0 for (var i = 0; i < eq.length; i ++) { var e = eq[i] this._emitMatch(e[0], e[1]) } } if (this._processQueue.length) { var pq = this._processQueue.slice(0) this._processQueue.length = 0 for (var i = 0; i < pq.length; i ++) { var p = pq[i] this._processing-- this._process(p[0], p[1], p[2], p[3]) } } } } Glob.prototype._process = function (pattern, index, inGlobStar, cb) { assert(this instanceof Glob) assert(typeof cb === 'function') if (this.aborted) return this._processing++ if (this.paused) { this._processQueue.push([pattern, index, inGlobStar, cb]) return } //console.error('PROCESS %d', this._processing, pattern) // Get the first [n] parts of pattern that are all strings. var n = 0 while (typeof pattern[n] === 'string') { n ++ } // now n is the index of the first one that is *not* a string. // see if there's anything else var prefix switch (n) { // if not, then this is rather simple case pattern.length: this._processSimple(pattern.join('/'), index, cb) return case 0: // pattern *starts* with some non-trivial item. // going to readdir(cwd), but not include the prefix in matches. prefix = null break default: // pattern has some string bits in the front. // whatever it starts with, whether that's 'absolute' like /foo/bar, // or 'relative' like '../baz' prefix = pattern.slice(0, n).join('/') break } var remain = pattern.slice(n) // get the list of entries. var read if (prefix === null) read = '.' else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix } else read = prefix var abs = this._makeAbs(read) //if ignored, skip _processing if (childrenIgnored(this, read)) return cb() var isGlobStar = remain[0] === minimatch.GLOBSTAR if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) } Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { // if the abs isn't a dir, then nothing can match! if (!entries) return cb() // It will only match dot entries if it starts with a dot, or if // dot is set. Stuff like @(.foo|.bar) isn't allowed. var pn = remain[0] var negate = !!this.minimatch.negate var rawGlob = pn._glob var dotOk = this.dot || rawGlob.charAt(0) === '.' var matchedEntries = [] for (var i = 0; i < entries.length; i++) { var e = entries[i] if (e.charAt(0) !== '.' || dotOk) { var m if (negate && !prefix) { m = !e.match(pn) } else { m = e.match(pn) } if (m) matchedEntries.push(e) } } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) var len = matchedEntries.length // If there are no matched entries, then nothing matches. if (len === 0) return cb() // if this is the last remaining pattern bit, then no need for // an additional stat *unless* the user has specified mark or // stat explicitly. We know they exist, since readdir returned // them. if (remain.length === 1 && !this.mark && !this.stat) { if (!this.matches[index]) this.matches[index] = Object.create(null) for (var i = 0; i < len; i ++) { var e = matchedEntries[i] if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } if (e.charAt(0) === '/' && !this.nomount) { e = path.join(this.root, e) } this._emitMatch(index, e) } // This was the last one, and no stats were needed return cb() } // now test all matched entries as stand-ins for that part // of the pattern. remain.shift() for (var i = 0; i < len; i ++) { var e = matchedEntries[i] var newPattern if (prefix) { if (prefix !== '/') e = prefix + '/' + e else e = prefix + e } this._process([e].concat(remain), index, inGlobStar, cb) } cb() } Glob.prototype._emitMatch = function (index, e) { if (this.aborted) return if (isIgnored(this, e)) return if (this.paused) { this._emitQueue.push([index, e]) return } var abs = isAbsolute(e) ? e : this._makeAbs(e) if (this.mark) e = this._mark(e) if (this.absolute) e = abs if (this.matches[index][e]) return if (this.nodir) { var c = this.cache[abs] if (c === 'DIR' || Array.isArray(c)) return } this.matches[index][e] = true var st = this.statCache[abs] if (st) this.emit('stat', e, st) this.emit('match', e) } Glob.prototype._readdirInGlobStar = function (abs, cb) { if (this.aborted) return // follow all symlinked directories forever // just proceed as if this is a non-globstar situation if (this.follow) return this._readdir(abs, false, cb) var lstatkey = 'lstat\0' + abs var self = this var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') return cb() var isSym = lstat && lstat.isSymbolicLink() self.symlinks[abs] = isSym // If it's not a symlink or a dir, then it's definitely a regular file. // don't bother doing a readdir in that case. if (!isSym && lstat && !lstat.isDirectory()) { self.cache[abs] = 'FILE' cb() } else self._readdir(abs, false, cb) } } Glob.prototype._readdir = function (abs, inGlobStar, cb) { if (this.aborted) return cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) if (!cb) return //console.error('RD %j %j', +inGlobStar, abs) if (inGlobStar && !ownProp(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb) if (ownProp(this.cache, abs)) { var c = this.cache[abs] if (!c || c === 'FILE') return cb() if (Array.isArray(c)) return cb(null, c) } var self = this self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { return function (er, entries) { if (er) self._readdirError(abs, er, cb) else self._readdirEntries(abs, entries, cb) } } Glob.prototype._readdirEntries = function (abs, entries, cb) { if (this.aborted) return // if we haven't asked to stat everything, then just // assume that everything in there exists, so we can avoid // having to stat it a second time. if (!this.mark && !this.stat) { for (var i = 0; i < entries.length; i ++) { var e = entries[i] if (abs === '/') e = abs + e else e = abs + '/' + e this.cache[e] = true } } this.cache[abs] = entries return cb(null, entries) } Glob.prototype._readdirError = function (f, er, cb) { if (this.aborted) return // handle errors, and cache the information switch (er.code) { case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 case 'ENOTDIR': // totally normal. means it *does* exist. var abs = this._makeAbs(f) this.cache[abs] = 'FILE' if (abs === this.cwdAbs) { var error = new Error(er.code + ' invalid cwd ' + this.cwd) error.path = this.cwd error.code = er.code this.emit('error', error) this.abort() } break case 'ENOENT': // not terribly unusual case 'ELOOP': case 'ENAMETOOLONG': case 'UNKNOWN': this.cache[this._makeAbs(f)] = false break default: // some unusual error. Treat as failure. this.cache[this._makeAbs(f)] = false if (this.strict) { this.emit('error', er) // If the error is handled, then we abort // if not, we threw out of here this.abort() } if (!this.silent) console.error('glob error', er) break } return cb() } Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { var self = this this._readdir(abs, inGlobStar, function (er, entries) { self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) }) } Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { //console.error('pgs2', prefix, remain[0], entries) // no entries means not a dir, so it can never have matches // foo.txt/** doesn't match foo.txt if (!entries) return cb() // test without the globstar, and with every child both below // and replacing the globstar. var remainWithoutGlobStar = remain.slice(1) var gspref = prefix ? [ prefix ] : [] var noGlobStar = gspref.concat(remainWithoutGlobStar) // the noGlobStar pattern exits the inGlobStar state this._process(noGlobStar, index, false, cb) var isSym = this.symlinks[abs] var len = entries.length // If it's a symlink, and we're in a globstar, then stop if (isSym && inGlobStar) return cb() for (var i = 0; i < len; i++) { var e = entries[i] if (e.charAt(0) === '.' && !this.dot) continue // these two cases enter the inGlobStar state var instead = gspref.concat(entries[i], remainWithoutGlobStar) this._process(instead, index, true, cb) var below = gspref.concat(entries[i], remain) this._process(below, index, true, cb) } cb() } Glob.prototype._processSimple = function (prefix, index, cb) { // XXX review this. Shouldn't it be doing the mounting etc // before doing stat? kinda weird? var self = this this._stat(prefix, function (er, exists) { self._processSimple2(prefix, index, er, exists, cb) }) } Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { //console.error('ps2', prefix, exists) if (!this.matches[index]) this.matches[index] = Object.create(null) // If it doesn't exist, then just mark the lack of results if (!exists) return cb() if (prefix && isAbsolute(prefix) && !this.nomount) { var trail = /[\/\\]$/.test(prefix) if (prefix.charAt(0) === '/') { prefix = path.join(this.root, prefix) } else { prefix = path.resolve(this.root, prefix) if (trail) prefix += '/' } } if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/') // Mark this as a match this._emitMatch(index, prefix) cb() } // Returns either 'DIR', 'FILE', or false Glob.prototype._stat = function (f, cb) { var abs = this._makeAbs(f) var needDir = f.slice(-1) === '/' if (f.length > this.maxLength) return cb() if (!this.stat && ownProp(this.cache, abs)) { var c = this.cache[abs] if (Array.isArray(c)) c = 'DIR' // It exists, but maybe not how we need it if (!needDir || c === 'DIR') return cb(null, c) if (needDir && c === 'FILE') return cb() // otherwise we have to stat, because maybe c=true // if we know it exists, but not what it is. } var exists var stat = this.statCache[abs] if (stat !== undefined) { if (stat === false) return cb(null, stat) else { var type = stat.isDirectory() ? 'DIR' : 'FILE' if (needDir && type === 'FILE') return cb() else return cb(null, type, stat) } } var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else self._stat2(f, abs, er, stat, cb) }) } else { self._stat2(f, abs, er, lstat, cb) } } } Glob.prototype._stat2 = function (f, abs, er, stat, cb) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false return cb() } var needDir = f.slice(-1) === '/' this.statCache[abs] = stat if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat) var c = true if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE' this.cache[abs] = this.cache[abs] || c if (needDir && c === 'FILE') return cb() return cb(null, c, stat) }
import AuthenticatedRoute from 'ghost/routes/authenticated'; import CurrentUserSettings from 'ghost/mixins/current-user-settings'; import styleBody from 'ghost/mixins/style-body'; var AppsRoute = AuthenticatedRoute.extend(styleBody, CurrentUserSettings, { titleToken: 'Apps', classNames: ['settings-view-apps'], beforeModel: function () { if (!this.get('config.apps')) { return this.transitionTo('settings.general'); } return this.get('session.user') .then(this.transitionAuthor()) .then(this.transitionEditor()); }, model: function () { return this.store.find('app'); } }); export default AppsRoute;
import Ember from 'ember-metal'; // Ember as namespace import { A as emberA, typeOf, String as StringUtils, Namespace, Object as EmberObject } from 'ember-runtime'; /** @module ember @submodule ember-extension-support */ /** The `ContainerDebugAdapter` helps the container and resolver interface with tools that debug Ember such as the [Ember Extension](https://github.com/tildeio/ember-extension) for Chrome and Firefox. This class can be extended by a custom resolver implementer to override some of the methods with library-specific code. The methods likely to be overridden are: * `canCatalogEntriesByType` * `catalogEntriesByType` The adapter will need to be registered in the application's container as `container-debug-adapter:main`. Example: ```javascript Application.initializer({ name: "containerDebugAdapter", initialize(application) { application.register('container-debug-adapter:main', require('app/container-debug-adapter')); } }); ``` @class ContainerDebugAdapter @namespace Ember @extends Ember.Object @since 1.5.0 @public */ export default EmberObject.extend({ /** The resolver instance of the application being debugged. This property will be injected on creation. @property resolver @default null @public */ resolver: null, /** Returns true if it is possible to catalog a list of available classes in the resolver for a given type. @method canCatalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {boolean} whether a list is available for this type. @public */ canCatalogEntriesByType(type) { if (type === 'model' || type === 'template') { return false; } return true; }, /** Returns the available classes a given type. @method catalogEntriesByType @param {String} type The type. e.g. "model", "controller", "route". @return {Array} An array of strings. @public */ catalogEntriesByType(type) { let namespaces = emberA(Namespace.NAMESPACES); let types = emberA(); let typeSuffixRegex = new RegExp(`${StringUtils.classify(type)}$`); namespaces.forEach(namespace => { if (namespace !== Ember) { for (let key in namespace) { if (!namespace.hasOwnProperty(key)) { continue; } if (typeSuffixRegex.test(key)) { let klass = namespace[key]; if (typeOf(klass) === 'class') { types.push(StringUtils.dasherize(key.replace(typeSuffixRegex, ''))); } } } } }); return types; } });
(function ($) { 'use strict'; $.extend(true, $.trumbowyg, { langs: { // jshint camelcase:false en: { fontFamily: 'Font' }, es: { fontFamily: 'Fuente' }, da: { fontFamily: 'Skrifttype' }, fr: { fontFamily: 'Police' }, de: { fontFamily: 'Schriftart' }, nl: { fontFamily: 'Lettertype' }, tr: { fontFamily: 'Yazı Tipi' }, zh_tw: { fontFamily: '字體', }, pt_br: { fontFamily: 'Fonte', } } }); // jshint camelcase:true var defaultOptions = { fontList: [ {name: 'Arial', family: 'Arial, Helvetica, sans-serif'}, {name: 'Arial Black', family: '\'Arial Black\', Gadget, sans-serif'}, {name: 'Comic Sans', family: '\'Comic Sans MS\', Textile, cursive, sans-serif'}, {name: 'Courier New', family: '\'Courier New\', Courier, monospace'}, {name: 'Georgia', family: 'Georgia, serif'}, {name: 'Impact', family: 'Impact, Charcoal, sans-serif'}, {name: 'Lucida Console', family: '\'Lucida Console\', Monaco, monospace'}, {name: 'Lucida Sans', family: '\'Lucida Sans Uncide\', \'Lucida Grande\', sans-serif'}, {name: 'Palatino', family: '\'Palatino Linotype\', \'Book Antiqua\', Palatino, serif'}, {name: 'Tahoma', family: 'Tahoma, Geneva, sans-serif'}, {name: 'Times New Roman', family: '\'Times New Roman\', Times, serif'}, {name: 'Trebuchet', family: '\'Trebuchet MS\', Helvetica, sans-serif'}, {name: 'Verdana', family: 'Verdana, Geneva, sans-serif'} ] }; // Add dropdown with web safe fonts $.extend(true, $.trumbowyg, { plugins: { fontfamily: { init: function (trumbowyg) { trumbowyg.o.plugins.fontfamily = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.fontfamily || {} ); trumbowyg.addBtnDef('fontfamily', { dropdown: buildDropdown(trumbowyg), hasIcon: false, text: trumbowyg.lang.fontFamily }); } } } }); function buildDropdown(trumbowyg) { var dropdown = []; $.each(trumbowyg.o.plugins.fontfamily.fontList, function (index, font) { trumbowyg.addBtnDef('fontfamily_' + index, { title: '<span style="font-family: ' + font.family + ';">' + font.name + '</span>', hasIcon: false, fn: function () { trumbowyg.execCmd('fontName', font.family, true); } }); dropdown.push('fontfamily_' + index); }); return dropdown; } })(jQuery);
CKEDITOR.plugins.setLang("uicolor","ro",{title:"Interfața cu utilizatorul a Selectorului de culoare",options:"Opțiuni culoare",highlight:"Evidențiere",selected:"Culoare selectată",predefined:"Seturi de culoare predefinite",config:"Copiază această expresie în fișierul tău config.js"});
// ========================================== // RECESS // RULE: .js prefixes should not be styled // ========================================== // Copyright 2012 Twitter, Inc // Licensed under the Apache License v2.0 // http://www.apache.org/licenses/LICENSE-2.0 // ========================================== 'use strict' var util = require('../util') , RULE = { type: 'noJSPrefix' , exp: /^\.js\-/ , message: '.js prefixes should not be styled' } // validation method module.exports = function (def, data) { // default validation to true var isValid = true // return if no selector to validate if (!def.selectors) return isValid // loop over selectors def.selectors.forEach(function (selector) { // loop over selector entities selector.elements.forEach(function (element) { var extract // continue to next element if .js- prefix not styled if (!RULE.exp.test(element.value)) return // calculate line number for the extract extract = util.getLine(element.index - element.value.length, data) extract = util.padLine(extract) // highlight invalid styling of .js- prefix extract += element.value.replace(RULE.exp, '.js-'.magenta) // set invalid flag to false isValid = false // set error object on defintion token util.throwError(def, { type: RULE.type , message: RULE.message , extract: extract }) }) }) // return valid state return isValid }
module.exports.twitter = function twitter(username) { // Creates the canonical twitter URL without the '@' return 'https://twitter.com/' + username.replace(/^@/, ''); }; module.exports.facebook = function facebook(username) { // Handles a starting slash, this shouldn't happen, but just in case return 'https://www.facebook.com/' + username.replace(/^\//, ''); };
var utils = exports; var uglify = require('uglify-js'); utils.extend = function extend(target, source) { Object.keys(source).forEach(function (key) { target[key] = source[key]; }); }; utils.beautify = function beautify(code) { var ast = uglify.parser.parse(code); return uglify.uglify.gen_code(ast, { beautify: true }); }; utils.expressionify = function expressionify(code) { try { var ast = uglify.parser.parse('(function(){\n' + code + '\n})'); } catch(e) { console.error(e.message + ' on ' + (e.line - 1) + ':' + e.pos); console.error('in'); console.error(code); throw e; } ast[1] = ast[1][0][1][3]; function traverse(ast) { if (!Array.isArray(ast)) return ast; switch (ast[0]) { case 'toplevel': if (ast[1].length === 1 && ast[1][0][0] !== 'block') { return ast; } else { var children = ast[1][0][0] === 'block' ? ast[1][0][1] : ast[1]; return ['toplevel', [[ 'call', [ 'dot', [ 'function', null, [], children.map(function(child, i, children) { return (i == children.length - 1) ? traverse(child) : child; }) ], 'call' ], [ ['name', 'this'] ] ]]]; } case 'block': // Empty blocks can't be processed if (ast[1].length <= 0) return ast; var last = ast[1][ast[1].length - 1]; return [ ast[0], ast[1].slice(0, -1).concat([traverse(last)]) ]; case 'while': case 'for': case 'switch': return ast; case 'if': return [ 'if', ast[1], traverse(ast[2]), traverse(ast[3]) ]; case 'stat': return [ 'stat', traverse(ast[1]) ]; default: if (ast[0] === 'return') return ast; return [ 'return', ast ] } return ast; } return uglify.uglify.gen_code(traverse(ast)).replace(/;$/, ''); }; utils.localify = function localify(code, id) { var ast = uglify.parser.parse(code); if (ast[1].length !== 1 || ast[1][0][0] !== 'stat') { throw new TypeError('Incorrect code for local: ' + code); } var vars = [], set = [], unset = []; function traverse(node) { if (node[0] === 'assign') { if (node[1] !== true) { throw new TypeError('Incorrect assignment in local'); } if (node[2][0] === 'dot' || node[2][0] === 'sub') { var host = ['name', '$l' + id++]; vars.push(host[1]); set.push(['assign', true, host, node[2][1]]); node[2][1] = host; if (node[2][0] === 'sub') { var property = ['name', '$l' + id++]; vars.push(property[1]); set.push(['assign', true, property, node[2][2]]); node[2][2] = property; } } var target = ['name', '$l' + id++]; vars.push(target[1]); set.push(['assign', true, target, node[2]]); set.push(['assign', true, node[2], node[3]]); unset.push(['assign', true, node[2], target]); } else if (node[0] === 'seq') { traverse(node[1]); traverse(node[2]); } else { throw new TypeError( 'Incorrect code for local (' + node[0] + '): ' + code ); } } traverse(ast[1][0][1]); function generate(seqs) { return uglify.uglify.gen_code(seqs.reduce(function (current, acc) { return ['seq', current, acc]; })); } return { vars: vars, before: generate(set.concat([['name', 'true']])), afterSuccess: generate(unset.concat([['name', 'true']])), afterFail: generate(unset.concat([['name', 'false']])) }; }; utils.merge = function merge(a, b) { Object.keys(b).forEach(function(key) { a[key] = b[key]; }); };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Plugin to hide series in flot graphs. * * To activate, set legend.hideable to true in the flot options object. * To hide one or more series by default, set legend.hidden to an array of * label strings. * * At the moment, this only works with line and point graphs. * * Example: * * var plotdata = [ * { * data: [[1, 1], [2, 1], [3, 3], [4, 2], [5, 5]], * label: "graph 1" * }, * { * data: [[1, 0], [2, 1], [3, 0], [4, 4], [5, 3]], * label: "graph 2" * } * ]; * * plot = $.plot($("#placeholder"), plotdata, { * series: { * points: { show: true }, * lines: { show: true } * }, * legend: { * hideable: true, * hidden: ["graph 1", "graph 2"] * } * }); * */ (function ($) { var options = { }; var drawnOnce = false; function init(plot) { function findPlotSeries(label) { var plotdata = plot.getData(); for (var i = 0; i < plotdata.length; i++) { if (plotdata[i].label == label) { return plotdata[i]; } } return null; } function plotLabelClicked(label, mouseOut) { var series = findPlotSeries(label); if (!series) { return; } var switchedOff = false; if (typeof series.points.oldShow === "undefined") { series.points.oldShow = false; } if (typeof series.lines.oldShow === "undefined") { series.lines.oldShow = false; } if (series.points.show && !series.points.oldShow) { series.points.show = false; series.points.oldShow = true; switchedOff = true; } if (series.lines.show && !series.lines.oldShow) { series.lines.show = false; series.lines.oldShow = true; switchedOff = true; } if (switchedOff) { series.oldColor = series.color; series.color = "#fff"; } else { var switchedOn = false; if (!series.points.show && series.points.oldShow) { series.points.show = true; series.points.oldShow = false; switchedOn = true; } if (!series.lines.show && series.lines.oldShow) { series.lines.show = true; series.lines.oldShow = false; switchedOn = true; } if (switchedOn) { series.color = series.oldColor; } } // HACK: Reset the data, triggering recalculation of graph bounds plot.setData(plot.getData()); plot.setupGrid(); plot.draw(); } function plotLabelHandlers(plot, options) { $(".graphlabel").mouseenter(function() { $(this).css("cursor", "pointer"); }) .mouseleave(function() { $(this).css("cursor", "default"); }) .unbind("click").click(function() { plotLabelClicked($(this).parent().text()); }); if (!drawnOnce) { drawnOnce = true; if (options.legend.hidden) { for (var i = 0; i < options.legend.hidden.length; i++) { plotLabelClicked(options.legend.hidden[i], true); } } } } function checkOptions(plot, options) { if (!options.legend.hideable) { return; } options.legend.labelFormatter = function(label, series) { return '<span class="graphlabel">' + label + '</span>'; }; // Really just needed for initial draw; the mouse-enter/leave // functions will call plotLabelHandlers() directly, since they // only call setupGrid(). plot.hooks.draw.push(function (plot, ctx) { plotLabelHandlers(plot, options); }); } plot.hooks.processOptions.push(checkOptions); function hideDatapointsIfNecessary(plot, s, datapoints) { if (!plot.getOptions().legend.hideable) { return; } if (!s.points.show && !s.lines.show) { s.datapoints.format = [ null, null ]; } } plot.hooks.processDatapoints.push(hideDatapointsIfNecessary); } $.plot.plugins.push({ init: init, options: options, name: 'hiddenGraphs', version: '1.0' }); })(jQuery);