Last active
August 29, 2015 13:57
-
-
Save hemulin/9374443 to your computer and use it in GitHub Desktop.
description
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!function(){function n(n){return null!=n&&!isNaN(n)}function t(n){return n.length}function e(n){for(var t=1;n*t%1;)t*=10;return t}function r(n,t){try{for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}catch(r){n.prototype=t}}function u(){}function i(n){return aa+n in this}function o(n){return n=aa+n,n in this&&delete this[n]}function a(){var n=[];return this.forEach(function(t){n.push(t)}),n}function c(){var n=0;for(var t in this)t.charCodeAt(0)===ca&&++n;return n}function s(){for(var n in this)if(n.charCodeAt(0)===ca)return!1;return!0}function l(){}function f(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function h(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.substring(1);for(var e=0,r=sa.length;r>e;++e){var u=sa[e]+t;if(u in n)return u}}function g(){}function p(){}function v(n){function t(){for(var t,r=e,u=-1,i=r.length;++u<i;)(t=r[u].on)&&t.apply(this,arguments);return n}var e=[],r=new u;return t.on=function(t,u){var i,o=r.get(t);return arguments.length<2?o&&o.on:(o&&(o.on=null,e=e.slice(0,i=e.indexOf(o)).concat(e.slice(i+1)),r.remove(t)),u&&e.push(r.set(t,{on:u})),n)},t}function d(){Xo.event.preventDefault()}function m(){for(var n,t=Xo.event;n=t.sourceEvent;)t=n;return t}function y(n){for(var t=new p,e=0,r=arguments.length;++e<r;)t[arguments[e]]=v(t);return t.of=function(e,r){return function(u){try{var i=u.sourceEvent=Xo.event;u.target=n,Xo.event=u,t[u.type].apply(e,r)}finally{Xo.event=i}}},t}function x(n){return fa(n,da),n}function M(n){return"function"==typeof n?n:function(){return ha(n,this)}}function _(n){return"function"==typeof n?n:function(){return ga(n,this)}}function b(n,t){function e(){this.removeAttribute(n)}function r(){this.removeAttributeNS(n.space,n.local)}function u(){this.setAttribute(n,t)}function i(){this.setAttributeNS(n.space,n.local,t)}function o(){var e=t.apply(this,arguments);null==e?this.removeAttribute(n):this.setAttribute(n,e)}function a(){var e=t.apply(this,arguments);null==e?this.removeAttributeNS(n.space,n.local):this.setAttributeNS(n.space,n.local,e)}return n=Xo.ns.qualify(n),null==t?n.local?r:e:"function"==typeof t?n.local?a:o:n.local?i:u}function w(n){return n.trim().replace(/\s+/g," ")}function S(n){return new RegExp("(?:^|\\s+)"+Xo.requote(n)+"(?:\\s+|$)","g")}function k(n){return n.trim().split(/^|\s+/)}function E(n,t){function e(){for(var e=-1;++e<u;)n[e](this,t)}function r(){for(var e=-1,r=t.apply(this,arguments);++e<u;)n[e](this,r)}n=k(n).map(A);var u=n.length;return"function"==typeof t?r:e}function A(n){var t=S(n);return function(e,r){if(u=e.classList)return r?u.add(n):u.remove(n);var u=e.getAttribute("class")||"";r?(t.lastIndex=0,t.test(u)||e.setAttribute("class",w(u+" "+n))):e.setAttribute("class",w(u.replace(t," ")))}}function C(n,t,e){function r(){this.style.removeProperty(n)}function u(){this.style.setProperty(n,t,e)}function i(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(n):this.style.setProperty(n,r,e)}return null==t?r:"function"==typeof t?i:u}function N(n,t){function e(){delete this[n]}function r(){this[n]=t}function u(){var e=t.apply(this,arguments);null==e?delete this[n]:this[n]=e}return null==t?e:"function"==typeof t?u:r}function L(n){return"function"==typeof n?n:(n=Xo.ns.qualify(n)).local?function(){return this.ownerDocument.createElementNS(n.space,n.local)}:function(){return this.ownerDocument.createElementNS(this.namespaceURI,n)}}function z(n){return{__data__:n}}function q(n){return function(){return va(this,n)}}function T(n){return arguments.length||(n=Xo.ascending),function(t,e){return t&&e?n(t.__data__,e.__data__):!t-!e}}function R(n,t){for(var e=0,r=n.length;r>e;e++)for(var u,i=n[e],o=0,a=i.length;a>o;o++)(u=i[o])&&t(u,o,e);return n}function D(n){return fa(n,ya),n}function P(n){var t,e;return function(r,u,i){var o,a=n[i].update,c=a.length;for(i!=e&&(e=i,t=0),u>=t&&(t=u+1);!(o=a[t])&&++t<c;);return o}}function U(){var n=this.__transition__;n&&++n.active}function j(n,t,e){function r(){var t=this[o];t&&(this.removeEventListener(n,t,t.$),delete this[o])}function u(){var u=c(t,Bo(arguments));r.call(this),this.addEventListener(n,this[o]=u,u.$=e),u._=t}function i(){var t,e=new RegExp("^__on([^.]+)"+Xo.requote(n)+"$");for(var r in this)if(t=r.match(e)){var u=this[r];this.removeEventListener(t[1],u,u.$),delete this[r]}}var o="__on"+n,a=n.indexOf("."),c=H;a>0&&(n=n.substring(0,a));var s=Ma.get(n);return s&&(n=s,c=F),a?t?u:r:t?g:i}function H(n,t){return function(e){var r=Xo.event;Xo.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{Xo.event=r}}}function F(n,t){var e=H(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function O(){var n=".dragsuppress-"+ ++ba,t="click"+n,e=Xo.select(Go).on("touchmove"+n,d).on("dragstart"+n,d).on("selectstart"+n,d);if(_a){var r=Jo.style,u=r[_a];r[_a]="none"}return function(i){function o(){e.on(t,null)}e.on(n,null),_a&&(r[_a]=u),i&&(e.on(t,function(){d(),o()},!0),setTimeout(o,0))}}function Y(n,t){t.changedTouches&&(t=t.changedTouches[0]);var e=n.ownerSVGElement||n;if(e.createSVGPoint){var r=e.createSVGPoint();if(0>wa&&(Go.scrollX||Go.scrollY)){e=Xo.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var u=e[0][0].getScreenCTM();wa=!(u.f||u.e),e.remove()}return wa?(r.x=t.pageX,r.y=t.pageY):(r.x=t.clientX,r.y=t.clientY),r=r.matrixTransform(n.getScreenCTM().inverse()),[r.x,r.y]}var i=n.getBoundingClientRect();return[t.clientX-i.left-n.clientLeft,t.clientY-i.top-n.clientTop]}function I(n){return n>0?1:0>n?-1:0}function Z(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(t[1]-n[1])*(e[0]-n[0])}function V(n){return n>1?0:-1>n?Sa:Math.acos(n)}function X(n){return n>1?Ea:-1>n?-Ea:Math.asin(n)}function $(n){return((n=Math.exp(n))-1/n)/2}function B(n){return((n=Math.exp(n))+1/n)/2}function W(n){return((n=Math.exp(2*n))-1)/(n+1)}function J(n){return(n=Math.sin(n/2))*n}function G(){}function K(n,t,e){return new Q(n,t,e)}function Q(n,t,e){this.h=n,this.s=t,this.l=e}function nt(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?i+(o-i)*n/60:180>n?o:240>n?i+(o-i)*(240-n)/60:i}function u(n){return Math.round(255*r(n))}var i,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,i=2*e-o,gt(u(n+120),u(n),u(n-120))}function tt(n,t,e){return new et(n,t,e)}function et(n,t,e){this.h=n,this.c=t,this.l=e}function rt(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),ut(e,Math.cos(n*=Na)*t,Math.sin(n)*t)}function ut(n,t,e){return new it(n,t,e)}function it(n,t,e){this.l=n,this.a=t,this.b=e}function ot(n,t,e){var r=(n+16)/116,u=r+t/500,i=r-e/200;return u=ct(u)*Fa,r=ct(r)*Oa,i=ct(i)*Ya,gt(lt(3.2404542*u-1.5371385*r-.4985314*i),lt(-.969266*u+1.8760108*r+.041556*i),lt(.0556434*u-.2040259*r+1.0572252*i))}function at(n,t,e){return n>0?tt(Math.atan2(e,t)*La,Math.sqrt(t*t+e*e),n):tt(0/0,0/0,n)}function ct(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function st(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function lt(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function ft(n){return gt(n>>16,255&n>>8,255&n)}function ht(n){return ft(n)+""}function gt(n,t,e){return new pt(n,t,e)}function pt(n,t,e){this.r=n,this.g=t,this.b=e}function vt(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function dt(n,t,e){var r,u,i,o=0,a=0,c=0;if(r=/([a-z]+)\((.*)\)/i.exec(n))switch(u=r[2].split(","),r[1]){case"hsl":return e(parseFloat(u[0]),parseFloat(u[1])/100,parseFloat(u[2])/100);case"rgb":return t(Mt(u[0]),Mt(u[1]),Mt(u[2]))}return(i=Va.get(n))?t(i.r,i.g,i.b):(null!=n&&"#"===n.charAt(0)&&(4===n.length?(o=n.charAt(1),o+=o,a=n.charAt(2),a+=a,c=n.charAt(3),c+=c):7===n.length&&(o=n.substring(1,3),a=n.substring(3,5),c=n.substring(5,7)),o=parseInt(o,16),a=parseInt(a,16),c=parseInt(c,16)),t(o,a,c))}function mt(n,t,e){var r,u,i=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-i,c=(o+i)/2;return a?(u=.5>c?a/(o+i):a/(2-o-i),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=0/0,u=c>0&&1>c?0:r),K(r,u,c)}function yt(n,t,e){n=xt(n),t=xt(t),e=xt(e);var r=st((.4124564*n+.3575761*t+.1804375*e)/Fa),u=st((.2126729*n+.7151522*t+.072175*e)/Oa),i=st((.0193339*n+.119192*t+.9503041*e)/Ya);return ut(116*u-16,500*(r-u),200*(u-i))}function xt(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Mt(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function _t(n){return"function"==typeof n?n:function(){return n}}function bt(n){return n}function wt(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),St(t,e,n,r)}}function St(n,t,e,r){function u(){var n,t=c.status;if(!t&&c.responseText||t>=200&&300>t||304===t){try{n=e.call(i,c)}catch(r){return o.error.call(i,r),void 0}o.load.call(i,n)}else o.error.call(i,c)}var i={},o=Xo.dispatch("beforesend","progress","load","error"),a={},c=new XMLHttpRequest,s=null;return!Go.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(n)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=u:c.onreadystatechange=function(){c.readyState>3&&u()},c.onprogress=function(n){var t=Xo.event;Xo.event=n;try{o.progress.call(i,c)}finally{Xo.event=t}},i.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",i)},i.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",i):t},i.responseType=function(n){return arguments.length?(s=n,i):s},i.response=function(n){return e=n,i},["get","post"].forEach(function(n){i[n]=function(){return i.send.apply(i,[n].concat(Bo(arguments)))}}),i.send=function(e,r,u){if(2===arguments.length&&"function"==typeof r&&(u=r,r=null),c.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),c.setRequestHeader)for(var l in a)c.setRequestHeader(l,a[l]);return null!=t&&c.overrideMimeType&&c.overrideMimeType(t),null!=s&&(c.responseType=s),null!=u&&i.on("error",u).on("load",function(n){u(null,n)}),o.beforesend.call(i,c),c.send(null==r?null:r),i},i.abort=function(){return c.abort(),i},Xo.rebind(i,o,"on"),null==r?i:i.get(kt(r))}function kt(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function Et(){var n=At(),t=Ct()-n;t>24?(isFinite(t)&&(clearTimeout(Wa),Wa=setTimeout(Et,t)),Ba=0):(Ba=1,Ga(Et))}function At(){var n=Date.now();for(Ja=Xa;Ja;)n>=Ja.t&&(Ja.f=Ja.c(n-Ja.t)),Ja=Ja.n;return n}function Ct(){for(var n,t=Xa,e=1/0;t;)t.f?t=n?n.n=t.n:Xa=t.n:(t.t<e&&(e=t.t),t=(n=t).n);return $a=n,e}function Nt(n,t){return t-(n?Math.ceil(Math.log(n)/Math.LN10):1)}function Lt(n,t){var e=Math.pow(10,3*oa(8-t));return{scale:t>8?function(n){return n/e}:function(n){return n*e},symbol:n}}function zt(n){var t=n.decimal,e=n.thousands,r=n.grouping,u=n.currency,i=r?function(n){for(var t=n.length,u=[],i=0,o=r[0];t>0&&o>0;)u.push(n.substring(t-=o,t+o)),o=r[i=(i+1)%r.length];return u.reverse().join(e)}:bt;return function(n){var e=Qa.exec(n),r=e[1]||" ",o=e[2]||">",a=e[3]||"",c=e[4]||"",s=e[5],l=+e[6],f=e[7],h=e[8],g=e[9],p=1,v="",d="",m=!1;switch(h&&(h=+h.substring(1)),(s||"0"===r&&"="===o)&&(s=r="0",o="=",f&&(l-=Math.floor((l-1)/4))),g){case"n":f=!0,g="g";break;case"%":p=100,d="%",g="f";break;case"p":p=100,d="%",g="r";break;case"b":case"o":case"x":case"X":"#"===c&&(v="0"+g.toLowerCase());case"c":case"d":m=!0,h=0;break;case"s":p=-1,g="r"}"$"===c&&(v=u[0],d=u[1]),"r"!=g||h||(g="g"),null!=h&&("g"==g?h=Math.max(1,Math.min(21,h)):("e"==g||"f"==g)&&(h=Math.max(0,Math.min(20,h)))),g=nc.get(g)||qt;var y=s&&f;return function(n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a;if(0>p){var c=Xo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}}}function qt(n){return n+""}function Tt(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Rt(n,t,e){function r(t){var e=n(t),r=i(e,1);return r-t>t-e?e:r}function u(e){return t(e=n(new ec(e-1)),1),e}function i(n,e){return t(n=new ec(+n),e),n}function o(n,r,i){var o=u(n),a=[];if(i>1)for(;r>o;)e(o)%i||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{ec=Tt;var r=new Tt;return r._=n,o(r,t,e)}finally{ec=Date}}n.floor=n,n.round=r,n.ceil=u,n.offset=i,n.range=o;var c=n.utc=Dt(n);return c.floor=c,c.round=Dt(r),c.ceil=Dt(u),c.offset=Dt(i),c.range=a,n}function Dt(n){return function(t,e){try{ec=Tt;var r=new Tt;return r._=t,n(r,e)._}finally{ec=Date}}}function Pt(n){function t(n){function t(t){for(var e,u,i,o=[],a=-1,c=0;++a<r;)37===n.charCodeAt(a)&&(o.push(n.substring(c,a)),null!=(u=uc[e=n.charAt(++a)])&&(e=n.charAt(++a)),(i=C[e])&&(e=i(t,null==u?"e"===e?" ":"0":u)),o.push(e),c=a+1);return o.push(n.substring(c,a)),o.join("")}var r=n.length;return t.parse=function(t){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},u=e(r,n,t,0);if(u!=t.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var i=null!=r.Z&&ec!==Tt,o=new(i?Tt:ec);return"j"in r?o.setFullYear(r.y,0,r.j):"w"in r&&("W"in r||"U"in r)?(o.setFullYear(r.y,0,1),o.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(o.getDay()+5)%7:r.w+7*r.U-(o.getDay()+6)%7)):o.setFullYear(r.y,r.m,r.d),o.setHours(r.H+Math.floor(r.Z/100),r.M+r.Z%100,r.S,r.L),i?o._:o},t.toString=function(){return n},t}function e(n,t,e,r){for(var u,i,o,a=0,c=t.length,s=e.length;c>a;){if(r>=s)return-1;if(u=t.charCodeAt(a++),37===u){if(o=t.charAt(a++),i=N[o in uc?t.charAt(a++):o],!i||(r=i(n,e,r))<0)return-1}else if(u!=e.charCodeAt(r++))return-1}return r}function r(n,t,e){b.lastIndex=0;var r=b.exec(t.substring(e));return r?(n.w=w.get(r[0].toLowerCase()),e+r[0].length):-1}function u(n,t,e){M.lastIndex=0;var r=M.exec(t.substring(e));return r?(n.w=_.get(r[0].toLowerCase()),e+r[0].length):-1}function i(n,t,e){E.lastIndex=0;var r=E.exec(t.substring(e));return r?(n.m=A.get(r[0].toLowerCase()),e+r[0].length):-1}function o(n,t,e){S.lastIndex=0;var r=S.exec(t.substring(e));return r?(n.m=k.get(r[0].toLowerCase()),e+r[0].length):-1}function a(n,t,r){return e(n,C.c.toString(),t,r)}function c(n,t,r){return e(n,C.x.toString(),t,r)}function s(n,t,r){return e(n,C.X.toString(),t,r)}function l(n,t,e){var r=x.get(t.substring(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}var f=n.dateTime,h=n.date,g=n.time,p=n.periods,v=n.days,d=n.shortDays,m=n.months,y=n.shortMonths;t.utc=function(n){function e(n){try{ec=Tt;var t=new ec;return t._=n,r(t)}finally{ec=Date}}var r=t(n);return e.parse=function(n){try{ec=Tt;var t=r.parse(n);return t&&t._}finally{ec=Date}},e.toString=r.toString,e},t.multi=t.utc.multi=ee;var x=Xo.map(),M=jt(v),_=Ht(v),b=jt(d),w=Ht(d),S=jt(m),k=Ht(m),E=jt(y),A=Ht(y);p.forEach(function(n,t){x.set(n.toLowerCase(),t)});var C={a:function(n){return d[n.getDay()]},A:function(n){return v[n.getDay()]},b:function(n){return y[n.getMonth()]},B:function(n){return m[n.getMonth()]},c:t(f),d:function(n,t){return Ut(n.getDate(),t,2)},e:function(n,t){return Ut(n.getDate(),t,2)},H:function(n,t){return Ut(n.getHours(),t,2)},I:function(n,t){return Ut(n.getHours()%12||12,t,2)},j:function(n,t){return Ut(1+tc.dayOfYear(n),t,3)},L:function(n,t){return Ut(n.getMilliseconds(),t,3)},m:function(n,t){return Ut(n.getMonth()+1,t,2)},M:function(n,t){return Ut(n.getMinutes(),t,2)},p:function(n){return p[+(n.getHours()>=12)]},S:function(n,t){return Ut(n.getSeconds(),t,2)},U:function(n,t){return Ut(tc.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return Ut(tc.mondayOfYear(n),t,2)},x:t(h),X:t(g),y:function(n,t){return Ut(n.getFullYear()%100,t,2)},Y:function(n,t){return Ut(n.getFullYear()%1e4,t,4)},Z:ne,"%":function(){return"%"}},N={a:r,A:u,b:i,B:o,c:a,d:Bt,e:Bt,H:Jt,I:Jt,j:Wt,L:Qt,m:$t,M:Gt,p:l,S:Kt,U:Ot,w:Ft,W:Yt,x:c,X:s,y:Zt,Y:It,Z:Vt,"%":te};return t}function Ut(n,t,e){var r=0>n?"-":"",u=(r?-n:n)+"",i=u.length;return r+(e>i?new Array(e-i+1).join(t)+u:u)}function jt(n){return new RegExp("^(?:"+n.map(Xo.requote).join("|")+")","i")}function Ht(n){for(var t=new u,e=-1,r=n.length;++e<r;)t.set(n[e].toLowerCase(),e);return t}function Ft(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+1));return r?(n.w=+r[0],e+r[0].length):-1}function Ot(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e));return r?(n.U=+r[0],e+r[0].length):-1}function Yt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e));return r?(n.W=+r[0],e+r[0].length):-1}function It(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+4));return r?(n.y=+r[0],e+r[0].length):-1}function Zt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+2));return r?(n.y=Xt(+r[0]),e+r[0].length):-1}function Vt(n,t,e){return/^[+-]\d{4}$/.test(t=t.substring(e,e+5))?(n.Z=+t,e+5):-1}function Xt(n){return n+(n>68?1900:2e3)}function $t(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function Bt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function Wt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function Jt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function Gt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function Kt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function Qt(n,t,e){ic.lastIndex=0;var r=ic.exec(t.substring(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function ne(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=~~(oa(t)/60),u=oa(t)%60;return e+Ut(r,"0",2)+Ut(u,"0",2)}function te(n,t,e){oc.lastIndex=0;var r=oc.exec(t.substring(e,e+1));return r?e+r[0].length:-1}function ee(n){for(var t=n.length,e=-1;++e<t;)n[e][0]=this(n[e][0]);return function(t){for(var e=0,r=n[e];!r[1](t);)r=n[++e];return r[0](t)}}function re(){}function ue(n,t,e){var r=e.s=n+t,u=r-n,i=r-u;e.t=n-i+(t-u)}function ie(n,t){n&&lc.hasOwnProperty(n.type)&&lc[n.type](n,t)}function oe(n,t,e){var r,u=-1,i=n.length-e;for(t.lineStart();++u<i;)r=n[u],t.point(r[0],r[1],r[2]);t.lineEnd()}function ae(n,t){var e=-1,r=n.length;for(t.polygonStart();++e<r;)oe(n[e],t,1);t.polygonEnd()}function ce(){function n(n,t){n*=Na,t=t*Na/2+Sa/4;var e=n-r,o=e>=0?1:-1,a=o*e,c=Math.cos(t),s=Math.sin(t),l=i*s,f=u*c+l*Math.cos(a),h=l*o*Math.sin(a);hc.add(Math.atan2(h,f)),r=n,u=c,i=s}var t,e,r,u,i;gc.point=function(o,a){gc.point=n,r=(t=o)*Na,u=Math.cos(a=(e=a)*Na/2+Sa/4),i=Math.sin(a)},gc.lineEnd=function(){n(t,e)}}function se(n){var t=n[0],e=n[1],r=Math.cos(e);return[r*Math.cos(t),r*Math.sin(t),Math.sin(e)]}function le(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]}function fe(n,t){return[n[1]*t[2]-n[2]*t[1],n[2]*t[0]-n[0]*t[2],n[0]*t[1]-n[1]*t[0]]}function he(n,t){n[0]+=t[0],n[1]+=t[1],n[2]+=t[2]}function ge(n,t){return[n[0]*t,n[1]*t,n[2]*t]}function pe(n){var t=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);n[0]/=t,n[1]/=t,n[2]/=t}function ve(n){return[Math.atan2(n[1],n[0]),X(n[2])]}function de(n,t){return oa(n[0]-t[0])<Aa&&oa(n[1]-t[1])<Aa}function me(n,t){n*=Na;var e=Math.cos(t*=Na);ye(e*Math.cos(n),e*Math.sin(n),Math.sin(t))}function ye(n,t,e){++pc,dc+=(n-dc)/pc,mc+=(t-mc)/pc,yc+=(e-yc)/pc}function xe(){function n(n,u){n*=Na;var i=Math.cos(u*=Na),o=i*Math.cos(n),a=i*Math.sin(n),c=Math.sin(u),s=Math.atan2(Math.sqrt((s=e*c-r*a)*s+(s=r*o-t*c)*s+(s=t*a-e*o)*s),t*o+e*a+r*c);vc+=s,xc+=s*(t+(t=o)),Mc+=s*(e+(e=a)),_c+=s*(r+(r=c)),ye(t,e,r)}var t,e,r;kc.point=function(u,i){u*=Na;var o=Math.cos(i*=Na);t=o*Math.cos(u),e=o*Math.sin(u),r=Math.sin(i),kc.point=n,ye(t,e,r)}}function Me(){kc.point=me}function _e(){function n(n,t){n*=Na;var e=Math.cos(t*=Na),o=e*Math.cos(n),a=e*Math.sin(n),c=Math.sin(t),s=u*c-i*a,l=i*o-r*c,f=r*a-u*o,h=Math.sqrt(s*s+l*l+f*f),g=r*o+u*a+i*c,p=h&&-V(g)/h,v=Math.atan2(h,g);bc+=p*s,wc+=p*l,Sc+=p*f,vc+=v,xc+=v*(r+(r=o)),Mc+=v*(u+(u=a)),_c+=v*(i+(i=c)),ye(r,u,i)}var t,e,r,u,i;kc.point=function(o,a){t=o,e=a,kc.point=n,o*=Na;var c=Math.cos(a*=Na);r=c*Math.cos(o),u=c*Math.sin(o),i=Math.sin(a),ye(r,u,i)},kc.lineEnd=function(){n(t,e),kc.lineEnd=Me,kc.point=me}}function be(){return!0}function we(n,t,e,r,u){var i=[],o=[];if(n.forEach(function(n){if(!((t=n.length-1)<=0)){var t,e=n[0],r=n[t];if(de(e,r)){u.lineStart();for(var a=0;t>a;++a)u.point((e=n[a])[0],e[1]);return u.lineEnd(),void 0}var c=new ke(e,n,null,!0),s=new ke(e,null,c,!1);c.o=s,i.push(c),o.push(s),c=new ke(r,n,null,!1),s=new ke(r,null,c,!0),c.o=s,i.push(c),o.push(s)}}),o.sort(t),Se(i),Se(o),i.length){for(var a=0,c=e,s=o.length;s>a;++a)o[a].e=c=!c;for(var l,f,h=i[0];;){for(var g=h,p=!0;g.v;)if((g=g.n)===h)return;l=g.z,u.lineStart();do{if(g.v=g.o.v=!0,g.e){if(p)for(var a=0,s=l.length;s>a;++a)u.point((f=l[a])[0],f[1]);else r(g.x,g.n.x,1,u);g=g.n}else{if(p){l=g.p.z;for(var a=l.length-1;a>=0;--a)u.point((f=l[a])[0],f[1])}else r(g.x,g.p.x,-1,u);g=g.p}g=g.o,l=g.z,p=!p}while(!g.v);u.lineEnd()}}}function Se(n){if(t=n.length){for(var t,e,r=0,u=n[0];++r<t;)u.n=e=n[r],e.p=u,u=e;u.n=e=n[0],e.p=u}}function ke(n,t,e,r){this.x=n,this.z=t,this.o=e,this.e=r,this.v=!1,this.n=this.p=null}function Ee(n,t,e,r){return function(u,i){function o(t,e){var r=u(t,e);n(t=r[0],e=r[1])&&i.point(t,e)}function a(n,t){var e=u(n,t);d.point(e[0],e[1])}function c(){y.point=a,d.lineStart()}function s(){y.point=o,d.lineEnd()}function l(n,t){v.push([n,t]);var e=u(n,t);M.point(e[0],e[1])}function f(){M.lineStart(),v=[]}function h(){l(v[0][0],v[0][1]),M.lineEnd();var n,t=M.clean(),e=x.buffer(),r=e.length;if(v.pop(),p.push(v),v=null,r){if(1&t){n=e[0];var u,r=n.length-1,o=-1;for(i.lineStart();++o<r;)i.point((u=n[o])[0],u[1]);return i.lineEnd(),void 0}r>1&&2&t&&e.push(e.pop().concat(e.shift())),g.push(e.filter(Ae))}}var g,p,v,d=t(i),m=u.invert(r[0],r[1]),y={point:o,lineStart:c,lineEnd:s,polygonStart:function(){y.point=l,y.lineStart=f,y.lineEnd=h,g=[],p=[],i.polygonStart()},polygonEnd:function(){y.point=o,y.lineStart=c,y.lineEnd=s,g=Xo.merge(g);var n=Le(m,p);g.length?we(g,Ne,n,e,i):n&&(i.lineStart(),e(null,null,1,i),i.lineEnd()),i.polygonEnd(),g=p=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}},x=Ce(),M=t(x);return y}}function Ae(n){return n.length>1}function Ce(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:g,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Ne(n,t){return((n=n.x)[0]<0?n[1]-Ea-Aa:Ea-n[1])-((t=t.x)[0]<0?t[1]-Ea-Aa:Ea-t[1])}function Le(n,t){var e=n[0],r=n[1],u=[Math.sin(e),-Math.cos(e),0],i=0,o=0;hc.reset();for(var a=0,c=t.length;c>a;++a){var s=t[a],l=s.length;if(l)for(var f=s[0],h=f[0],g=f[1]/2+Sa/4,p=Math.sin(g),v=Math.cos(g),d=1;;){d===l&&(d=0),n=s[d];var m=n[0],y=n[1]/2+Sa/4,x=Math.sin(y),M=Math.cos(y),_=m-h,b=_>=0?1:-1,w=b*_,S=w>Sa,k=p*x;if(hc.add(Math.atan2(k*b*Math.sin(w),v*M+k*Math.cos(w))),i+=S?_+b*ka:_,S^h>=e^m>=e){var E=fe(se(f),se(n));pe(E);var A=fe(u,E);pe(A);var C=(S^_>=0?-1:1)*X(A[2]);(r>C||r===C&&(E[0]||E[1]))&&(o+=S^_>=0?1:-1)}if(!d++)break;h=m,p=x,v=M,f=n}}return(-Aa>i||Aa>i&&0>hc)^1&o}function ze(n){var t,e=0/0,r=0/0,u=0/0;return{lineStart:function(){n.lineStart(),t=1},point:function(i,o){var a=i>0?Sa:-Sa,c=oa(i-e);oa(c-Sa)<Aa?(n.point(e,r=(r+o)/2>0?Ea:-Ea),n.point(u,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(i,r),t=0):u!==a&&c>=Sa&&(oa(e-u)<Aa&&(e-=u*Aa),oa(i-a)<Aa&&(i-=a*Aa),r=qe(e,r,i,o),n.point(u,r),n.lineEnd(),n.lineStart(),n.point(a,r),t=0),n.point(e=i,r=o),u=a},lineEnd:function(){n.lineEnd(),e=r=0/0},clean:function(){return 2-t}}}function qe(n,t,e,r){var u,i,o=Math.sin(n-e);return oa(o)>Aa?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(e)-Math.sin(r)*(u=Math.cos(t))*Math.sin(n))/(u*i*o)):(t+r)/2}function Te(n,t,e,r){var u;if(null==n)u=e*Ea,r.point(-Sa,u),r.point(0,u),r.point(Sa,u),r.point(Sa,0),r.point(Sa,-u),r.point(0,-u),r.point(-Sa,-u),r.point(-Sa,0),r.point(-Sa,u);else if(oa(n[0]-t[0])>Aa){var i=n[0]<t[0]?Sa:-Sa;u=e*i/2,r.point(-i,u),r.point(0,u),r.point(i,u)}else r.point(t[0],t[1])}function Re(n){function t(n,t){return Math.cos(n)*Math.cos(t)>i}function e(n){var e,i,c,s,l;return{lineStart:function(){s=c=!1,l=1},point:function(f,h){var g,p=[f,h],v=t(f,h),d=o?v?0:u(f,h):v?u(f+(0>f?Sa:-Sa),h):0;if(!e&&(s=c=v)&&n.lineStart(),v!==c&&(g=r(e,p),(de(e,g)||de(p,g))&&(p[0]+=Aa,p[1]+=Aa,v=t(p[0],p[1]))),v!==c)l=0,v?(n.lineStart(),g=r(p,e),n.point(g[0],g[1])):(g=r(e,p),n.point(g[0],g[1]),n.lineEnd()),e=g;else if(a&&e&&o^v){var m;d&i||!(m=r(p,e,!0))||(l=0,o?(n.lineStart(),n.point(m[0][0],m[0][1]),n.point(m[1][0],m[1][1]),n.lineEnd()):(n.point(m[1][0],m[1][1]),n.lineEnd(),n.lineStart(),n.point(m[0][0],m[0][1])))}!v||e&&de(e,p)||n.point(p[0],p[1]),e=p,c=v,i=d},lineEnd:function(){c&&n.lineEnd(),e=null},clean:function(){return l|(s&&c)<<1}}}function r(n,t,e){var r=se(n),u=se(t),o=[1,0,0],a=fe(r,u),c=le(a,a),s=a[0],l=c-s*s;if(!l)return!e&&n;var f=i*c/l,h=-i*s/l,g=fe(o,a),p=ge(o,f),v=ge(a,h);he(p,v);var d=g,m=le(p,d),y=le(d,d),x=m*m-y*(le(p,p)-1);if(!(0>x)){var M=Math.sqrt(x),_=ge(d,(-m-M)/y);if(he(_,p),_=ve(_),!e)return _;var b,w=n[0],S=t[0],k=n[1],E=t[1];w>S&&(b=w,w=S,S=b);var A=S-w,C=oa(A-Sa)<Aa,N=C||Aa>A;if(!C&&k>E&&(b=k,k=E,E=b),N?C?k+E>0^_[1]<(oa(_[0]-w)<Aa?k:E):k<=_[1]&&_[1]<=E:A>Sa^(w<=_[0]&&_[0]<=S)){var L=ge(d,(-m+M)/y);return he(L,p),[_,ve(L)]}}}function u(t,e){var r=o?n:Sa-n,u=0;return-r>t?u|=1:t>r&&(u|=2),-r>e?u|=4:e>r&&(u|=8),u}var i=Math.cos(n),o=i>0,a=oa(i)>Aa,c=cr(n,6*Na);return Ee(t,e,c,o?[0,-n]:[-Sa,n-Sa])}function De(n,t,e,r){return function(u){var i,o=u.a,a=u.b,c=o.x,s=o.y,l=a.x,f=a.y,h=0,g=1,p=l-c,v=f-s;if(i=n-c,p||!(i>0)){if(i/=p,0>p){if(h>i)return;g>i&&(g=i)}else if(p>0){if(i>g)return;i>h&&(h=i)}if(i=e-c,p||!(0>i)){if(i/=p,0>p){if(i>g)return;i>h&&(h=i)}else if(p>0){if(h>i)return;g>i&&(g=i)}if(i=t-s,v||!(i>0)){if(i/=v,0>v){if(h>i)return;g>i&&(g=i)}else if(v>0){if(i>g)return;i>h&&(h=i)}if(i=r-s,v||!(0>i)){if(i/=v,0>v){if(i>g)return;i>h&&(h=i)}else if(v>0){if(h>i)return;g>i&&(g=i)}return h>0&&(u.a={x:c+h*p,y:s+h*v}),1>g&&(u.b={x:c+g*p,y:s+g*v}),u}}}}}}function Pe(n,t,e,r){function u(r,u){return oa(r[0]-n)<Aa?u>0?0:3:oa(r[0]-e)<Aa?u>0?2:1:oa(r[1]-t)<Aa?u>0?1:0:u>0?3:2}function i(n,t){return o(n.x,t.x)}function o(n,t){var e=u(n,1),r=u(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function c(n){for(var t=0,e=d.length,r=n[1],u=0;e>u;++u)for(var i,o=1,a=d[u],c=a.length,s=a[0];c>o;++o)i=a[o],s[1]<=r?i[1]>r&&Z(s,i,n)>0&&++t:i[1]<=r&&Z(s,i,n)<0&&--t,s=i;return 0!==t}function s(i,a,c,s){var l=0,f=0;if(null==i||(l=u(i,c))!==(f=u(a,c))||o(i,a)<0^c>0){do s.point(0===l||3===l?n:e,l>1?r:t);while((l=(l+c+4)%4)!==f)}else s.point(a[0],a[1])}function l(u,i){return u>=n&&e>=u&&i>=t&&r>=i}function f(n,t){l(n,t)&&a.point(n,t)}function h(){N.point=p,d&&d.push(m=[]),S=!0,w=!1,_=b=0/0}function g(){v&&(p(y,x),M&&w&&A.rejoin(),v.push(A.buffer())),N.point=f,w&&a.lineEnd()}function p(n,t){n=Math.max(-Ac,Math.min(Ac,n)),t=Math.max(-Ac,Math.min(Ac,t));var e=l(n,t);if(d&&m.push([n,t]),S)y=n,x=t,M=e,S=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&w)a.point(n,t);else{var r={a:{x:_,y:b},b:{x:n,y:t}};C(r)?(w||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),k=!1):e&&(a.lineStart(),a.point(n,t),k=!1)}_=n,b=t,w=e}var v,d,m,y,x,M,_,b,w,S,k,E=a,A=Ce(),C=De(n,t,e,r),N={point:f,lineStart:h,lineEnd:g,polygonStart:function(){a=A,v=[],d=[],k=!0},polygonEnd:function(){a=E,v=Xo.merge(v);var t=c([n,r]),e=k&&t,u=v.length;(e||u)&&(a.polygonStart(),e&&(a.lineStart(),s(null,null,1,a),a.lineEnd()),u&&we(v,i,t,s,a),a.polygonEnd()),v=d=m=null}};return N}}function Ue(n,t){function e(e,r){return e=n(e,r),t(e[0],e[1])}return n.invert&&t.invert&&(e.invert=function(e,r){return e=t.invert(e,r),e&&n.invert(e[0],e[1])}),e}function je(n){var t=0,e=Sa/3,r=nr(n),u=r(t,e);return u.parallels=function(n){return arguments.length?r(t=n[0]*Sa/180,e=n[1]*Sa/180):[180*(t/Sa),180*(e/Sa)]},u}function He(n,t){function e(n,t){var e=Math.sqrt(i-2*u*Math.sin(t))/u;return[e*Math.sin(n*=u),o-e*Math.cos(n)]}var r=Math.sin(n),u=(r+Math.sin(t))/2,i=1+r*(2*u-r),o=Math.sqrt(i)/u;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/u,X((i-(n*n+e*e)*u*u)/(2*u))]},e}function Fe(){function n(n,t){Nc+=u*n-r*t,r=n,u=t}var t,e,r,u;Rc.point=function(i,o){Rc.point=n,t=r=i,e=u=o},Rc.lineEnd=function(){n(t,e)}}function Oe(n,t){Lc>n&&(Lc=n),n>qc&&(qc=n),zc>t&&(zc=t),t>Tc&&(Tc=t)}function Ye(){function n(n,t){o.push("M",n,",",t,i)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function u(){o.push("Z")}var i=Ie(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return i=Ie(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function Ie(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function Ze(n,t){dc+=n,mc+=t,++yc}function Ve(){function n(n,r){var u=n-t,i=r-e,o=Math.sqrt(u*u+i*i);xc+=o*(t+n)/2,Mc+=o*(e+r)/2,_c+=o,Ze(t=n,e=r)}var t,e;Pc.point=function(r,u){Pc.point=n,Ze(t=r,e=u)}}function Xe(){Pc.point=Ze}function $e(){function n(n,t){var e=n-r,i=t-u,o=Math.sqrt(e*e+i*i);xc+=o*(r+n)/2,Mc+=o*(u+t)/2,_c+=o,o=u*n-r*t,bc+=o*(r+n),wc+=o*(u+t),Sc+=3*o,Ze(r=n,u=t)}var t,e,r,u;Pc.point=function(i,o){Pc.point=n,Ze(t=r=i,e=u=o)},Pc.lineEnd=function(){n(t,e)}}function Be(n){function t(t,e){n.moveTo(t,e),n.arc(t,e,o,0,ka)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function u(){a.point=t}function i(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:u,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=u,a.point=t},pointRadius:function(n){return o=n,a},result:g};return a}function We(n){function t(n){return(a?r:e)(n)}function e(t){return Ke(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){x=0/0,S.point=i,t.lineStart()}function i(e,r){var i=se([e,r]),o=n(e,r);u(x,M,y,_,b,w,x=o[0],M=o[1],y=e,_=i[0],b=i[1],w=i[2],a,t),t.point(x,M)}function o(){S.point=e,t.lineEnd()}function c(){r(),S.point=s,S.lineEnd=l}function s(n,t){i(f=n,h=t),g=x,p=M,v=_,d=b,m=w,S.point=i}function l(){u(x,M,y,_,b,w,g,p,f,v,d,m,a,t),S.lineEnd=o,o()}var f,h,g,p,v,d,m,y,x,M,_,b,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=c},polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function u(t,e,r,a,c,s,l,f,h,g,p,v,d,m){var y=l-t,x=f-e,M=y*y+x*x;if(M>4*i&&d--){var _=a+g,b=c+p,w=s+v,S=Math.sqrt(_*_+b*b+w*w),k=Math.asin(w/=S),E=oa(oa(w)-1)<Aa||oa(r-h)<Aa?(r+h)/2:Math.atan2(b,_),A=n(E,k),C=A[0],N=A[1],L=C-t,z=N-e,q=x*L-y*z;(q*q/M>i||oa((y*L+x*z)/M-.5)>.3||o>a*g+c*p+s*v)&&(u(t,e,r,a,c,s,C,N,E,_/=S,b/=S,w,d,m),m.point(C,N),u(C,N,E,_,b,w,l,f,h,g,p,v,d,m))}}var i=.5,o=Math.cos(30*Na),a=16;return t.precision=function(n){return arguments.length?(a=(i=n*n)>0&&16,t):Math.sqrt(i)},t}function Je(n){var t=We(function(t,e){return n([t*La,e*La])});return function(n){return tr(t(n))}}function Ge(n){this.stream=n}function Ke(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function Qe(n){return nr(function(){return n})()}function nr(n){function t(n){return n=a(n[0]*Na,n[1]*Na),[n[0]*h+c,s-n[1]*h]}function e(n){return n=a.invert((n[0]-c)/h,(s-n[1])/h),n&&[n[0]*La,n[1]*La]}function r(){a=Ue(o=ur(m,y,x),i);var n=i(v,d);return c=g-n[0]*h,s=p+n[1]*h,u()}function u(){return l&&(l.valid=!1,l=null),t}var i,o,a,c,s,l,f=We(function(n,t){return n=i(n,t),[n[0]*h+c,s-n[1]*h]}),h=150,g=480,p=250,v=0,d=0,m=0,y=0,x=0,M=Ec,_=bt,b=null,w=null;return t.stream=function(n){return l&&(l.valid=!1),l=tr(M(o,f(_(n)))),l.valid=!0,l | |
},t.clipAngle=function(n){return arguments.length?(M=null==n?(b=n,Ec):Re((b=+n)*Na),u()):b},t.clipExtent=function(n){return arguments.length?(w=n,_=n?Pe(n[0][0],n[0][1],n[1][0],n[1][1]):bt,u()):w},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(g=+n[0],p=+n[1],r()):[g,p]},t.center=function(n){return arguments.length?(v=n[0]%360*Na,d=n[1]%360*Na,r()):[v*La,d*La]},t.rotate=function(n){return arguments.length?(m=n[0]%360*Na,y=n[1]%360*Na,x=n.length>2?n[2]%360*Na:0,r()):[m*La,y*La,x*La]},Xo.rebind(t,f,"precision"),function(){return i=n.apply(this,arguments),t.invert=i.invert&&e,r()}}function tr(n){return Ke(n,function(t,e){n.point(t*Na,e*Na)})}function er(n,t){return[n,t]}function rr(n,t){return[n>Sa?n-ka:-Sa>n?n+ka:n,t]}function ur(n,t,e){return n?t||e?Ue(or(n),ar(t,e)):or(n):t||e?ar(t,e):rr}function ir(n){return function(t,e){return t+=n,[t>Sa?t-ka:-Sa>t?t+ka:t,e]}}function or(n){var t=ir(n);return t.invert=ir(-n),t}function ar(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,s=Math.sin(t),l=s*r+a*u;return[Math.atan2(c*i-l*o,a*r-s*u),X(l*i+c*o)]}var r=Math.cos(n),u=Math.sin(n),i=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,s=Math.sin(t),l=s*i-c*o;return[Math.atan2(c*i+s*o,a*r+l*u),X(l*r-a*u)]},e}function cr(n,t){var e=Math.cos(n),r=Math.sin(n);return function(u,i,o,a){var c=o*t;null!=u?(u=sr(e,u),i=sr(e,i),(o>0?i>u:u>i)&&(u+=o*ka)):(u=n+o*ka,i=n-.5*c);for(var s,l=u;o>0?l>i:i>l;l-=c)a.point((s=ve([e,-r*Math.cos(l),-r*Math.sin(l)]))[0],s[1])}}function sr(n,t){var e=se(t);e[0]-=n,pe(e);var r=V(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-Aa)%(2*Math.PI)}function lr(n,t,e){var r=Xo.range(n,t-Aa,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function fr(n,t,e){var r=Xo.range(n,t-Aa,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function hr(n){return n.source}function gr(n){return n.target}function pr(n,t,e,r){var u=Math.cos(t),i=Math.sin(t),o=Math.cos(r),a=Math.sin(r),c=u*Math.cos(n),s=u*Math.sin(n),l=o*Math.cos(e),f=o*Math.sin(e),h=2*Math.asin(Math.sqrt(J(r-t)+u*o*J(e-n))),g=1/Math.sin(h),p=h?function(n){var t=Math.sin(n*=h)*g,e=Math.sin(h-n)*g,r=e*c+t*l,u=e*s+t*f,o=e*i+t*a;return[Math.atan2(u,r)*La,Math.atan2(o,Math.sqrt(r*r+u*u))*La]}:function(){return[n*La,t*La]};return p.distance=h,p}function vr(){function n(n,u){var i=Math.sin(u*=Na),o=Math.cos(u),a=oa((n*=Na)-t),c=Math.cos(a);Uc+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*i-e*o*c)*a),e*i+r*o*c),t=n,e=i,r=o}var t,e,r;jc.point=function(u,i){t=u*Na,e=Math.sin(i*=Na),r=Math.cos(i),jc.point=n},jc.lineEnd=function(){jc.point=jc.lineEnd=g}}function dr(n,t){function e(t,e){var r=Math.cos(t),u=Math.cos(e),i=n(r*u);return[i*u*Math.sin(t),i*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),u=t(r),i=Math.sin(u),o=Math.cos(u);return[Math.atan2(n*i,r*o),Math.asin(r&&e*i/r)]},e}function mr(n,t){function e(n,t){var e=oa(oa(t)-Ea)<Aa?0:o/Math.pow(u(t),i);return[e*Math.sin(i*n),o-e*Math.cos(i*n)]}var r=Math.cos(n),u=function(n){return Math.tan(Sa/4+n/2)},i=n===t?Math.sin(n):Math.log(r/Math.cos(t))/Math.log(u(t)/u(n)),o=r*Math.pow(u(n),i)/i;return i?(e.invert=function(n,t){var e=o-t,r=I(i)*Math.sqrt(n*n+e*e);return[Math.atan2(n,e)/i,2*Math.atan(Math.pow(o/r,1/i))-Ea]},e):xr}function yr(n,t){function e(n,t){var e=i-t;return[e*Math.sin(u*n),i-e*Math.cos(u*n)]}var r=Math.cos(n),u=n===t?Math.sin(n):(r-Math.cos(t))/(t-n),i=r/u+n;return oa(u)<Aa?er:(e.invert=function(n,t){var e=i-t;return[Math.atan2(n,e)/u,i-I(u)*Math.sqrt(n*n+e*e)]},e)}function xr(n,t){return[n,Math.log(Math.tan(Sa/4+t/2))]}function Mr(n){var t,e=Qe(n),r=e.scale,u=e.translate,i=e.clipExtent;return e.scale=function(){var n=r.apply(e,arguments);return n===e?t?e.clipExtent(null):e:n},e.translate=function(){var n=u.apply(e,arguments);return n===e?t?e.clipExtent(null):e:n},e.clipExtent=function(n){var o=i.apply(e,arguments);if(o===e){if(t=null==n){var a=Sa*r(),c=u();i([[c[0]-a,c[1]-a],[c[0]+a,c[1]+a]])}}else t&&(o=null);return o},e.clipExtent(null)}function _r(n,t){return[Math.log(Math.tan(Sa/4+t/2)),-n]}function br(n){return n[0]}function wr(n){return n[1]}function Sr(n){for(var t=n.length,e=[0,1],r=2,u=2;t>u;u++){for(;r>1&&Z(n[e[r-2]],n[e[r-1]],n[u])<=0;)--r;e[r++]=u}return e.slice(0,r)}function kr(n,t){return n[0]-t[0]||n[1]-t[1]}function Er(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Ar(n,t,e,r){var u=n[0],i=e[0],o=t[0]-u,a=r[0]-i,c=n[1],s=e[1],l=t[1]-c,f=r[1]-s,h=(a*(c-s)-f*(u-i))/(f*o-a*l);return[u+h*o,c+h*l]}function Cr(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function Nr(){Jr(this),this.edge=this.site=this.circle=null}function Lr(n){var t=Jc.pop()||new Nr;return t.site=n,t}function zr(n){Or(n),$c.remove(n),Jc.push(n),Jr(n)}function qr(n){var t=n.circle,e=t.x,r=t.cy,u={x:e,y:r},i=n.P,o=n.N,a=[n];zr(n);for(var c=i;c.circle&&oa(e-c.circle.x)<Aa&&oa(r-c.circle.cy)<Aa;)i=c.P,a.unshift(c),zr(c),c=i;a.unshift(c),Or(c);for(var s=o;s.circle&&oa(e-s.circle.x)<Aa&&oa(r-s.circle.cy)<Aa;)o=s.N,a.push(s),zr(s),s=o;a.push(s),Or(s);var l,f=a.length;for(l=1;f>l;++l)s=a[l],c=a[l-1],$r(s.edge,c.site,s.site,u);c=a[0],s=a[f-1],s.edge=Vr(c.site,s.site,null,u),Fr(c),Fr(s)}function Tr(n){for(var t,e,r,u,i=n.x,o=n.y,a=$c._;a;)if(r=Rr(a,o)-i,r>Aa)a=a.L;else{if(u=i-Dr(a,o),!(u>Aa)){r>-Aa?(t=a.P,e=a):u>-Aa?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var c=Lr(n);if($c.insert(t,c),t||e){if(t===e)return Or(t),e=Lr(t.site),$c.insert(c,e),c.edge=e.edge=Vr(t.site,c.site),Fr(t),Fr(e),void 0;if(!e)return c.edge=Vr(t.site,c.site),void 0;Or(t),Or(e);var s=t.site,l=s.x,f=s.y,h=n.x-l,g=n.y-f,p=e.site,v=p.x-l,d=p.y-f,m=2*(h*d-g*v),y=h*h+g*g,x=v*v+d*d,M={x:(d*y-g*x)/m+l,y:(h*x-v*y)/m+f};$r(e.edge,s,p,M),c.edge=Vr(s,n,null,M),e.edge=Vr(n,p,null,M),Fr(t),Fr(e)}}function Rr(n,t){var e=n.site,r=e.x,u=e.y,i=u-t;if(!i)return r;var o=n.P;if(!o)return-1/0;e=o.site;var a=e.x,c=e.y,s=c-t;if(!s)return a;var l=a-r,f=1/i-1/s,h=l/s;return f?(-h+Math.sqrt(h*h-2*f*(l*l/(-2*s)-c+s/2+u-i/2)))/f+r:(r+a)/2}function Dr(n,t){var e=n.N;if(e)return Rr(e,t);var r=n.site;return r.y===t?r.x:1/0}function Pr(n){this.site=n,this.edges=[]}function Ur(n){for(var t,e,r,u,i,o,a,c,s,l,f=n[0][0],h=n[1][0],g=n[0][1],p=n[1][1],v=Xc,d=v.length;d--;)if(i=v[d],i&&i.prepare())for(a=i.edges,c=a.length,o=0;c>o;)l=a[o].end(),r=l.x,u=l.y,s=a[++o%c].start(),t=s.x,e=s.y,(oa(r-t)>Aa||oa(u-e)>Aa)&&(a.splice(o,0,new Br(Xr(i.site,l,oa(r-f)<Aa&&p-u>Aa?{x:f,y:oa(t-f)<Aa?e:p}:oa(u-p)<Aa&&h-r>Aa?{x:oa(e-p)<Aa?t:h,y:p}:oa(r-h)<Aa&&u-g>Aa?{x:h,y:oa(t-h)<Aa?e:g}:oa(u-g)<Aa&&r-f>Aa?{x:oa(e-g)<Aa?t:f,y:g}:null),i.site,null)),++c)}function jr(n,t){return t.angle-n.angle}function Hr(){Jr(this),this.x=this.y=this.arc=this.site=this.cy=null}function Fr(n){var t=n.P,e=n.N;if(t&&e){var r=t.site,u=n.site,i=e.site;if(r!==i){var o=u.x,a=u.y,c=r.x-o,s=r.y-a,l=i.x-o,f=i.y-a,h=2*(c*f-s*l);if(!(h>=-Ca)){var g=c*c+s*s,p=l*l+f*f,v=(f*g-s*p)/h,d=(c*p-l*g)/h,f=d+a,m=Gc.pop()||new Hr;m.arc=n,m.site=u,m.x=v+o,m.y=f+Math.sqrt(v*v+d*d),m.cy=f,n.circle=m;for(var y=null,x=Wc._;x;)if(m.y<x.y||m.y===x.y&&m.x<=x.x){if(!x.L){y=x.P;break}x=x.L}else{if(!x.R){y=x;break}x=x.R}Wc.insert(y,m),y||(Bc=m)}}}}function Or(n){var t=n.circle;t&&(t.P||(Bc=t.N),Wc.remove(t),Gc.push(t),Jr(t),n.circle=null)}function Yr(n){for(var t,e=Vc,r=De(n[0][0],n[0][1],n[1][0],n[1][1]),u=e.length;u--;)t=e[u],(!Ir(t,n)||!r(t)||oa(t.a.x-t.b.x)<Aa&&oa(t.a.y-t.b.y)<Aa)&&(t.a=t.b=null,e.splice(u,1))}function Ir(n,t){var e=n.b;if(e)return!0;var r,u,i=n.a,o=t[0][0],a=t[1][0],c=t[0][1],s=t[1][1],l=n.l,f=n.r,h=l.x,g=l.y,p=f.x,v=f.y,d=(h+p)/2,m=(g+v)/2;if(v===g){if(o>d||d>=a)return;if(h>p){if(i){if(i.y>=s)return}else i={x:d,y:c};e={x:d,y:s}}else{if(i){if(i.y<c)return}else i={x:d,y:s};e={x:d,y:c}}}else if(r=(h-p)/(v-g),u=m-r*d,-1>r||r>1)if(h>p){if(i){if(i.y>=s)return}else i={x:(c-u)/r,y:c};e={x:(s-u)/r,y:s}}else{if(i){if(i.y<c)return}else i={x:(s-u)/r,y:s};e={x:(c-u)/r,y:c}}else if(v>g){if(i){if(i.x>=a)return}else i={x:o,y:r*o+u};e={x:a,y:r*a+u}}else{if(i){if(i.x<o)return}else i={x:a,y:r*a+u};e={x:o,y:r*o+u}}return n.a=i,n.b=e,!0}function Zr(n,t){this.l=n,this.r=t,this.a=this.b=null}function Vr(n,t,e,r){var u=new Zr(n,t);return Vc.push(u),e&&$r(u,n,t,e),r&&$r(u,t,n,r),Xc[n.i].edges.push(new Br(u,n,t)),Xc[t.i].edges.push(new Br(u,t,n)),u}function Xr(n,t,e){var r=new Zr(n,null);return r.a=t,r.b=e,Vc.push(r),r}function $r(n,t,e,r){n.a||n.b?n.l===e?n.b=r:n.a=r:(n.a=r,n.l=t,n.r=e)}function Br(n,t,e){var r=n.a,u=n.b;this.edge=n,this.site=t,this.angle=e?Math.atan2(e.y-t.y,e.x-t.x):n.l===t?Math.atan2(u.x-r.x,r.y-u.y):Math.atan2(r.x-u.x,u.y-r.y)}function Wr(){this._=null}function Jr(n){n.U=n.C=n.L=n.R=n.P=n.N=null}function Gr(n,t){var e=t,r=t.R,u=e.U;u?u.L===e?u.L=r:u.R=r:n._=r,r.U=u,e.U=r,e.R=r.L,e.R&&(e.R.U=e),r.L=e}function Kr(n,t){var e=t,r=t.L,u=e.U;u?u.L===e?u.L=r:u.R=r:n._=r,r.U=u,e.U=r,e.L=r.R,e.L&&(e.L.U=e),r.R=e}function Qr(n){for(;n.L;)n=n.L;return n}function nu(n,t){var e,r,u,i=n.sort(tu).pop();for(Vc=[],Xc=new Array(n.length),$c=new Wr,Wc=new Wr;;)if(u=Bc,i&&(!u||i.y<u.y||i.y===u.y&&i.x<u.x))(i.x!==e||i.y!==r)&&(Xc[i.i]=new Pr(i),Tr(i),e=i.x,r=i.y),i=n.pop();else{if(!u)break;qr(u.arc)}t&&(Yr(t),Ur(t));var o={cells:Xc,edges:Vc};return $c=Wc=Vc=Xc=null,o}function tu(n,t){return t.y-n.y||t.x-n.x}function eu(n,t,e){return(n.x-e.x)*(t.y-n.y)-(n.x-t.x)*(e.y-n.y)}function ru(n){return n.x}function uu(n){return n.y}function iu(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function ou(n,t,e,r,u,i){if(!n(t,e,r,u,i)){var o=.5*(e+u),a=.5*(r+i),c=t.nodes;c[0]&&ou(n,c[0],e,r,o,a),c[1]&&ou(n,c[1],o,r,u,a),c[2]&&ou(n,c[2],e,a,o,i),c[3]&&ou(n,c[3],o,a,u,i)}}function au(n,t){n=Xo.rgb(n),t=Xo.rgb(t);var e=n.r,r=n.g,u=n.b,i=t.r-e,o=t.g-r,a=t.b-u;return function(n){return"#"+vt(Math.round(e+i*n))+vt(Math.round(r+o*n))+vt(Math.round(u+a*n))}}function cu(n,t){var e,r={},u={};for(e in n)e in t?r[e]=fu(n[e],t[e]):u[e]=n[e];for(e in t)e in n||(u[e]=t[e]);return function(n){for(e in r)u[e]=r[e](n);return u}}function su(n,t){return t-=n=+n,function(e){return n+t*e}}function lu(n,t){var e,r,u,i,o,a=0,c=0,s=[],l=[];for(n+="",t+="",Qc.lastIndex=0,r=0;e=Qc.exec(t);++r)e.index&&s.push(t.substring(a,c=e.index)),l.push({i:s.length,x:e[0]}),s.push(null),a=Qc.lastIndex;for(a<t.length&&s.push(t.substring(a)),r=0,i=l.length;(e=Qc.exec(n))&&i>r;++r)if(o=l[r],o.x==e[0]){if(o.i)if(null==s[o.i+1])for(s[o.i-1]+=o.x,s.splice(o.i,1),u=r+1;i>u;++u)l[u].i--;else for(s[o.i-1]+=o.x+s[o.i+1],s.splice(o.i,2),u=r+1;i>u;++u)l[u].i-=2;else if(null==s[o.i+1])s[o.i]=o.x;else for(s[o.i]=o.x+s[o.i+1],s.splice(o.i+1,1),u=r+1;i>u;++u)l[u].i--;l.splice(r,1),i--,r--}else o.x=su(parseFloat(e[0]),parseFloat(o.x));for(;i>r;)o=l.pop(),null==s[o.i+1]?s[o.i]=o.x:(s[o.i]=o.x+s[o.i+1],s.splice(o.i+1,1)),i--;return 1===s.length?null==s[0]?(o=l[0].x,function(n){return o(n)+""}):function(){return t}:function(n){for(r=0;i>r;++r)s[(o=l[r]).i]=o.x(n);return s.join("")}}function fu(n,t){for(var e,r=Xo.interpolators.length;--r>=0&&!(e=Xo.interpolators[r](n,t)););return e}function hu(n,t){var e,r=[],u=[],i=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(fu(n[e],t[e]));for(;i>e;++e)u[e]=n[e];for(;o>e;++e)u[e]=t[e];return function(n){for(e=0;a>e;++e)u[e]=r[e](n);return u}}function gu(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function pu(n){return function(t){return 1-n(1-t)}}function vu(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function du(n){return n*n}function mu(n){return n*n*n}function yu(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function xu(n){return function(t){return Math.pow(t,n)}}function Mu(n){return 1-Math.cos(n*Ea)}function _u(n){return Math.pow(2,10*(n-1))}function bu(n){return 1-Math.sqrt(1-n*n)}function wu(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/ka*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*ka/t)}}function Su(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function ku(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function Eu(n,t){n=Xo.hcl(n),t=Xo.hcl(t);var e=n.h,r=n.c,u=n.l,i=t.h-e,o=t.c-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return rt(e+i*n,r+o*n,u+a*n)+""}}function Au(n,t){n=Xo.hsl(n),t=Xo.hsl(t);var e=n.h,r=n.s,u=n.l,i=t.h-e,o=t.s-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return nt(e+i*n,r+o*n,u+a*n)+""}}function Cu(n,t){n=Xo.lab(n),t=Xo.lab(t);var e=n.l,r=n.a,u=n.b,i=t.l-e,o=t.a-r,a=t.b-u;return function(n){return ot(e+i*n,r+o*n,u+a*n)+""}}function Nu(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function Lu(n){var t=[n.a,n.b],e=[n.c,n.d],r=qu(t),u=zu(t,e),i=qu(Tu(e,t,-u))||0;t[0]*e[1]<e[0]*t[1]&&(t[0]*=-1,t[1]*=-1,r*=-1,u*=-1),this.rotate=(r?Math.atan2(t[1],t[0]):Math.atan2(-e[0],e[1]))*La,this.translate=[n.e,n.f],this.scale=[r,i],this.skew=i?Math.atan2(u,i)*La:0}function zu(n,t){return n[0]*t[0]+n[1]*t[1]}function qu(n){var t=Math.sqrt(zu(n,n));return t&&(n[0]/=t,n[1]/=t),t}function Tu(n,t,e){return n[0]+=e*t[0],n[1]+=e*t[1],n}function Ru(n,t){var e,r=[],u=[],i=Xo.transform(n),o=Xo.transform(t),a=i.translate,c=o.translate,s=i.rotate,l=o.rotate,f=i.skew,h=o.skew,g=i.scale,p=o.scale;return a[0]!=c[0]||a[1]!=c[1]?(r.push("translate(",null,",",null,")"),u.push({i:1,x:su(a[0],c[0])},{i:3,x:su(a[1],c[1])})):c[0]||c[1]?r.push("translate("+c+")"):r.push(""),s!=l?(s-l>180?l+=360:l-s>180&&(s+=360),u.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:su(s,l)})):l&&r.push(r.pop()+"rotate("+l+")"),f!=h?u.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:su(f,h)}):h&&r.push(r.pop()+"skewX("+h+")"),g[0]!=p[0]||g[1]!=p[1]?(e=r.push(r.pop()+"scale(",null,",",null,")"),u.push({i:e-4,x:su(g[0],p[0])},{i:e-2,x:su(g[1],p[1])})):(1!=p[0]||1!=p[1])&&r.push(r.pop()+"scale("+p+")"),e=u.length,function(n){for(var t,i=-1;++i<e;)r[(t=u[i]).i]=t.x(n);return r.join("")}}function Du(n,t){return t=t-(n=+n)?1/(t-n):0,function(e){return(e-n)*t}}function Pu(n,t){return t=t-(n=+n)?1/(t-n):0,function(e){return Math.max(0,Math.min(1,(e-n)*t))}}function Uu(n){for(var t=n.source,e=n.target,r=Hu(t,e),u=[t];t!==r;)t=t.parent,u.push(t);for(var i=u.length;e!==r;)u.splice(i,0,e),e=e.parent;return u}function ju(n){for(var t=[],e=n.parent;null!=e;)t.push(n),n=e,e=e.parent;return t.push(n),t}function Hu(n,t){if(n===t)return n;for(var e=ju(n),r=ju(t),u=e.pop(),i=r.pop(),o=null;u===i;)o=u,u=e.pop(),i=r.pop();return o}function Fu(n){n.fixed|=2}function Ou(n){n.fixed&=-7}function Yu(n){n.fixed|=4,n.px=n.x,n.py=n.y}function Iu(n){n.fixed&=-5}function Zu(n,t,e){var r=0,u=0;if(n.charge=0,!n.leaf)for(var i,o=n.nodes,a=o.length,c=-1;++c<a;)i=o[c],null!=i&&(Zu(i,t,e),n.charge+=i.charge,r+=i.charge*i.cx,u+=i.charge*i.cy);if(n.point){n.leaf||(n.point.x+=Math.random()-.5,n.point.y+=Math.random()-.5);var s=t*e[n.point.index];n.charge+=n.pointCharge=s,r+=s*n.point.x,u+=s*n.point.y}n.cx=r/n.charge,n.cy=u/n.charge}function Vu(n,t){return Xo.rebind(n,t,"sort","children","value"),n.nodes=n,n.links=Wu,n}function Xu(n){return n.children}function $u(n){return n.value}function Bu(n,t){return t.value-n.value}function Wu(n){return Xo.merge(n.map(function(n){return(n.children||[]).map(function(t){return{source:n,target:t}})}))}function Ju(n){return n.x}function Gu(n){return n.y}function Ku(n,t,e){n.y0=t,n.y=e}function Qu(n){return Xo.range(n.length)}function ni(n){for(var t=-1,e=n[0].length,r=[];++t<e;)r[t]=0;return r}function ti(n){for(var t,e=1,r=0,u=n[0][1],i=n.length;i>e;++e)(t=n[e][1])>u&&(r=e,u=t);return r}function ei(n){return n.reduce(ri,0)}function ri(n,t){return n+t[1]}function ui(n,t){return ii(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function ii(n,t){for(var e=-1,r=+n[0],u=(n[1]-r)/t,i=[];++e<=t;)i[e]=u*e+r;return i}function oi(n){return[Xo.min(n),Xo.max(n)]}function ai(n,t){return n.parent==t.parent?1:2}function ci(n){var t=n.children;return t&&t.length?t[0]:n._tree.thread}function si(n){var t,e=n.children;return e&&(t=e.length)?e[t-1]:n._tree.thread}function li(n,t){var e=n.children;if(e&&(u=e.length))for(var r,u,i=-1;++i<u;)t(r=li(e[i],t),n)>0&&(n=r);return n}function fi(n,t){return n.x-t.x}function hi(n,t){return t.x-n.x}function gi(n,t){return n.depth-t.depth}function pi(n,t){function e(n,r){var u=n.children;if(u&&(o=u.length))for(var i,o,a=null,c=-1;++c<o;)i=u[c],e(i,a),a=i;t(n,r)}e(n,null)}function vi(n){for(var t,e=0,r=0,u=n.children,i=u.length;--i>=0;)t=u[i]._tree,t.prelim+=e,t.mod+=e,e+=t.shift+(r+=t.change)}function di(n,t,e){n=n._tree,t=t._tree;var r=e/(t.number-n.number);n.change+=r,t.change-=r,t.shift+=e,t.prelim+=e,t.mod+=e}function mi(n,t,e){return n._tree.ancestor.parent==t.parent?n._tree.ancestor:e}function yi(n,t){return n.value-t.value}function xi(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function Mi(n,t){n._pack_next=t,t._pack_prev=n}function _i(n,t){var e=t.x-n.x,r=t.y-n.y,u=n.r+t.r;return.999*u*u>e*e+r*r}function bi(n){function t(n){l=Math.min(n.x-n.r,l),f=Math.max(n.x+n.r,f),h=Math.min(n.y-n.r,h),g=Math.max(n.y+n.r,g)}if((e=n.children)&&(s=e.length)){var e,r,u,i,o,a,c,s,l=1/0,f=-1/0,h=1/0,g=-1/0;if(e.forEach(wi),r=e[0],r.x=-r.r,r.y=0,t(r),s>1&&(u=e[1],u.x=u.r,u.y=0,t(u),s>2))for(i=e[2],Ei(r,u,i),t(i),xi(r,i),r._pack_prev=i,xi(i,u),u=r._pack_next,o=3;s>o;o++){Ei(r,u,i=e[o]);var p=0,v=1,d=1;for(a=u._pack_next;a!==u;a=a._pack_next,v++)if(_i(a,i)){p=1;break}if(1==p)for(c=r._pack_prev;c!==a._pack_prev&&!_i(c,i);c=c._pack_prev,d++);p?(d>v||v==d&&u.r<r.r?Mi(r,u=a):Mi(r=c,u),o--):(xi(r,i),u=i,t(i))}var m=(l+f)/2,y=(h+g)/2,x=0;for(o=0;s>o;o++)i=e[o],i.x-=m,i.y-=y,x=Math.max(x,i.r+Math.sqrt(i.x*i.x+i.y*i.y));n.r=x,e.forEach(Si)}}function wi(n){n._pack_next=n._pack_prev=n}function Si(n){delete n._pack_next,delete n._pack_prev}function ki(n,t,e,r){var u=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,u)for(var i=-1,o=u.length;++i<o;)ki(u[i],t,e,r)}function Ei(n,t,e){var r=n.r+e.r,u=t.x-n.x,i=t.y-n.y;if(r&&(u||i)){var o=t.r+e.r,a=u*u+i*i;o*=o,r*=r;var c=.5+(r-o)/(2*a),s=Math.sqrt(Math.max(0,2*o*(r+a)-(r-=a)*r-o*o))/(2*a);e.x=n.x+c*u+s*i,e.y=n.y+c*i-s*u}else e.x=n.x+r,e.y=n.y}function Ai(n){return 1+Xo.max(n,function(n){return n.y})}function Ci(n){return n.reduce(function(n,t){return n+t.x},0)/n.length}function Ni(n){var t=n.children;return t&&t.length?Ni(t[0]):n}function Li(n){var t,e=n.children;return e&&(t=e.length)?Li(e[t-1]):n}function zi(n){return{x:n.x,y:n.y,dx:n.dx,dy:n.dy}}function qi(n,t){var e=n.x+t[3],r=n.y+t[0],u=n.dx-t[1]-t[3],i=n.dy-t[0]-t[2];return 0>u&&(e+=u/2,u=0),0>i&&(r+=i/2,i=0),{x:e,y:r,dx:u,dy:i}}function Ti(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function Ri(n){return n.rangeExtent?n.rangeExtent():Ti(n.range())}function Di(n,t,e,r){var u=e(n[0],n[1]),i=r(t[0],t[1]);return function(n){return i(u(n))}}function Pi(n,t){var e,r=0,u=n.length-1,i=n[r],o=n[u];return i>o&&(e=r,r=u,u=e,e=i,i=o,o=e),n[r]=t.floor(i),n[u]=t.ceil(o),n}function Ui(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:ls}function ji(n,t,e,r){var u=[],i=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]<n[0]&&(n=n.slice().reverse(),t=t.slice().reverse());++o<=a;)u.push(e(n[o-1],n[o])),i.push(r(t[o-1],t[o]));return function(t){var e=Xo.bisect(n,t,1,a)-1;return i[e](u[e](t))}}function Hi(n,t,e,r){function u(){var u=Math.min(n.length,t.length)>2?ji:Di,c=r?Pu:Du;return o=u(n,t,c,e),a=u(t,n,c,fu),i}function i(n){return o(n)}var o,a;return i.invert=function(n){return a(n)},i.domain=function(t){return arguments.length?(n=t.map(Number),u()):n},i.range=function(n){return arguments.length?(t=n,u()):t},i.rangeRound=function(n){return i.range(n).interpolate(Nu)},i.clamp=function(n){return arguments.length?(r=n,u()):r},i.interpolate=function(n){return arguments.length?(e=n,u()):e},i.ticks=function(t){return Ii(n,t)},i.tickFormat=function(t,e){return Zi(n,t,e)},i.nice=function(t){return Oi(n,t),u()},i.copy=function(){return Hi(n,t,e,r)},u()}function Fi(n,t){return Xo.rebind(n,t,"range","rangeRound","interpolate","clamp")}function Oi(n,t){return Pi(n,Ui(Yi(n,t)[2]))}function Yi(n,t){null==t&&(t=10);var e=Ti(n),r=e[1]-e[0],u=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),i=t/r*u;return.15>=i?u*=10:.35>=i?u*=5:.75>=i&&(u*=2),e[0]=Math.ceil(e[0]/u)*u,e[1]=Math.floor(e[1]/u)*u+.5*u,e[2]=u,e}function Ii(n,t){return Xo.range.apply(Xo,Yi(n,t))}function Zi(n,t,e){var r=Yi(n,t);return Xo.format(e?e.replace(Qa,function(n,t,e,u,i,o,a,c,s,l){return[t,e,u,i,o,a,c,s||"."+Xi(l,r),l].join("")}):",."+Vi(r[2])+"f")}function Vi(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function Xi(n,t){var e=Vi(t[2]);return n in fs?Math.abs(e-Vi(Math.max(Math.abs(t[0]),Math.abs(t[1]))))+ +("e"!==n):e-2*("%"===n)}function $i(n,t,e,r){function u(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function i(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(u(t))}return o.invert=function(t){return i(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(u)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(u)),o):t},o.nice=function(){var t=Pi(r.map(u),e?Math:gs);return n.domain(t),r=t.map(i),o},o.ticks=function(){var n=Ti(r),o=[],a=n[0],c=n[1],s=Math.floor(u(a)),l=Math.ceil(u(c)),f=t%1?2:t;if(isFinite(l-s)){if(e){for(;l>s;s++)for(var h=1;f>h;h++)o.push(i(s)*h);o.push(i(s))}else for(o.push(i(s));s++<l;)for(var h=f-1;h>0;h--)o.push(i(s)*h);for(s=0;o[s]<a;s++);for(l=o.length;o[l-1]>c;l--);o=o.slice(s,l)}return o},o.tickFormat=function(n,t){if(!arguments.length)return hs;arguments.length<2?t=hs:"function"!=typeof t&&(t=Xo.format(t));var r,a=Math.max(.1,n/o.ticks().length),c=e?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(n){return n/i(c(u(n)+r))<=a?t(n):""}},o.copy=function(){return $i(n.copy(),t,e,r)},Fi(o,n)}function Bi(n,t,e){function r(t){return n(u(t))}var u=Wi(t),i=Wi(1/t);return r.invert=function(t){return i(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(u)),r):e},r.ticks=function(n){return Ii(e,n)},r.tickFormat=function(n,t){return Zi(e,n,t)},r.nice=function(n){return r.domain(Oi(e,n))},r.exponent=function(o){return arguments.length?(u=Wi(t=o),i=Wi(1/t),n.domain(e.map(u)),r):t},r.copy=function(){return Bi(n.copy(),t,e)},Fi(r,n)}function Wi(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function Ji(n,t){function e(e){return o[((i.get(e)||"range"===t.t&&i.set(e,n.push(e)))-1)%o.length]}function r(t,e){return Xo.range(n.length).map(function(n){return t+e*n})}var i,o,a;return e.domain=function(r){if(!arguments.length)return n;n=[],i=new u;for(var o,a=-1,c=r.length;++a<c;)i.has(o=r[a])||i.set(o,n.push(o));return e[t.t].apply(e,t.a)},e.range=function(n){return arguments.length?(o=n,a=0,t={t:"range",a:arguments},e):o},e.rangePoints=function(u,i){arguments.length<2&&(i=0);var c=u[0],s=u[1],l=(s-c)/(Math.max(1,n.length-1)+i);return o=r(n.length<2?(c+s)/2:c+l*i/2,l),a=0,t={t:"rangePoints",a:arguments},e},e.rangeBands=function(u,i,c){arguments.length<2&&(i=0),arguments.length<3&&(c=i);var s=u[1]<u[0],l=u[s-0],f=u[1-s],h=(f-l)/(n.length-i+2*c);return o=r(l+h*c,h),s&&o.reverse(),a=h*(1-i),t={t:"rangeBands",a:arguments},e},e.rangeRoundBands=function(u,i,c){arguments.length<2&&(i=0),arguments.length<3&&(c=i);var s=u[1]<u[0],l=u[s-0],f=u[1-s],h=Math.floor((f-l)/(n.length-i+2*c)),g=f-l-(n.length-i)*h;return o=r(l+Math.round(g/2),h),s&&o.reverse(),a=Math.round(h*(1-i)),t={t:"rangeRoundBands",a:arguments},e},e.rangeBand=function(){return a},e.rangeExtent=function(){return Ti(t.a[0])},e.copy=function(){return Ji(n,t)},e.domain(n)}function Gi(n,t){function e(){var e=0,i=t.length;for(u=[];++e<i;)u[e-1]=Xo.quantile(n,e/i);return r}function r(n){return isNaN(n=+n)?void 0:t[Xo.bisect(u,n)]}var u;return r.domain=function(t){return arguments.length?(n=t.filter(function(n){return!isNaN(n)}).sort(Xo.ascending),e()):n},r.range=function(n){return arguments.length?(t=n,e()):t},r.quantiles=function(){return u},r.invertExtent=function(e){return e=t.indexOf(e),0>e?[0/0,0/0]:[e>0?u[e-1]:n[0],e<u.length?u[e]:n[n.length-1]]},r.copy=function(){return Gi(n,t)},e()}function Ki(n,t,e){function r(t){return e[Math.max(0,Math.min(o,Math.floor(i*(t-n))))]}function u(){return i=e.length/(t-n),o=e.length-1,r}var i,o;return r.domain=function(e){return arguments.length?(n=+e[0],t=+e[e.length-1],u()):[n,t]},r.range=function(n){return arguments.length?(e=n,u()):e},r.invertExtent=function(t){return t=e.indexOf(t),t=0>t?0/0:t/i+n,[t,t+1/i]},r.copy=function(){return Ki(n,t,e)},u()}function Qi(n,t){function e(e){return e>=e?t[Xo.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return Qi(n,t)},e}function no(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return Ii(n,t)},t.tickFormat=function(t,e){return Zi(n,t,e)},t.copy=function(){return no(n)},t}function to(n){return n.innerRadius}function eo(n){return n.outerRadius}function ro(n){return n.startAngle}function uo(n){return n.endAngle}function io(n){function t(t){function o(){s.push("M",i(n(l),a))}for(var c,s=[],l=[],f=-1,h=t.length,g=_t(e),p=_t(r);++f<h;)u.call(this,c=t[f],f)?l.push([+g.call(this,c,f),+p.call(this,c,f)]):l.length&&(o(),l=[]);return l.length&&o(),s.length?s.join(""):null}var e=br,r=wr,u=be,i=oo,o=i.key,a=.7;return t.x=function(n){return arguments.length?(e=n,t):e},t.y=function(n){return arguments.length?(r=n,t):r},t.defined=function(n){return arguments.length?(u=n,t):u},t.interpolate=function(n){return arguments.length?(o="function"==typeof n?i=n:(i=Ms.get(n)||oo).key,t):o},t.tension=function(n){return arguments.length?(a=n,t):a},t}function oo(n){return n.join("L")}function ao(n){return oo(n)+"Z"}function co(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t<e;)u.push("H",(r[0]+(r=n[t])[0])/2,"V",r[1]);return e>1&&u.push("H",r[0]),u.join("")}function so(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t<e;)u.push("V",(r=n[t])[1],"H",r[0]);return u.join("")}function lo(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t<e;)u.push("H",(r=n[t])[0],"V",r[1]);return u.join("")}function fo(n,t){return n.length<4?oo(n):n[1]+po(n.slice(1,n.length-1),vo(n,t))}function ho(n,t){return n.length<3?oo(n):n[0]+po((n.push(n[0]),n),vo([n[n.length-2]].concat(n,[n[1]]),t))}function go(n,t){return n.length<3?oo(n):n[0]+po(n,vo(n,t))}function po(n,t){if(t.length<1||n.length!=t.length&&n.length!=t.length+2)return oo(n);var e=n.length!=t.length,r="",u=n[0],i=n[1],o=t[0],a=o,c=1;if(e&&(r+="Q"+(i[0]-2*o[0]/3)+","+(i[1]-2*o[1]/3)+","+i[0]+","+i[1],u=n[1],c=2),t.length>1){a=t[1],i=n[c],c++,r+="C"+(u[0]+o[0])+","+(u[1]+o[1])+","+(i[0]-a[0])+","+(i[1]-a[1])+","+i[0]+","+i[1];for(var s=2;s<t.length;s++,c++)i=n[c],a=t[s],r+="S"+(i[0]-a[0])+","+(i[1]-a[1])+","+i[0]+","+i[1]}if(e){var l=n[c];r+="Q"+(i[0]+2*a[0]/3)+","+(i[1]+2*a[1]/3)+","+l[0]+","+l[1]}return r}function vo(n,t){for(var e,r=[],u=(1-t)/2,i=n[0],o=n[1],a=1,c=n.length;++a<c;)e=i,i=o,o=n[a],r.push([u*(o[0]-e[0]),u*(o[1]-e[1])]);return r}function mo(n){if(n.length<3)return oo(n);var t=1,e=n.length,r=n[0],u=r[0],i=r[1],o=[u,u,u,(r=n[1])[0]],a=[i,i,i,r[1]],c=[u,",",i,"L",_o(ws,o),",",_o(ws,a)];for(n.push(n[e-1]);++t<=e;)r=n[t],o.shift(),o.push(r[0]),a.shift(),a.push(r[1]),bo(c,o,a);return n.pop(),c.push("L",r),c.join("")}function yo(n){if(n.length<4)return oo(n);for(var t,e=[],r=-1,u=n.length,i=[0],o=[0];++r<3;)t=n[r],i.push(t[0]),o.push(t[1]);for(e.push(_o(ws,i)+","+_o(ws,o)),--r;++r<u;)t=n[r],i.shift(),i.push(t[0]),o.shift(),o.push(t[1]),bo(e,i,o);return e.join("")}function xo(n){for(var t,e,r=-1,u=n.length,i=u+4,o=[],a=[];++r<4;)e=n[r%u],o.push(e[0]),a.push(e[1]);for(t=[_o(ws,o),",",_o(ws,a)],--r;++r<i;)e=n[r%u],o.shift(),o.push(e[0]),a.shift(),a.push(e[1]),bo(t,o,a);return t.join("")}function Mo(n,t){var e=n.length-1;if(e)for(var r,u,i=n[0][0],o=n[0][1],a=n[e][0]-i,c=n[e][1]-o,s=-1;++s<=e;)r=n[s],u=s/e,r[0]=t*r[0]+(1-t)*(i+u*a),r[1]=t*r[1]+(1-t)*(o+u*c);return mo(n)}function _o(n,t){return n[0]*t[0]+n[1]*t[1]+n[2]*t[2]+n[3]*t[3]}function bo(n,t,e){n.push("C",_o(_s,t),",",_o(_s,e),",",_o(bs,t),",",_o(bs,e),",",_o(ws,t),",",_o(ws,e))}function wo(n,t){return(t[1]-n[1])/(t[0]-n[0])}function So(n){for(var t=0,e=n.length-1,r=[],u=n[0],i=n[1],o=r[0]=wo(u,i);++t<e;)r[t]=(o+(o=wo(u=i,i=n[t+1])))/2;return r[t]=o,r}function ko(n){for(var t,e,r,u,i=[],o=So(n),a=-1,c=n.length-1;++a<c;)t=wo(n[a],n[a+1]),oa(t)<Aa?o[a]=o[a+1]=0:(e=o[a]/t,r=o[a+1]/t,u=e*e+r*r,u>9&&(u=3*t/Math.sqrt(u),o[a]=u*e,o[a+1]=u*r));for(a=-1;++a<=c;)u=(n[Math.min(c,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),i.push([u||0,o[a]*u||0]);return i}function Eo(n){return n.length<3?oo(n):n[0]+po(n,ko(n))}function Ao(n){for(var t,e,r,u=-1,i=n.length;++u<i;)t=n[u],e=t[0],r=t[1]+ys,t[0]=e*Math.cos(r),t[1]=e*Math.sin(r);return n}function Co(n){function t(t){function c(){v.push("M",a(n(m),f),l,s(n(d.reverse()),f),"Z")}for(var h,g,p,v=[],d=[],m=[],y=-1,x=t.length,M=_t(e),_=_t(u),b=e===r?function(){return g}:_t(r),w=u===i?function(){return p}:_t(i);++y<x;)o.call(this,h=t[y],y)?(d.push([g=+M.call(this,h,y),p=+_.call(this,h,y)]),m.push([+b.call(this,h,y),+w.call(this,h,y)])):d.length&&(c(),d=[],m=[]);return d.length&&c(),v.length?v.join(""):null}var e=br,r=br,u=0,i=wr,o=be,a=oo,c=a.key,s=a,l="L",f=.7;return t.x=function(n){return arguments.length?(e=r=n,t):r},t.x0=function(n){return arguments.length?(e=n,t):e},t.x1=function(n){return arguments.length?(r=n,t):r},t.y=function(n){return arguments.length?(u=i=n,t):i},t.y0=function(n){return arguments.length?(u=n,t):u},t.y1=function(n){return arguments.length?(i=n,t):i},t.defined=function(n){return arguments.length?(o=n,t):o},t.interpolate=function(n){return arguments.length?(c="function"==typeof n?a=n:(a=Ms.get(n)||oo).key,s=a.reverse||a,l=a.closed?"M":"L",t):c},t.tension=function(n){return arguments.length?(f=n,t):f},t}function No(n){return n.radius}function Lo(n){return[n.x,n.y]}function zo(n){return function(){var t=n.apply(this,arguments),e=t[0],r=t[1]+ys;return[e*Math.cos(r),e*Math.sin(r)]}}function qo(){return 64}function To(){return"circle"}function Ro(n){var t=Math.sqrt(n/Sa);return"M0,"+t+"A"+t+","+t+" 0 1,1 0,"+-t+"A"+t+","+t+" 0 1,1 0,"+t+"Z"}function Do(n,t){return fa(n,Ns),n.id=t,n}function Po(n,t,e,r){var u=n.id;return R(n,"function"==typeof e?function(n,i,o){n.__transition__[u].tween.set(t,r(e.call(n,n.__data__,i,o)))}:(e=r(e),function(n){n.__transition__[u].tween.set(t,e)}))}function Uo(n){return null==n&&(n=""),function(){this.textContent=n}}function jo(n,t,e,r){var i=n.__transition__||(n.__transition__={active:0,count:0}),o=i[e];if(!o){var a=r.time;o=i[e]={tween:new u,time:a,ease:r.ease,delay:r.delay,duration:r.duration},++i.count,Xo.timer(function(r){function u(r){return i.active>e?s():(i.active=e,o.event&&o.event.start.call(n,l,t),o.tween.forEach(function(e,r){(r=r.call(n,l,t))&&v.push(r)}),Xo.timer(function(){return p.c=c(r||1)?be:c,1},0,a),void 0)}function c(r){if(i.active!==e)return s();for(var u=r/g,a=f(u),c=v.length;c>0;)v[--c].call(n,a);return u>=1?(o.event&&o.event.end.call(n,l,t),s()):void 0}function s(){return--i.count?delete i[e]:delete n.__transition__,1}var l=n.__data__,f=o.ease,h=o.delay,g=o.duration,p=Ja,v=[];return p.t=h+a,r>=h?u(r-h):(p.c=u,void 0)},0,a)}}function Ho(n,t){n.attr("transform",function(n){return"translate("+t(n)+",0)"})}function Fo(n,t){n.attr("transform",function(n){return"translate(0,"+t(n)+")"})}function Oo(n){return n.toISOString()}function Yo(n,t,e){function r(t){return n(t)}function u(n,e){var r=n[1]-n[0],u=r/e,i=Xo.bisect(js,u); | |
return i==js.length?[t.year,Yi(n.map(function(n){return n/31536e6}),e)[2]]:i?t[u/js[i-1]<js[i]/u?i-1:i]:[Os,Yi(n,e)[2]]}return r.invert=function(t){return Io(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain(t),r):n.domain().map(Io)},r.nice=function(n,t){function e(e){return!isNaN(e)&&!n.range(e,Io(+e+1),t).length}var i=r.domain(),o=Ti(i),a=null==n?u(o,10):"number"==typeof n&&u(o,n);return a&&(n=a[0],t=a[1]),r.domain(Pi(i,t>1?{floor:function(t){for(;e(t=n.floor(t));)t=Io(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=Io(+t+1);return t}}:n))},r.ticks=function(n,t){var e=Ti(r.domain()),i=null==n?u(e,10):"number"==typeof n?u(e,n):!n.range&&[{range:n},t];return i&&(n=i[0],t=i[1]),n.range(e[0],Io(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return Yo(n.copy(),t,e)},Fi(r,n)}function Io(n){return new Date(n)}function Zo(n){return JSON.parse(n.responseText)}function Vo(n){var t=Wo.createRange();return t.selectNode(Wo.body),t.createContextualFragment(n.responseText)}var Xo={version:"3.4.3"};Date.now||(Date.now=function(){return+new Date});var $o=[].slice,Bo=function(n){return $o.call(n)},Wo=document,Jo=Wo.documentElement,Go=window;try{Bo(Jo.childNodes)[0].nodeType}catch(Ko){Bo=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}try{Wo.createElement("div").style.setProperty("opacity",0,"")}catch(Qo){var na=Go.Element.prototype,ta=na.setAttribute,ea=na.setAttributeNS,ra=Go.CSSStyleDeclaration.prototype,ua=ra.setProperty;na.setAttribute=function(n,t){ta.call(this,n,t+"")},na.setAttributeNS=function(n,t,e){ea.call(this,n,t,e+"")},ra.setProperty=function(n,t,e){ua.call(this,n,t+"",e)}}Xo.ascending=function(n,t){return t>n?-1:n>t?1:n>=t?0:0/0},Xo.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:0/0},Xo.min=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u<i&&!(null!=(e=n[u])&&e>=e);)e=void 0;for(;++u<i;)null!=(r=n[u])&&e>r&&(e=r)}else{for(;++u<i&&!(null!=(e=t.call(n,n[u],u))&&e>=e);)e=void 0;for(;++u<i;)null!=(r=t.call(n,n[u],u))&&e>r&&(e=r)}return e},Xo.max=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u<i&&!(null!=(e=n[u])&&e>=e);)e=void 0;for(;++u<i;)null!=(r=n[u])&&r>e&&(e=r)}else{for(;++u<i&&!(null!=(e=t.call(n,n[u],u))&&e>=e);)e=void 0;for(;++u<i;)null!=(r=t.call(n,n[u],u))&&r>e&&(e=r)}return e},Xo.extent=function(n,t){var e,r,u,i=-1,o=n.length;if(1===arguments.length){for(;++i<o&&!(null!=(e=u=n[i])&&e>=e);)e=u=void 0;for(;++i<o;)null!=(r=n[i])&&(e>r&&(e=r),r>u&&(u=r))}else{for(;++i<o&&!(null!=(e=u=t.call(n,n[i],i))&&e>=e);)e=void 0;for(;++i<o;)null!=(r=t.call(n,n[i],i))&&(e>r&&(e=r),r>u&&(u=r))}return[e,u]},Xo.sum=function(n,t){var e,r=0,u=n.length,i=-1;if(1===arguments.length)for(;++i<u;)isNaN(e=+n[i])||(r+=e);else for(;++i<u;)isNaN(e=+t.call(n,n[i],i))||(r+=e);return r},Xo.mean=function(t,e){var r,u=t.length,i=0,o=-1,a=0;if(1===arguments.length)for(;++o<u;)n(r=t[o])&&(i+=(r-i)/++a);else for(;++o<u;)n(r=e.call(t,t[o],o))&&(i+=(r-i)/++a);return a?i:void 0},Xo.quantile=function(n,t){var e=(n.length-1)*t+1,r=Math.floor(e),u=+n[r-1],i=e-r;return i?u+i*(n[r]-u):u},Xo.median=function(t,e){return arguments.length>1&&(t=t.map(e)),t=t.filter(n),t.length?Xo.quantile(t.sort(Xo.ascending),.5):void 0},Xo.bisector=function(n){return{left:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n.call(t,t[i],i)<e?r=i+1:u=i}return r},right:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;e<n.call(t,t[i],i)?u=i:r=i+1}return r}}};var ia=Xo.bisector(function(n){return n});Xo.bisectLeft=ia.left,Xo.bisect=Xo.bisectRight=ia.right,Xo.shuffle=function(n){for(var t,e,r=n.length;r;)e=0|Math.random()*r--,t=n[r],n[r]=n[e],n[e]=t;return n},Xo.permute=function(n,t){for(var e=t.length,r=new Array(e);e--;)r[e]=n[t[e]];return r},Xo.pairs=function(n){for(var t,e=0,r=n.length-1,u=n[0],i=new Array(0>r?0:r);r>e;)i[e]=[t=u,u=n[++e]];return i},Xo.zip=function(){if(!(u=arguments.length))return[];for(var n=-1,e=Xo.min(arguments,t),r=new Array(e);++n<e;)for(var u,i=-1,o=r[n]=new Array(u);++i<u;)o[i]=arguments[i][n];return r},Xo.transpose=function(n){return Xo.zip.apply(Xo,n)},Xo.keys=function(n){var t=[];for(var e in n)t.push(e);return t},Xo.values=function(n){var t=[];for(var e in n)t.push(n[e]);return t},Xo.entries=function(n){var t=[];for(var e in n)t.push({key:e,value:n[e]});return t},Xo.merge=function(n){for(var t,e,r,u=n.length,i=-1,o=0;++i<u;)o+=n[i].length;for(e=new Array(o);--u>=0;)for(r=n[u],t=r.length;--t>=0;)e[--o]=r[t];return e};var oa=Math.abs;Xo.range=function(n,t,r){if(arguments.length<3&&(r=1,arguments.length<2&&(t=n,n=0)),1/0===(t-n)/r)throw new Error("infinite range");var u,i=[],o=e(oa(r)),a=-1;if(n*=o,t*=o,r*=o,0>r)for(;(u=n+r*++a)>t;)i.push(u/o);else for(;(u=n+r*++a)<t;)i.push(u/o);return i},Xo.map=function(n){var t=new u;if(n instanceof u)n.forEach(function(n,e){t.set(n,e)});else for(var e in n)t.set(e,n[e]);return t},r(u,{has:i,get:function(n){return this[aa+n]},set:function(n,t){return this[aa+n]=t},remove:o,keys:a,values:function(){var n=[];return this.forEach(function(t,e){n.push(e)}),n},entries:function(){var n=[];return this.forEach(function(t,e){n.push({key:t,value:e})}),n},size:c,empty:s,forEach:function(n){for(var t in this)t.charCodeAt(0)===ca&&n.call(this,t.substring(1),this[t])}});var aa="\x00",ca=aa.charCodeAt(0);Xo.nest=function(){function n(t,a,c){if(c>=o.length)return r?r.call(i,a):e?a.sort(e):a;for(var s,l,f,h,g=-1,p=a.length,v=o[c++],d=new u;++g<p;)(h=d.get(s=v(l=a[g])))?h.push(l):d.set(s,[l]);return t?(l=t(),f=function(e,r){l.set(e,n(t,r,c))}):(l={},f=function(e,r){l[e]=n(t,r,c)}),d.forEach(f),l}function t(n,e){if(e>=o.length)return n;var r=[],u=a[e++];return n.forEach(function(n,u){r.push({key:n,values:t(u,e)})}),u?r.sort(function(n,t){return u(n.key,t.key)}):r}var e,r,i={},o=[],a=[];return i.map=function(t,e){return n(e,t,0)},i.entries=function(e){return t(n(Xo.map,e,0),0)},i.key=function(n){return o.push(n),i},i.sortKeys=function(n){return a[o.length-1]=n,i},i.sortValues=function(n){return e=n,i},i.rollup=function(n){return r=n,i},i},Xo.set=function(n){var t=new l;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},r(l,{has:i,add:function(n){return this[aa+n]=!0,n},remove:function(n){return n=aa+n,n in this&&delete this[n]},values:a,size:c,empty:s,forEach:function(n){for(var t in this)t.charCodeAt(0)===ca&&n.call(this,t.substring(1))}}),Xo.behavior={},Xo.rebind=function(n,t){for(var e,r=1,u=arguments.length;++r<u;)n[e=arguments[r]]=f(n,t,t[e]);return n};var sa=["webkit","ms","moz","Moz","o","O"];Xo.dispatch=function(){for(var n=new p,t=-1,e=arguments.length;++t<e;)n[arguments[t]]=v(n);return n},p.prototype.on=function(n,t){var e=n.indexOf("."),r="";if(e>=0&&(r=n.substring(e+1),n=n.substring(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},Xo.event=null,Xo.requote=function(n){return n.replace(la,"\\$&")};var la=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,fa={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},ha=function(n,t){return t.querySelector(n)},ga=function(n,t){return t.querySelectorAll(n)},pa=Jo[h(Jo,"matchesSelector")],va=function(n,t){return pa.call(n,t)};"function"==typeof Sizzle&&(ha=function(n,t){return Sizzle(n,t)[0]||null},ga=function(n,t){return Sizzle.uniqueSort(Sizzle(n,t))},va=Sizzle.matchesSelector),Xo.selection=function(){return xa};var da=Xo.selection.prototype=[];da.select=function(n){var t,e,r,u,i=[];n=M(n);for(var o=-1,a=this.length;++o<a;){i.push(t=[]),t.parentNode=(r=this[o]).parentNode;for(var c=-1,s=r.length;++c<s;)(u=r[c])?(t.push(e=n.call(u,u.__data__,c,o)),e&&"__data__"in u&&(e.__data__=u.__data__)):t.push(null)}return x(i)},da.selectAll=function(n){var t,e,r=[];n=_(n);for(var u=-1,i=this.length;++u<i;)for(var o=this[u],a=-1,c=o.length;++a<c;)(e=o[a])&&(r.push(t=Bo(n.call(e,e.__data__,a,u))),t.parentNode=e);return x(r)};var ma={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};Xo.ns={prefix:ma,qualify:function(n){var t=n.indexOf(":"),e=n;return t>=0&&(e=n.substring(0,t),n=n.substring(t+1)),ma.hasOwnProperty(e)?{space:ma[e],local:n}:n}},da.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=Xo.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(b(t,n[t]));return this}return this.each(b(n,t))},da.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=k(n)).length,u=-1;if(t=e.classList){for(;++u<r;)if(!t.contains(n[u]))return!1}else for(t=e.getAttribute("class");++u<r;)if(!S(n[u]).test(t))return!1;return!0}for(t in n)this.each(E(t,n[t]));return this}return this.each(E(n,t))},da.style=function(n,t,e){var r=arguments.length;if(3>r){if("string"!=typeof n){2>r&&(t="");for(e in n)this.each(C(e,n[e],t));return this}if(2>r)return Go.getComputedStyle(this.node(),null).getPropertyValue(n);e=""}return this.each(C(n,t,e))},da.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(N(t,n[t]));return this}return this.each(N(n,t))},da.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},da.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},da.append=function(n){return n=L(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},da.insert=function(n,t){return n=L(n),t=M(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},da.remove=function(){return this.each(function(){var n=this.parentNode;n&&n.removeChild(this)})},da.data=function(n,t){function e(n,e){var r,i,o,a=n.length,f=e.length,h=Math.min(a,f),g=new Array(f),p=new Array(f),v=new Array(a);if(t){var d,m=new u,y=new u,x=[];for(r=-1;++r<a;)d=t.call(i=n[r],i.__data__,r),m.has(d)?v[r]=i:m.set(d,i),x.push(d);for(r=-1;++r<f;)d=t.call(e,o=e[r],r),(i=m.get(d))?(g[r]=i,i.__data__=o):y.has(d)||(p[r]=z(o)),y.set(d,o),m.remove(d);for(r=-1;++r<a;)m.has(x[r])&&(v[r]=n[r])}else{for(r=-1;++r<h;)i=n[r],o=e[r],i?(i.__data__=o,g[r]=i):p[r]=z(o);for(;f>r;++r)p[r]=z(e[r]);for(;a>r;++r)v[r]=n[r]}p.update=g,p.parentNode=g.parentNode=v.parentNode=n.parentNode,c.push(p),s.push(g),l.push(v)}var r,i,o=-1,a=this.length;if(!arguments.length){for(n=new Array(a=(r=this[0]).length);++o<a;)(i=r[o])&&(n[o]=i.__data__);return n}var c=D([]),s=x([]),l=x([]);if("function"==typeof n)for(;++o<a;)e(r=this[o],n.call(r,r.parentNode.__data__,o));else for(;++o<a;)e(r=this[o],n);return s.enter=function(){return c},s.exit=function(){return l},s},da.datum=function(n){return arguments.length?this.property("__data__",n):this.property("__data__")},da.filter=function(n){var t,e,r,u=[];"function"!=typeof n&&(n=q(n));for(var i=0,o=this.length;o>i;i++){u.push(t=[]),t.parentNode=(e=this[i]).parentNode;for(var a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return x(u)},da.order=function(){for(var n=-1,t=this.length;++n<t;)for(var e,r=this[n],u=r.length-1,i=r[u];--u>=0;)(e=r[u])&&(i&&i!==e.nextSibling&&i.parentNode.insertBefore(e,i),i=e);return this},da.sort=function(n){n=T.apply(this,arguments);for(var t=-1,e=this.length;++t<e;)this[t].sort(n);return this.order()},da.each=function(n){return R(this,function(t,e,r){n.call(t,t.__data__,e,r)})},da.call=function(n){var t=Bo(arguments);return n.apply(t[0]=this,t),this},da.empty=function(){return!this.node()},da.node=function(){for(var n=0,t=this.length;t>n;n++)for(var e=this[n],r=0,u=e.length;u>r;r++){var i=e[r];if(i)return i}return null},da.size=function(){var n=0;return this.each(function(){++n}),n};var ya=[];Xo.selection.enter=D,Xo.selection.enter.prototype=ya,ya.append=da.append,ya.empty=da.empty,ya.node=da.node,ya.call=da.call,ya.size=da.size,ya.select=function(n){for(var t,e,r,u,i,o=[],a=-1,c=this.length;++a<c;){r=(u=this[a]).update,o.push(t=[]),t.parentNode=u.parentNode;for(var s=-1,l=u.length;++s<l;)(i=u[s])?(t.push(r[s]=e=n.call(u.parentNode,i.__data__,s,a)),e.__data__=i.__data__):t.push(null)}return x(o)},ya.insert=function(n,t){return arguments.length<2&&(t=P(this)),da.insert.call(this,n,t)},da.transition=function(){for(var n,t,e=ks||++Ls,r=[],u=Es||{time:Date.now(),ease:yu,delay:0,duration:250},i=-1,o=this.length;++i<o;){r.push(n=[]);for(var a=this[i],c=-1,s=a.length;++c<s;)(t=a[c])&&jo(t,c,e,u),n.push(t)}return Do(r,e)},da.interrupt=function(){return this.each(U)},Xo.select=function(n){var t=["string"==typeof n?ha(n,Wo):n];return t.parentNode=Jo,x([t])},Xo.selectAll=function(n){var t=Bo("string"==typeof n?ga(n,Wo):n);return t.parentNode=Jo,x([t])};var xa=Xo.select(Jo);da.on=function(n,t,e){var r=arguments.length;if(3>r){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(j(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(j(n,t,e))};var Ma=Xo.map({mouseenter:"mouseover",mouseleave:"mouseout"});Ma.forEach(function(n){"on"+n in Wo&&Ma.remove(n)});var _a="onselectstart"in Wo?null:h(Jo.style,"userSelect"),ba=0;Xo.mouse=function(n){return Y(n,m())};var wa=/WebKit/.test(Go.navigator.userAgent)?-1:0;Xo.touches=function(n,t){return arguments.length<2&&(t=m().touches),t?Bo(t).map(function(t){var e=Y(n,t);return e.identifier=t.identifier,e}):[]},Xo.behavior.drag=function(){function n(){this.on("mousedown.drag",o).on("touchstart.drag",a)}function t(){return Xo.event.changedTouches[0].identifier}function e(n,t){return Xo.touches(n).filter(function(n){return n.identifier===t})[0]}function r(n,t,e,r){return function(){function o(){var n=t(l,g),e=n[0]-v[0],r=n[1]-v[1];d|=e|r,v=n,f({type:"drag",x:n[0]+c[0],y:n[1]+c[1],dx:e,dy:r})}function a(){m.on(e+"."+p,null).on(r+"."+p,null),y(d&&Xo.event.target===h),f({type:"dragend"})}var c,s=this,l=s.parentNode,f=u.of(s,arguments),h=Xo.event.target,g=n(),p=null==g?"drag":"drag-"+g,v=t(l,g),d=0,m=Xo.select(Go).on(e+"."+p,o).on(r+"."+p,a),y=O();i?(c=i.apply(s,arguments),c=[c.x-v[0],c.y-v[1]]):c=[0,0],f({type:"dragstart"})}}var u=y(n,"drag","dragstart","dragend"),i=null,o=r(g,Xo.mouse,"mousemove","mouseup"),a=r(t,e,"touchmove","touchend");return n.origin=function(t){return arguments.length?(i=t,n):i},Xo.rebind(n,u,"on")};var Sa=Math.PI,ka=2*Sa,Ea=Sa/2,Aa=1e-6,Ca=Aa*Aa,Na=Sa/180,La=180/Sa,za=Math.SQRT2,qa=2,Ta=4;Xo.interpolateZoom=function(n,t){function e(n){var t=n*y;if(m){var e=B(v),o=i/(qa*h)*(e*W(za*t+v)-$(v));return[r+o*s,u+o*l,i*e/B(za*t+v)]}return[r+n*s,u+n*l,i*Math.exp(za*t)]}var r=n[0],u=n[1],i=n[2],o=t[0],a=t[1],c=t[2],s=o-r,l=a-u,f=s*s+l*l,h=Math.sqrt(f),g=(c*c-i*i+Ta*f)/(2*i*qa*h),p=(c*c-i*i-Ta*f)/(2*c*qa*h),v=Math.log(Math.sqrt(g*g+1)-g),d=Math.log(Math.sqrt(p*p+1)-p),m=d-v,y=(m||Math.log(c/i))/za;return e.duration=1e3*y,e},Xo.behavior.zoom=function(){function n(n){n.on(A,s).on(Pa+".zoom",f).on(C,h).on("dblclick.zoom",g).on(L,l)}function t(n){return[(n[0]-S.x)/S.k,(n[1]-S.y)/S.k]}function e(n){return[n[0]*S.k+S.x,n[1]*S.k+S.y]}function r(n){S.k=Math.max(E[0],Math.min(E[1],n))}function u(n,t){t=e(t),S.x+=n[0]-t[0],S.y+=n[1]-t[1]}function i(){_&&_.domain(M.range().map(function(n){return(n-S.x)/S.k}).map(M.invert)),w&&w.domain(b.range().map(function(n){return(n-S.y)/S.k}).map(b.invert))}function o(n){n({type:"zoomstart"})}function a(n){i(),n({type:"zoom",scale:S.k,translate:[S.x,S.y]})}function c(n){n({type:"zoomend"})}function s(){function n(){l=1,u(Xo.mouse(r),g),a(i)}function e(){f.on(C,Go===r?h:null).on(N,null),p(l&&Xo.event.target===s),c(i)}var r=this,i=z.of(r,arguments),s=Xo.event.target,l=0,f=Xo.select(Go).on(C,n).on(N,e),g=t(Xo.mouse(r)),p=O();U.call(r),o(i)}function l(){function n(){var n=Xo.touches(g);return h=S.k,n.forEach(function(n){n.identifier in v&&(v[n.identifier]=t(n))}),n}function e(){for(var t=Xo.event.changedTouches,e=0,i=t.length;i>e;++e)v[t[e].identifier]=null;var o=n(),c=Date.now();if(1===o.length){if(500>c-x){var s=o[0],l=v[s.identifier];r(2*S.k),u(s,l),d(),a(p)}x=c}else if(o.length>1){var s=o[0],f=o[1],h=s[0]-f[0],g=s[1]-f[1];m=h*h+g*g}}function i(){for(var n,t,e,i,o=Xo.touches(g),c=0,s=o.length;s>c;++c,i=null)if(e=o[c],i=v[e.identifier]){if(t)break;n=e,t=i}if(i){var l=(l=e[0]-n[0])*l+(l=e[1]-n[1])*l,f=m&&Math.sqrt(l/m);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+i[0])/2,(t[1]+i[1])/2],r(f*h)}x=null,u(n,t),a(p)}function f(){if(Xo.event.touches.length){for(var t=Xo.event.changedTouches,e=0,r=t.length;r>e;++e)delete v[t[e].identifier];for(var u in v)return void n()}b.on(M,null).on(_,null),w.on(A,s).on(L,l),k(),c(p)}var h,g=this,p=z.of(g,arguments),v={},m=0,y=Xo.event.changedTouches[0].identifier,M="touchmove.zoom-"+y,_="touchend.zoom-"+y,b=Xo.select(Go).on(M,i).on(_,f),w=Xo.select(g).on(A,null).on(L,e),k=O();U.call(g),e(),o(p)}function f(){var n=z.of(this,arguments);m?clearTimeout(m):(U.call(this),o(n)),m=setTimeout(function(){m=null,c(n)},50),d();var e=v||Xo.mouse(this);p||(p=t(e)),r(Math.pow(2,.002*Ra())*S.k),u(e,p),a(n)}function h(){p=null}function g(){var n=z.of(this,arguments),e=Xo.mouse(this),i=t(e),s=Math.log(S.k)/Math.LN2;o(n),r(Math.pow(2,Xo.event.shiftKey?Math.ceil(s)-1:Math.floor(s)+1)),u(e,i),a(n),c(n)}var p,v,m,x,M,_,b,w,S={x:0,y:0,k:1},k=[960,500],E=Da,A="mousedown.zoom",C="mousemove.zoom",N="mouseup.zoom",L="touchstart.zoom",z=y(n,"zoomstart","zoom","zoomend");return n.event=function(n){n.each(function(){var n=z.of(this,arguments),t=S;ks?Xo.select(this).transition().each("start.zoom",function(){S=this.__chart__||{x:0,y:0,k:1},o(n)}).tween("zoom:zoom",function(){var e=k[0],r=k[1],u=e/2,i=r/2,o=Xo.interpolateZoom([(u-S.x)/S.k,(i-S.y)/S.k,e/S.k],[(u-t.x)/t.k,(i-t.y)/t.k,e/t.k]);return function(t){var r=o(t),c=e/r[2];this.__chart__=S={x:u-r[0]*c,y:i-r[1]*c,k:c},a(n)}}).each("end.zoom",function(){c(n)}):(this.__chart__=S,o(n),a(n),c(n))})},n.translate=function(t){return arguments.length?(S={x:+t[0],y:+t[1],k:S.k},i(),n):[S.x,S.y]},n.scale=function(t){return arguments.length?(S={x:S.x,y:S.y,k:+t},i(),n):S.k},n.scaleExtent=function(t){return arguments.length?(E=null==t?Da:[+t[0],+t[1]],n):E},n.center=function(t){return arguments.length?(v=t&&[+t[0],+t[1]],n):v},n.size=function(t){return arguments.length?(k=t&&[+t[0],+t[1]],n):k},n.x=function(t){return arguments.length?(_=t,M=t.copy(),S={x:0,y:0,k:1},n):_},n.y=function(t){return arguments.length?(w=t,b=t.copy(),S={x:0,y:0,k:1},n):w},Xo.rebind(n,z,"on")};var Ra,Da=[0,1/0],Pa="onwheel"in Wo?(Ra=function(){return-Xo.event.deltaY*(Xo.event.deltaMode?120:1)},"wheel"):"onmousewheel"in Wo?(Ra=function(){return Xo.event.wheelDelta},"mousewheel"):(Ra=function(){return-Xo.event.detail},"MozMousePixelScroll");G.prototype.toString=function(){return this.rgb()+""},Xo.hsl=function(n,t,e){return 1===arguments.length?n instanceof Q?K(n.h,n.s,n.l):dt(""+n,mt,K):K(+n,+t,+e)};var Ua=Q.prototype=new G;Ua.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),K(this.h,this.s,this.l/n)},Ua.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),K(this.h,this.s,n*this.l)},Ua.rgb=function(){return nt(this.h,this.s,this.l)},Xo.hcl=function(n,t,e){return 1===arguments.length?n instanceof et?tt(n.h,n.c,n.l):n instanceof it?at(n.l,n.a,n.b):at((n=yt((n=Xo.rgb(n)).r,n.g,n.b)).l,n.a,n.b):tt(+n,+t,+e)};var ja=et.prototype=new G;ja.brighter=function(n){return tt(this.h,this.c,Math.min(100,this.l+Ha*(arguments.length?n:1)))},ja.darker=function(n){return tt(this.h,this.c,Math.max(0,this.l-Ha*(arguments.length?n:1)))},ja.rgb=function(){return rt(this.h,this.c,this.l).rgb()},Xo.lab=function(n,t,e){return 1===arguments.length?n instanceof it?ut(n.l,n.a,n.b):n instanceof et?rt(n.l,n.c,n.h):yt((n=Xo.rgb(n)).r,n.g,n.b):ut(+n,+t,+e)};var Ha=18,Fa=.95047,Oa=1,Ya=1.08883,Ia=it.prototype=new G;Ia.brighter=function(n){return ut(Math.min(100,this.l+Ha*(arguments.length?n:1)),this.a,this.b)},Ia.darker=function(n){return ut(Math.max(0,this.l-Ha*(arguments.length?n:1)),this.a,this.b)},Ia.rgb=function(){return ot(this.l,this.a,this.b)},Xo.rgb=function(n,t,e){return 1===arguments.length?n instanceof pt?gt(n.r,n.g,n.b):dt(""+n,gt,nt):gt(~~n,~~t,~~e)};var Za=pt.prototype=new G;Za.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,u=30;return t||e||r?(t&&u>t&&(t=u),e&&u>e&&(e=u),r&&u>r&&(r=u),gt(Math.min(255,~~(t/n)),Math.min(255,~~(e/n)),Math.min(255,~~(r/n)))):gt(u,u,u)},Za.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),gt(~~(n*this.r),~~(n*this.g),~~(n*this.b))},Za.hsl=function(){return mt(this.r,this.g,this.b)},Za.toString=function(){return"#"+vt(this.r)+vt(this.g)+vt(this.b)};var Va=Xo.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});Va.forEach(function(n,t){Va.set(n,ft(t))}),Xo.functor=_t,Xo.xhr=wt(bt),Xo.dsv=function(n,t){function e(n,e,i){arguments.length<3&&(i=e,e=null);var o=St(n,t,null==e?r:u(e),i);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:u(n)):e},o}function r(n){return e.parse(n.responseText)}function u(n){return function(t){return e.parse(t.responseText,n)}}function i(t){return t.map(o).join(n)}function o(n){return a.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var a=new RegExp('["'+n+"\n]"),c=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var u=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(u(n),e)}:u})},e.parseRows=function(n,t){function e(){if(l>=s)return o;if(u)return u=!1,i;var t=l;if(34===n.charCodeAt(t)){for(var e=t;e++<s;)if(34===n.charCodeAt(e)){if(34!==n.charCodeAt(e+1))break;++e}l=e+2;var r=n.charCodeAt(e+1);return 13===r?(u=!0,10===n.charCodeAt(e+2)&&++l):10===r&&(u=!0),n.substring(t+1,e).replace(/""/g,'"')}for(;s>l;){var r=n.charCodeAt(l++),a=1;if(10===r)u=!0;else if(13===r)u=!0,10===n.charCodeAt(l)&&(++l,++a);else if(r!==c)continue;return n.substring(t,l-a)}return n.substring(t)}for(var r,u,i={},o={},a=[],s=n.length,l=0,f=0;(r=e())!==o;){for(var h=[];r!==i&&r!==o;)h.push(r),r=e();(!t||(h=t(h,f++)))&&a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new l,u=[];return t.forEach(function(n){for(var t in n)r.has(t)||u.push(r.add(t))}),[u.map(o).join(n)].concat(t.map(function(t){return u.map(function(n){return o(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(i).join("\n")},e},Xo.csv=Xo.dsv(",","text/csv"),Xo.tsv=Xo.dsv(" ","text/tab-separated-values");var Xa,$a,Ba,Wa,Ja,Ga=Go[h(Go,"requestAnimationFrame")]||function(n){setTimeout(n,17)};Xo.timer=function(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var u=e+t,i={c:n,t:u,f:!1,n:null};$a?$a.n=i:Xa=i,$a=i,Ba||(Wa=clearTimeout(Wa),Ba=1,Ga(Et))},Xo.timer.flush=function(){At(),Ct()},Xo.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)};var Ka=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Lt);Xo.formatPrefix=function(n,t){var e=0;return n&&(0>n&&(n*=-1),t&&(n=Xo.round(n,Nt(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((0>=e?e+1:e-1)/3)))),Ka[8+e/3]};var Qa=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,nc=Xo.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=Xo.round(n,Nt(n,t))).toFixed(Math.max(0,Math.min(20,Nt(n*(1+1e-15),t))))}}),tc=Xo.time={},ec=Date;Tt.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){rc.setUTCDate.apply(this._,arguments)},setDay:function(){rc.setUTCDay.apply(this._,arguments)},setFullYear:function(){rc.setUTCFullYear.apply(this._,arguments)},setHours:function(){rc.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){rc.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){rc.setUTCMinutes.apply(this._,arguments)},setMonth:function(){rc.setUTCMonth.apply(this._,arguments)},setSeconds:function(){rc.setUTCSeconds.apply(this._,arguments)},setTime:function(){rc.setTime.apply(this._,arguments)}};var rc=Date.prototype;tc.year=Rt(function(n){return n=tc.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),tc.years=tc.year.range,tc.years.utc=tc.year.utc.range,tc.day=Rt(function(n){var t=new ec(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),tc.days=tc.day.range,tc.days.utc=tc.day.utc.range,tc.dayOfYear=function(n){var t=tc.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(n,t){t=7-t;var e=tc[n]=Rt(function(n){return(n=tc.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=tc.year(n).getDay();return Math.floor((tc.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});tc[n+"s"]=e.range,tc[n+"s"].utc=e.utc.range,tc[n+"OfYear"]=function(n){var e=tc.year(n).getDay();return Math.floor((tc.dayOfYear(n)+(e+t)%7)/7)}}),tc.week=tc.sunday,tc.weeks=tc.sunday.range,tc.weeks.utc=tc.sunday.utc.range,tc.weekOfYear=tc.sundayOfYear;var uc={"-":"",_:" ",0:"0"},ic=/^\s*\d+/,oc=/^%/;Xo.locale=function(n){return{numberFormat:zt(n),timeFormat:Pt(n)}};var ac=Xo.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});Xo.format=ac.numberFormat,Xo.geo={},re.prototype={s:0,t:0,add:function(n){ue(n,this.t,cc),ue(cc.s,this.s,this),this.s?this.t+=cc.t:this.s=cc.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cc=new re;Xo.geo.stream=function(n,t){n&&sc.hasOwnProperty(n.type)?sc[n.type](n,t):ie(n,t)};var sc={Feature:function(n,t){ie(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,u=e.length;++r<u;)ie(e[r].geometry,t)}},lc={Sphere:function(n,t){t.sphere()},Point:function(n,t){n=n.coordinates,t.point(n[0],n[1],n[2])},MultiPoint:function(n,t){for(var e=n.coordinates,r=-1,u=e.length;++r<u;)n=e[r],t.point(n[0],n[1],n[2])},LineString:function(n,t){oe(n.coordinates,t,0)},MultiLineString:function(n,t){for(var e=n.coordinates,r=-1,u=e.length;++r<u;)oe(e[r],t,0)},Polygon:function(n,t){ae(n.coordinates,t)},MultiPolygon:function(n,t){for(var e=n.coordinates,r=-1,u=e.length;++r<u;)ae(e[r],t)},GeometryCollection:function(n,t){for(var e=n.geometries,r=-1,u=e.length;++r<u;)ie(e[r],t)}};Xo.geo.area=function(n){return fc=0,Xo.geo.stream(n,gc),fc};var fc,hc=new re,gc={sphere:function(){fc+=4*Sa},point:g,lineStart:g,lineEnd:g,polygonStart:function(){hc.reset(),gc.lineStart=ce},polygonEnd:function(){var n=2*hc;fc+=0>n?4*Sa+n:n,gc.lineStart=gc.lineEnd=gc.point=g}};Xo.geo.bounds=function(){function n(n,t){x.push(M=[l=n,h=n]),f>t&&(f=t),t>g&&(g=t)}function t(t,e){var r=se([t*Na,e*Na]);if(m){var u=fe(m,r),i=[u[1],-u[0],0],o=fe(i,u);pe(o),o=ve(o);var c=t-p,s=c>0?1:-1,v=o[0]*La*s,d=oa(c)>180;if(d^(v>s*p&&s*t>v)){var y=o[1]*La;y>g&&(g=y)}else if(v=(v+360)%360-180,d^(v>s*p&&s*t>v)){var y=-o[1]*La;f>y&&(f=y)}else f>e&&(f=e),e>g&&(g=e);d?p>t?a(l,t)>a(l,h)&&(h=t):a(t,h)>a(l,h)&&(l=t):h>=l?(l>t&&(l=t),t>h&&(h=t)):t>p?a(l,t)>a(l,h)&&(h=t):a(t,h)>a(l,h)&&(l=t)}else n(t,e);m=r,p=t}function e(){_.point=t}function r(){M[0]=l,M[1]=h,_.point=n,m=null}function u(n,e){if(m){var r=n-p;y+=oa(r)>180?r+(r>0?360:-360):r}else v=n,d=e;gc.point(n,e),t(n,e)}function i(){gc.lineStart()}function o(){u(v,d),gc.lineEnd(),oa(y)>Aa&&(l=-(h=180)),M[0]=l,M[1]=h,m=null}function a(n,t){return(t-=n)<0?t+360:t}function c(n,t){return n[0]-t[0]}function s(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:n<t[0]||t[1]<n}var l,f,h,g,p,v,d,m,y,x,M,_={point:n,lineStart:e,lineEnd:r,polygonStart:function(){_.point=u,_.lineStart=i,_.lineEnd=o,y=0,gc.polygonStart()},polygonEnd:function(){gc.polygonEnd(),_.point=n,_.lineStart=e,_.lineEnd=r,0>hc?(l=-(h=180),f=-(g=90)):y>Aa?g=90:-Aa>y&&(f=-90),M[0]=l,M[1]=h | |
}};return function(n){g=h=-(l=f=1/0),x=[],Xo.geo.stream(n,_);var t=x.length;if(t){x.sort(c);for(var e,r=1,u=x[0],i=[u];t>r;++r)e=x[r],s(e[0],u)||s(e[1],u)?(a(u[0],e[1])>a(u[0],u[1])&&(u[1]=e[1]),a(e[0],u[1])>a(u[0],u[1])&&(u[0]=e[0])):i.push(u=e);for(var o,e,p=-1/0,t=i.length-1,r=0,u=i[t];t>=r;u=e,++r)e=i[r],(o=a(u[1],e[0]))>p&&(p=o,l=e[0],h=u[1])}return x=M=null,1/0===l||1/0===f?[[0/0,0/0],[0/0,0/0]]:[[l,f],[h,g]]}}(),Xo.geo.centroid=function(n){pc=vc=dc=mc=yc=xc=Mc=_c=bc=wc=Sc=0,Xo.geo.stream(n,kc);var t=bc,e=wc,r=Sc,u=t*t+e*e+r*r;return Ca>u&&(t=xc,e=Mc,r=_c,Aa>vc&&(t=dc,e=mc,r=yc),u=t*t+e*e+r*r,Ca>u)?[0/0,0/0]:[Math.atan2(e,t)*La,X(r/Math.sqrt(u))*La]};var pc,vc,dc,mc,yc,xc,Mc,_c,bc,wc,Sc,kc={sphere:g,point:me,lineStart:xe,lineEnd:Me,polygonStart:function(){kc.lineStart=_e},polygonEnd:function(){kc.lineStart=xe}},Ec=Ee(be,ze,Te,[-Sa,-Sa/2]),Ac=1e9;Xo.geo.clipExtent=function(){var n,t,e,r,u,i,o={stream:function(n){return u&&(u.valid=!1),u=i(n),u.valid=!0,u},extent:function(a){return arguments.length?(i=Pe(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),u&&(u.valid=!1,u=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},(Xo.geo.conicEqualArea=function(){return je(He)}).raw=He,Xo.geo.albers=function(){return Xo.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},Xo.geo.albersUsa=function(){function n(n){var i=n[0],o=n[1];return t=null,e(i,o),t||(r(i,o),t)||u(i,o),t}var t,e,r,u,i=Xo.geo.albers(),o=Xo.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=Xo.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=i.scale(),e=i.translate(),r=(n[0]-e[0])/t,u=(n[1]-e[1])/t;return(u>=.12&&.234>u&&r>=-.425&&-.214>r?o:u>=.166&&.234>u&&r>=-.214&&-.115>r?a:i).invert(n)},n.stream=function(n){var t=i.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,u){t.point(n,u),e.point(n,u),r.point(n,u)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),a.precision(t),n):i.precision()},n.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),a.scale(t),n.translate(i.translate())):i.scale()},n.translate=function(t){if(!arguments.length)return i.translate();var s=i.scale(),l=+t[0],f=+t[1];return e=i.translate(t).clipExtent([[l-.455*s,f-.238*s],[l+.455*s,f+.238*s]]).stream(c).point,r=o.translate([l-.307*s,f+.201*s]).clipExtent([[l-.425*s+Aa,f+.12*s+Aa],[l-.214*s-Aa,f+.234*s-Aa]]).stream(c).point,u=a.translate([l-.205*s,f+.212*s]).clipExtent([[l-.214*s+Aa,f+.166*s+Aa],[l-.115*s-Aa,f+.234*s-Aa]]).stream(c).point,n},n.scale(1070)};var Cc,Nc,Lc,zc,qc,Tc,Rc={point:g,lineStart:g,lineEnd:g,polygonStart:function(){Nc=0,Rc.lineStart=Fe},polygonEnd:function(){Rc.lineStart=Rc.lineEnd=Rc.point=g,Cc+=oa(Nc/2)}},Dc={point:Oe,lineStart:g,lineEnd:g,polygonStart:g,polygonEnd:g},Pc={point:Ze,lineStart:Ve,lineEnd:Xe,polygonStart:function(){Pc.lineStart=$e},polygonEnd:function(){Pc.point=Ze,Pc.lineStart=Ve,Pc.lineEnd=Xe}};Xo.geo.path=function(){function n(n){return n&&("function"==typeof a&&i.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=u(i)),Xo.geo.stream(n,o)),i.result()}function t(){return o=null,n}var e,r,u,i,o,a=4.5;return n.area=function(n){return Cc=0,Xo.geo.stream(n,u(Rc)),Cc},n.centroid=function(n){return dc=mc=yc=xc=Mc=_c=bc=wc=Sc=0,Xo.geo.stream(n,u(Pc)),Sc?[bc/Sc,wc/Sc]:_c?[xc/_c,Mc/_c]:yc?[dc/yc,mc/yc]:[0/0,0/0]},n.bounds=function(n){return qc=Tc=-(Lc=zc=1/0),Xo.geo.stream(n,u(Dc)),[[Lc,zc],[qc,Tc]]},n.projection=function(n){return arguments.length?(u=(e=n)?n.stream||Je(n):bt,t()):e},n.context=function(n){return arguments.length?(i=null==(r=n)?new Ye:new Be(n),"function"!=typeof a&&i.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(i.pointRadius(+t),+t),n):a},n.projection(Xo.geo.albersUsa()).context(null)},Xo.geo.transform=function(n){return{stream:function(t){var e=new Ge(t);for(var r in n)e[r]=n[r];return e}}},Ge.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},Xo.geo.projection=Qe,Xo.geo.projectionMutator=nr,(Xo.geo.equirectangular=function(){return Qe(er)}).raw=er.invert=er,Xo.geo.rotation=function(n){function t(t){return t=n(t[0]*Na,t[1]*Na),t[0]*=La,t[1]*=La,t}return n=ur(n[0]%360*Na,n[1]*Na,n.length>2?n[2]*Na:0),t.invert=function(t){return t=n.invert(t[0]*Na,t[1]*Na),t[0]*=La,t[1]*=La,t},t},rr.invert=er,Xo.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=ur(-n[0]*Na,-n[1]*Na,0).invert,u=[];return e(null,null,1,{point:function(n,e){u.push(n=t(n,e)),n[0]*=La,n[1]*=La}}),{type:"Polygon",coordinates:[u]}}var t,e,r=[0,0],u=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=cr((t=+r)*Na,u*Na),n):t},n.precision=function(r){return arguments.length?(e=cr(t*Na,(u=+r)*Na),n):u},n.angle(90)},Xo.geo.distance=function(n,t){var e,r=(t[0]-n[0])*Na,u=n[1]*Na,i=t[1]*Na,o=Math.sin(r),a=Math.cos(r),c=Math.sin(u),s=Math.cos(u),l=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((e=f*o)*e+(e=s*l-c*f*a)*e),c*l+s*f*a)},Xo.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return Xo.range(Math.ceil(i/d)*d,u,d).map(h).concat(Xo.range(Math.ceil(s/m)*m,c,m).map(g)).concat(Xo.range(Math.ceil(r/p)*p,e,p).filter(function(n){return oa(n%d)>Aa}).map(l)).concat(Xo.range(Math.ceil(a/v)*v,o,v).filter(function(n){return oa(n%m)>Aa}).map(f))}var e,r,u,i,o,a,c,s,l,f,h,g,p=10,v=p,d=90,m=360,y=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(g(c).slice(1),h(u).reverse().slice(1),g(s).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(i=+t[0][0],u=+t[1][0],s=+t[0][1],c=+t[1][1],i>u&&(t=i,i=u,u=t),s>c&&(t=s,s=c,c=t),n.precision(y)):[[i,s],[u,c]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(y)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],m=+t[1],n):[d,m]},n.minorStep=function(t){return arguments.length?(p=+t[0],v=+t[1],n):[p,v]},n.precision=function(t){return arguments.length?(y=+t,l=lr(a,o,90),f=fr(r,e,y),h=lr(s,c,90),g=fr(i,u,y),n):y},n.majorExtent([[-180,-90+Aa],[180,90-Aa]]).minorExtent([[-180,-80-Aa],[180,80+Aa]])},Xo.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||u.apply(this,arguments)]}}var t,e,r=hr,u=gr;return n.distance=function(){return Xo.geo.distance(t||r.apply(this,arguments),e||u.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(u=t,e="function"==typeof t?null:t,n):u},n.precision=function(){return arguments.length?n:0},n},Xo.geo.interpolate=function(n,t){return pr(n[0]*Na,n[1]*Na,t[0]*Na,t[1]*Na)},Xo.geo.length=function(n){return Uc=0,Xo.geo.stream(n,jc),Uc};var Uc,jc={sphere:g,point:g,lineStart:vr,lineEnd:g,polygonStart:g,polygonEnd:g},Hc=dr(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});(Xo.geo.azimuthalEqualArea=function(){return Qe(Hc)}).raw=Hc;var Fc=dr(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},bt);(Xo.geo.azimuthalEquidistant=function(){return Qe(Fc)}).raw=Fc,(Xo.geo.conicConformal=function(){return je(mr)}).raw=mr,(Xo.geo.conicEquidistant=function(){return je(yr)}).raw=yr;var Oc=dr(function(n){return 1/n},Math.atan);(Xo.geo.gnomonic=function(){return Qe(Oc)}).raw=Oc,xr.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-Ea]},(Xo.geo.mercator=function(){return Mr(xr)}).raw=xr;var Yc=dr(function(){return 1},Math.asin);(Xo.geo.orthographic=function(){return Qe(Yc)}).raw=Yc;var Ic=dr(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});(Xo.geo.stereographic=function(){return Qe(Ic)}).raw=Ic,_r.invert=function(n,t){return[-t,2*Math.atan(Math.exp(n))-Ea]},(Xo.geo.transverseMercator=function(){var n=Mr(_r),t=n.center,e=n.rotate;return n.center=function(n){return n?t([-n[1],n[0]]):(n=t(),[-n[1],n[0]])},n.rotate=function(n){return n?e([n[0],n[1],n.length>2?n[2]+90:90]):(n=e(),[n[0],n[1],n[2]-90])},n.rotate([0,0])}).raw=_r,Xo.geom={},Xo.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,u=_t(e),i=_t(r),o=n.length,a=[],c=[];for(t=0;o>t;t++)a.push([+u.call(this,n[t],t),+i.call(this,n[t],t),t]);for(a.sort(kr),t=0;o>t;t++)c.push([a[t][0],-a[t][1]]);var s=Sr(a),l=Sr(c),f=l[0]===s[0],h=l[l.length-1]===s[s.length-1],g=[];for(t=s.length-1;t>=0;--t)g.push(n[a[s[t]][2]]);for(t=+f;t<l.length-h;++t)g.push(n[a[l[t]][2]]);return g}var e=br,r=wr;return arguments.length?t(n):(t.x=function(n){return arguments.length?(e=n,t):e},t.y=function(n){return arguments.length?(r=n,t):r},t)},Xo.geom.polygon=function(n){return fa(n,Zc),n};var Zc=Xo.geom.polygon.prototype=[];Zc.area=function(){for(var n,t=-1,e=this.length,r=this[e-1],u=0;++t<e;)n=r,r=this[t],u+=n[1]*r[0]-n[0]*r[1];return.5*u},Zc.centroid=function(n){var t,e,r=-1,u=this.length,i=0,o=0,a=this[u-1];for(arguments.length||(n=-1/(6*this.area()));++r<u;)t=a,a=this[r],e=t[0]*a[1]-a[0]*t[1],i+=(t[0]+a[0])*e,o+=(t[1]+a[1])*e;return[i*n,o*n]},Zc.clip=function(n){for(var t,e,r,u,i,o,a=Cr(n),c=-1,s=this.length-Cr(this),l=this[s-1];++c<s;){for(t=n.slice(),n.length=0,u=this[c],i=t[(r=t.length-a)-1],e=-1;++e<r;)o=t[e],Er(o,l,u)?(Er(i,l,u)||n.push(Ar(i,o,l,u)),n.push(o)):Er(i,l,u)&&n.push(Ar(i,o,l,u)),i=o;a&&n.push(n[0]),l=u}return n};var Vc,Xc,$c,Bc,Wc,Jc=[],Gc=[];Pr.prototype.prepare=function(){for(var n,t=this.edges,e=t.length;e--;)n=t[e].edge,n.b&&n.a||t.splice(e,1);return t.sort(jr),t.length},Br.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},Wr.prototype={insert:function(n,t){var e,r,u;if(n){if(t.P=n,t.N=n.N,n.N&&(n.N.P=t),n.N=t,n.R){for(n=n.R;n.L;)n=n.L;n.L=t}else n.R=t;e=n}else this._?(n=Qr(this._),t.P=null,t.N=n,n.P=n.L=t,e=n):(t.P=t.N=null,this._=t,e=null);for(t.L=t.R=null,t.U=e,t.C=!0,n=t;e&&e.C;)r=e.U,e===r.L?(u=r.R,u&&u.C?(e.C=u.C=!1,r.C=!0,n=r):(n===e.R&&(Gr(this,e),n=e,e=n.U),e.C=!1,r.C=!0,Kr(this,r))):(u=r.L,u&&u.C?(e.C=u.C=!1,r.C=!0,n=r):(n===e.L&&(Kr(this,e),n=e,e=n.U),e.C=!1,r.C=!0,Gr(this,r))),e=n.U;this._.C=!1},remove:function(n){n.N&&(n.N.P=n.P),n.P&&(n.P.N=n.N),n.N=n.P=null;var t,e,r,u=n.U,i=n.L,o=n.R;if(e=i?o?Qr(o):i:o,u?u.L===n?u.L=e:u.R=e:this._=e,i&&o?(r=e.C,e.C=n.C,e.L=i,i.U=e,e!==o?(u=e.U,e.U=n.U,n=e.R,u.L=n,e.R=o,o.U=e):(e.U=u,u=e,n=e.R)):(r=n.C,n=e),n&&(n.U=u),!r){if(n&&n.C)return n.C=!1,void 0;do{if(n===this._)break;if(n===u.L){if(t=u.R,t.C&&(t.C=!1,u.C=!0,Gr(this,u),t=u.R),t.L&&t.L.C||t.R&&t.R.C){t.R&&t.R.C||(t.L.C=!1,t.C=!0,Kr(this,t),t=u.R),t.C=u.C,u.C=t.R.C=!1,Gr(this,u),n=this._;break}}else if(t=u.L,t.C&&(t.C=!1,u.C=!0,Kr(this,u),t=u.L),t.L&&t.L.C||t.R&&t.R.C){t.L&&t.L.C||(t.R.C=!1,t.C=!0,Gr(this,t),t=u.L),t.C=u.C,u.C=t.L.C=!1,Kr(this,u),n=this._;break}t.C=!0,n=u,u=u.U}while(!n.C);n&&(n.C=!1)}}},Xo.geom.voronoi=function(n){function t(n){var t=new Array(n.length),r=a[0][0],u=a[0][1],i=a[1][0],o=a[1][1];return nu(e(n),a).cells.forEach(function(e,a){var c=e.edges,s=e.site,l=t[a]=c.length?c.map(function(n){var t=n.start();return[t.x,t.y]}):s.x>=r&&s.x<=i&&s.y>=u&&s.y<=o?[[r,o],[i,o],[i,u],[r,u]]:[];l.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(i(n,t)/Aa)*Aa,y:Math.round(o(n,t)/Aa)*Aa,i:t}})}var r=br,u=wr,i=r,o=u,a=Kc;return n?t(n):(t.links=function(n){return nu(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return nu(e(n)).cells.forEach(function(e,r){for(var u,i,o=e.site,a=e.edges.sort(jr),c=-1,s=a.length,l=a[s-1].edge,f=l.l===o?l.r:l.l;++c<s;)u=l,i=f,l=a[c].edge,f=l.l===o?l.r:l.l,r<i.i&&r<f.i&&eu(o,i,f)<0&&t.push([n[r],n[i.i],n[f.i]])}),t},t.x=function(n){return arguments.length?(i=_t(r=n),t):r},t.y=function(n){return arguments.length?(o=_t(u=n),t):u},t.clipExtent=function(n){return arguments.length?(a=null==n?Kc:n,t):a===Kc?null:a},t.size=function(n){return arguments.length?t.clipExtent(n&&[[0,0],n]):a===Kc?null:a&&a[1]},t)};var Kc=[[-1e6,-1e6],[1e6,1e6]];Xo.geom.delaunay=function(n){return Xo.geom.voronoi().triangles(n)},Xo.geom.quadtree=function(n,t,e,r,u){function i(n){function i(n,t,e,r,u,i,o,a){if(!isNaN(e)&&!isNaN(r))if(n.leaf){var c=n.x,l=n.y;if(null!=c)if(oa(c-e)+oa(l-r)<.01)s(n,t,e,r,u,i,o,a);else{var f=n.point;n.x=n.y=n.point=null,s(n,f,c,l,u,i,o,a),s(n,t,e,r,u,i,o,a)}else n.x=e,n.y=r,n.point=t}else s(n,t,e,r,u,i,o,a)}function s(n,t,e,r,u,o,a,c){var s=.5*(u+a),l=.5*(o+c),f=e>=s,h=r>=l,g=(h<<1)+f;n.leaf=!1,n=n.nodes[g]||(n.nodes[g]=iu()),f?u=s:a=s,h?o=l:c=l,i(n,t,e,r,u,o,a,c)}var l,f,h,g,p,v,d,m,y,x=_t(a),M=_t(c);if(null!=t)v=t,d=e,m=r,y=u;else if(m=y=-(v=d=1/0),f=[],h=[],p=n.length,o)for(g=0;p>g;++g)l=n[g],l.x<v&&(v=l.x),l.y<d&&(d=l.y),l.x>m&&(m=l.x),l.y>y&&(y=l.y),f.push(l.x),h.push(l.y);else for(g=0;p>g;++g){var _=+x(l=n[g],g),b=+M(l,g);v>_&&(v=_),d>b&&(d=b),_>m&&(m=_),b>y&&(y=b),f.push(_),h.push(b)}var w=m-v,S=y-d;w>S?y=d+w:m=v+S;var k=iu();if(k.add=function(n){i(k,n,+x(n,++g),+M(n,g),v,d,m,y)},k.visit=function(n){ou(n,k,v,d,m,y)},g=-1,null==t){for(;++g<p;)i(k,n[g],f[g],h[g],v,d,m,y);--g}else n.forEach(k.add);return f=h=n=l=null,k}var o,a=br,c=wr;return(o=arguments.length)?(a=ru,c=uu,3===o&&(u=e,r=t,e=t=0),i(n)):(i.x=function(n){return arguments.length?(a=n,i):a},i.y=function(n){return arguments.length?(c=n,i):c},i.extent=function(n){return arguments.length?(null==n?t=e=r=u=null:(t=+n[0][0],e=+n[0][1],r=+n[1][0],u=+n[1][1]),i):null==t?null:[[t,e],[r,u]]},i.size=function(n){return arguments.length?(null==n?t=e=r=u=null:(t=e=0,r=+n[0],u=+n[1]),i):null==t?null:[r-t,u-e]},i)},Xo.interpolateRgb=au,Xo.interpolateObject=cu,Xo.interpolateNumber=su,Xo.interpolateString=lu;var Qc=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;Xo.interpolate=fu,Xo.interpolators=[function(n,t){var e=typeof t;return("string"===e?Va.has(t)||/^(#|rgb\(|hsl\()/.test(t)?au:lu:t instanceof G?au:"object"===e?Array.isArray(t)?hu:cu:su)(n,t)}],Xo.interpolateArray=hu;var ns=function(){return bt},ts=Xo.map({linear:ns,poly:xu,quad:function(){return du},cubic:function(){return mu},sin:function(){return Mu},exp:function(){return _u},circle:function(){return bu},elastic:wu,back:Su,bounce:function(){return ku}}),es=Xo.map({"in":bt,out:pu,"in-out":vu,"out-in":function(n){return vu(pu(n))}});Xo.ease=function(n){var t=n.indexOf("-"),e=t>=0?n.substring(0,t):n,r=t>=0?n.substring(t+1):"in";return e=ts.get(e)||ns,r=es.get(r)||bt,gu(r(e.apply(null,$o.call(arguments,1))))},Xo.interpolateHcl=Eu,Xo.interpolateHsl=Au,Xo.interpolateLab=Cu,Xo.interpolateRound=Nu,Xo.transform=function(n){var t=Wo.createElementNS(Xo.ns.prefix.svg,"g");return(Xo.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new Lu(e?e.matrix:rs)})(n)},Lu.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var rs={a:1,b:0,c:0,d:1,e:0,f:0};Xo.interpolateTransform=Ru,Xo.layout={},Xo.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++e<r;)t.push(Uu(n[e]));return t}},Xo.layout.chord=function(){function n(){var n,s,f,h,g,p={},v=[],d=Xo.range(i),m=[];for(e=[],r=[],n=0,h=-1;++h<i;){for(s=0,g=-1;++g<i;)s+=u[h][g];v.push(s),m.push(Xo.range(i)),n+=s}for(o&&d.sort(function(n,t){return o(v[n],v[t])}),a&&m.forEach(function(n,t){n.sort(function(n,e){return a(u[t][n],u[t][e])})}),n=(ka-l*i)/n,s=0,h=-1;++h<i;){for(f=s,g=-1;++g<i;){var y=d[h],x=m[y][g],M=u[y][x],_=s,b=s+=M*n;p[y+"-"+x]={index:y,subindex:x,startAngle:_,endAngle:b,value:M}}r[y]={index:y,startAngle:f,endAngle:s,value:(s-f)/n},s+=l}for(h=-1;++h<i;)for(g=h-1;++g<i;){var w=p[h+"-"+g],S=p[g+"-"+h];(w.value||S.value)&&e.push(w.value<S.value?{source:S,target:w}:{source:w,target:S})}c&&t()}function t(){e.sort(function(n,t){return c((n.source.value+n.target.value)/2,(t.source.value+t.target.value)/2)})}var e,r,u,i,o,a,c,s={},l=0;return s.matrix=function(n){return arguments.length?(i=(u=n)&&u.length,e=r=null,s):u},s.padding=function(n){return arguments.length?(l=n,e=r=null,s):l},s.sortGroups=function(n){return arguments.length?(o=n,e=r=null,s):o},s.sortSubgroups=function(n){return arguments.length?(a=n,e=null,s):a},s.sortChords=function(n){return arguments.length?(c=n,e&&t(),s):c},s.chords=function(){return e||n(),e},s.groups=function(){return r||n(),r},s},Xo.layout.force=function(){function n(n){return function(t,e,r,u){if(t.point!==n){var i=t.cx-n.x,o=t.cy-n.y,a=u-e,c=i*i+o*o;if(c>a*a/d){if(p>c){var s=t.charge/c;n.px-=i*s,n.py-=o*s}return!0}if(t.point&&c&&p>c){var s=t.pointCharge/c;n.px-=i*s,n.py-=o*s}}return!t.charge}}function t(n){n.px=Xo.event.x,n.py=Xo.event.y,a.resume()}var e,r,u,i,o,a={},c=Xo.dispatch("start","tick","end"),s=[1,1],l=.9,f=us,h=is,g=-30,p=os,v=.1,d=.64,m=[],y=[];return a.tick=function(){if((r*=.99)<.005)return c.end({type:"end",alpha:r=0}),!0;var t,e,a,f,h,p,d,x,M,_=m.length,b=y.length;for(e=0;b>e;++e)a=y[e],f=a.source,h=a.target,x=h.x-f.x,M=h.y-f.y,(p=x*x+M*M)&&(p=r*i[e]*((p=Math.sqrt(p))-u[e])/p,x*=p,M*=p,h.x-=x*(d=f.weight/(h.weight+f.weight)),h.y-=M*d,f.x+=x*(d=1-d),f.y+=M*d);if((d=r*v)&&(x=s[0]/2,M=s[1]/2,e=-1,d))for(;++e<_;)a=m[e],a.x+=(x-a.x)*d,a.y+=(M-a.y)*d;if(g)for(Zu(t=Xo.geom.quadtree(m),r,o),e=-1;++e<_;)(a=m[e]).fixed||t.visit(n(a));for(e=-1;++e<_;)a=m[e],a.fixed?(a.x=a.px,a.y=a.py):(a.x-=(a.px-(a.px=a.x))*l,a.y-=(a.py-(a.py=a.y))*l);c.tick({type:"tick",alpha:r})},a.nodes=function(n){return arguments.length?(m=n,a):m},a.links=function(n){return arguments.length?(y=n,a):y},a.size=function(n){return arguments.length?(s=n,a):s},a.linkDistance=function(n){return arguments.length?(f="function"==typeof n?n:+n,a):f},a.distance=a.linkDistance,a.linkStrength=function(n){return arguments.length?(h="function"==typeof n?n:+n,a):h},a.friction=function(n){return arguments.length?(l=+n,a):l},a.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,a):g},a.chargeDistance=function(n){return arguments.length?(p=n*n,a):Math.sqrt(p)},a.gravity=function(n){return arguments.length?(v=+n,a):v},a.theta=function(n){return arguments.length?(d=n*n,a):Math.sqrt(d)},a.alpha=function(n){return arguments.length?(n=+n,r?r=n>0?n:0:n>0&&(c.start({type:"start",alpha:r=n}),Xo.timer(a.tick)),a):r},a.start=function(){function n(n,r){if(!e){for(e=new Array(c),a=0;c>a;++a)e[a]=[];for(a=0;s>a;++a){var u=y[a];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var i,o=e[t],a=-1,s=o.length;++a<s;)if(!isNaN(i=o[a][n]))return i;return Math.random()*r}var t,e,r,c=m.length,l=y.length,p=s[0],v=s[1];for(t=0;c>t;++t)(r=m[t]).index=t,r.weight=0;for(t=0;l>t;++t)r=y[t],"number"==typeof r.source&&(r.source=m[r.source]),"number"==typeof r.target&&(r.target=m[r.target]),++r.source.weight,++r.target.weight;for(t=0;c>t;++t)r=m[t],isNaN(r.x)&&(r.x=n("x",p)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof f)for(t=0;l>t;++t)u[t]=+f.call(this,y[t],t);else for(t=0;l>t;++t)u[t]=f;if(i=[],"function"==typeof h)for(t=0;l>t;++t)i[t]=+h.call(this,y[t],t);else for(t=0;l>t;++t)i[t]=h;if(o=[],"function"==typeof g)for(t=0;c>t;++t)o[t]=+g.call(this,m[t],t);else for(t=0;c>t;++t)o[t]=g;return a.resume()},a.resume=function(){return a.alpha(.1)},a.stop=function(){return a.alpha(0)},a.drag=function(){return e||(e=Xo.behavior.drag().origin(bt).on("dragstart.force",Fu).on("drag.force",t).on("dragend.force",Ou)),arguments.length?(this.on("mouseover.force",Yu).on("mouseout.force",Iu).call(e),void 0):e},Xo.rebind(a,c,"on")};var us=20,is=1,os=1/0;Xo.layout.hierarchy=function(){function n(t,o,a){var c=u.call(e,t,o);if(t.depth=o,a.push(t),c&&(s=c.length)){for(var s,l,f=-1,h=t.children=new Array(s),g=0,p=o+1;++f<s;)l=h[f]=n(c[f],p,a),l.parent=t,g+=l.value;r&&h.sort(r),i&&(t.value=g)}else delete t.children,i&&(t.value=+i.call(e,t,o)||0);return t}function t(n,r){var u=n.children,o=0;if(u&&(a=u.length))for(var a,c=-1,s=r+1;++c<a;)o+=t(u[c],s);else i&&(o=+i.call(e,n,r)||0);return i&&(n.value=o),o}function e(t){var e=[];return n(t,0,e),e}var r=Bu,u=Xu,i=$u;return e.sort=function(n){return arguments.length?(r=n,e):r},e.children=function(n){return arguments.length?(u=n,e):u},e.value=function(n){return arguments.length?(i=n,e):i},e.revalue=function(n){return t(n,0),n},e},Xo.layout.partition=function(){function n(t,e,r,u){var i=t.children;if(t.x=e,t.y=t.depth*u,t.dx=r,t.dy=u,i&&(o=i.length)){var o,a,c,s=-1;for(r=t.value?r/t.value:0;++s<o;)n(a=i[s],e,c=a.value*r,u),e+=c}}function t(n){var e=n.children,r=0;if(e&&(u=e.length))for(var u,i=-1;++i<u;)r=Math.max(r,t(e[i]));return 1+r}function e(e,i){var o=r.call(this,e,i);return n(o[0],0,u[0],u[1]/t(o[0])),o}var r=Xo.layout.hierarchy(),u=[1,1];return e.size=function(n){return arguments.length?(u=n,e):u},Vu(e,r)},Xo.layout.pie=function(){function n(i){var o=i.map(function(e,r){return+t.call(n,e,r)}),a=+("function"==typeof r?r.apply(this,arguments):r),c=(("function"==typeof u?u.apply(this,arguments):u)-a)/Xo.sum(o),s=Xo.range(i.length);null!=e&&s.sort(e===as?function(n,t){return o[t]-o[n]}:function(n,t){return e(i[n],i[t])});var l=[];return s.forEach(function(n){var t;l[n]={data:i[n],value:t=o[n],startAngle:a,endAngle:a+=t*c}}),l}var t=Number,e=as,r=0,u=ka;return n.value=function(e){return arguments.length?(t=e,n):t},n.sort=function(t){return arguments.length?(e=t,n):e},n.startAngle=function(t){return arguments.length?(r=t,n):r},n.endAngle=function(t){return arguments.length?(u=t,n):u},n};var as={};Xo.layout.stack=function(){function n(a,c){var s=a.map(function(e,r){return t.call(n,e,r)}),l=s.map(function(t){return t.map(function(t,e){return[i.call(n,t,e),o.call(n,t,e)]})}),f=e.call(n,l,c);s=Xo.permute(s,f),l=Xo.permute(l,f);var h,g,p,v=r.call(n,l,c),d=s.length,m=s[0].length;for(g=0;m>g;++g)for(u.call(n,s[0][g],p=v[g],l[0][g][1]),h=1;d>h;++h)u.call(n,s[h][g],p+=l[h-1][g][1],l[h][g][1]);return a}var t=bt,e=Qu,r=ni,u=Ku,i=Ju,o=Gu;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:cs.get(t)||Qu,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:ss.get(t)||ni,n):r},n.x=function(t){return arguments.length?(i=t,n):i},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(u=t,n):u},n};var cs=Xo.map({"inside-out":function(n){var t,e,r=n.length,u=n.map(ti),i=n.map(ei),o=Xo.range(r).sort(function(n,t){return u[n]-u[t]}),a=0,c=0,s=[],l=[];for(t=0;r>t;++t)e=o[t],c>a?(a+=i[e],s.push(e)):(c+=i[e],l.push(e));return l.reverse().concat(s)},reverse:function(n){return Xo.range(n.length).reverse()},"default":Qu}),ss=Xo.map({silhouette:function(n){var t,e,r,u=n.length,i=n[0].length,o=[],a=0,c=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;i>e;++e)c[e]=(a-o[e])/2;return c},wiggle:function(n){var t,e,r,u,i,o,a,c,s,l=n.length,f=n[0],h=f.length,g=[];for(g[0]=c=s=0,e=1;h>e;++e){for(t=0,u=0;l>t;++t)u+=n[t][e][1];for(t=0,i=0,a=f[e][0]-f[e-1][0];l>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;i+=o*n[t][e][1]}g[e]=c-=u?i/u*a:0,s>c&&(s=c)}for(e=0;h>e;++e)g[e]-=s;return g},expand:function(n){var t,e,r,u=n.length,i=n[0].length,o=1/u,a=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];if(r)for(t=0;u>t;t++)n[t][e][1]/=r;else for(t=0;u>t;t++)n[t][e][1]=o}for(e=0;i>e;++e)a[e]=0;return a},zero:ni});Xo.layout.histogram=function(){function n(n,i){for(var o,a,c=[],s=n.map(e,this),l=r.call(this,s,i),f=u.call(this,l,s,i),i=-1,h=s.length,g=f.length-1,p=t?1:1/h;++i<g;)o=c[i]=[],o.dx=f[i+1]-(o.x=f[i]),o.y=0;if(g>0)for(i=-1;++i<h;)a=s[i],a>=l[0]&&a<=l[1]&&(o=c[Xo.bisect(f,a,1,g)-1],o.y+=p,o.push(n[i]));return c}var t=!0,e=Number,r=oi,u=ui;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=_t(t),n):r},n.bins=function(t){return arguments.length?(u="number"==typeof t?function(n){return ii(n,t)}:_t(t),n):u},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},Xo.layout.tree=function(){function n(n,i){function o(n,t){var r=n.children,u=n._tree;if(r&&(i=r.length)){for(var i,a,s,l=r[0],f=l,h=-1;++h<i;)s=r[h],o(s,a),f=c(s,a,f),a=s;vi(n);var g=.5*(l._tree.prelim+s._tree.prelim);t?(u.prelim=t._tree.prelim+e(n,t),u.mod=u.prelim-g):u.prelim=g}else t&&(u.prelim=t._tree.prelim+e(n,t))}function a(n,t){n.x=n._tree.prelim+t;var e=n.children;if(e&&(r=e.length)){var r,u=-1;for(t+=n._tree.mod;++u<r;)a(e[u],t)}}function c(n,t,r){if(t){for(var u,i=n,o=n,a=t,c=n.parent.children[0],s=i._tree.mod,l=o._tree.mod,f=a._tree.mod,h=c._tree.mod;a=si(a),i=ci(i),a&&i;)c=ci(c),o=si(o),o._tree.ancestor=n,u=a._tree.prelim+f-i._tree.prelim-s+e(a,i),u>0&&(di(mi(a,n,r),n,u),s+=u,l+=u),f+=a._tree.mod,s+=i._tree.mod,h+=c._tree.mod,l+=o._tree.mod;a&&!si(o)&&(o._tree.thread=a,o._tree.mod+=f-l),i&&!ci(c)&&(c._tree.thread=i,c._tree.mod+=s-h,r=n)}return r}var s=t.call(this,n,i),l=s[0];pi(l,function(n,t){n._tree={ancestor:n,prelim:0,mod:0,change:0,shift:0,number:t?t._tree.number+1:0}}),o(l),a(l,-l._tree.prelim);var f=li(l,hi),h=li(l,fi),g=li(l,gi),p=f.x-e(f,h)/2,v=h.x+e(h,f)/2,d=g.depth||1;return pi(l,u?function(n){n.x*=r[0],n.y=n.depth*r[1],delete n._tree}:function(n){n.x=(n.x-p)/(v-p)*r[0],n.y=n.depth/d*r[1],delete n._tree}),s}var t=Xo.layout.hierarchy().sort(null).value(null),e=ai,r=[1,1],u=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(u=null==(r=t),n):u?null:r},n.nodeSize=function(t){return arguments.length?(u=null!=(r=t),n):u?r:null},Vu(n,t)},Xo.layout.pack=function(){function n(n,i){var o=e.call(this,n,i),a=o[0],c=u[0],s=u[1],l=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,pi(a,function(n){n.r=+l(n.value)}),pi(a,bi),r){var f=r*(t?1:Math.max(2*a.r/c,2*a.r/s))/2;pi(a,function(n){n.r+=f}),pi(a,bi),pi(a,function(n){n.r-=f})}return ki(a,c/2,s/2,t?1:1/Math.max(2*a.r/c,2*a.r/s)),o}var t,e=Xo.layout.hierarchy().sort(yi),r=0,u=[1,1];return n.size=function(t){return arguments.length?(u=t,n):u},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},Vu(n,e)},Xo.layout.cluster=function(){function n(n,i){var o,a=t.call(this,n,i),c=a[0],s=0;pi(c,function(n){var t=n.children;t&&t.length?(n.x=Ci(t),n.y=Ai(t)):(n.x=o?s+=e(n,o):0,n.y=0,o=n)});var l=Ni(c),f=Li(c),h=l.x-e(l,f)/2,g=f.x+e(f,l)/2;return pi(c,u?function(n){n.x=(n.x-c.x)*r[0],n.y=(c.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(g-h)*r[0],n.y=(1-(c.y?n.y/c.y:1))*r[1]}),a}var t=Xo.layout.hierarchy().sort(null).value(null),e=ai,r=[1,1],u=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(u=null==(r=t),n):u?null:r},n.nodeSize=function(t){return arguments.length?(u=null!=(r=t),n):u?r:null},Vu(n,t)},Xo.layout.treemap=function(){function n(n,t){for(var e,r,u=-1,i=n.length;++u<i;)r=(e=n[u]).value*(0>t?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var i=e.children;if(i&&i.length){var o,a,c,s=f(e),l=[],h=i.slice(),p=1/0,v="slice"===g?s.dx:"dice"===g?s.dy:"slice-dice"===g?1&e.depth?s.dy:s.dx:Math.min(s.dx,s.dy);for(n(h,s.dx*s.dy/e.value),l.area=0;(c=h.length)>0;)l.push(o=h[c-1]),l.area+=o.area,"squarify"!==g||(a=r(l,v))<=p?(h.pop(),p=a):(l.area-=l.pop().area,u(l,v,s,!1),v=Math.min(s.dx,s.dy),l.length=l.area=0,p=1/0);l.length&&(u(l,v,s,!0),l.length=l.area=0),i.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var i,o=f(t),a=r.slice(),c=[];for(n(a,o.dx*o.dy/t.value),c.area=0;i=a.pop();)c.push(i),c.area+=i.area,null!=i.z&&(u(c,i.z?o.dx:o.dy,o,!a.length),c.length=c.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,u=0,i=1/0,o=-1,a=n.length;++o<a;)(e=n[o].area)&&(i>e&&(i=e),e>u&&(u=e));return r*=r,t*=t,r?Math.max(t*u*p/r,r/(t*i*p)):1/0}function u(n,t,e,r){var u,i=-1,o=n.length,a=e.x,s=e.y,l=t?c(n.area/t):0;if(t==e.dx){for((r||l>e.dy)&&(l=e.dy);++i<o;)u=n[i],u.x=a,u.y=s,u.dy=l,a+=u.dx=Math.min(e.x+e.dx-a,l?c(u.area/l):0);u.z=!0,u.dx+=e.x+e.dx-a,e.y+=l,e.dy-=l}else{for((r||l>e.dx)&&(l=e.dx);++i<o;)u=n[i],u.x=a,u.y=s,u.dx=l,s+=u.dy=Math.min(e.y+e.dy-s,l?c(u.area/l):0);u.z=!1,u.dy+=e.y+e.dy-s,e.x+=l,e.dx-=l}}function i(r){var u=o||a(r),i=u[0];return i.x=0,i.y=0,i.dx=s[0],i.dy=s[1],o&&a.revalue(i),n([i],i.dx*i.dy/i.value),(o?e:t)(i),h&&(o=u),u}var o,a=Xo.layout.hierarchy(),c=Math.round,s=[1,1],l=null,f=zi,h=!1,g="squarify",p=.5*(1+Math.sqrt(5));return i.size=function(n){return arguments.length?(s=n,i):s},i.padding=function(n){function t(t){var e=n.call(i,t,t.depth);return null==e?zi(t):qi(t,"number"==typeof e?[e,e,e,e]:e)}function e(t){return qi(t,n)}if(!arguments.length)return l;var r;return f=null==(l=n)?zi:"function"==(r=typeof n)?t:"number"===r?(n=[n,n,n,n],e):e,i},i.round=function(n){return arguments.length?(c=n?Math.round:Number,i):c!=Number},i.sticky=function(n){return arguments.length?(h=n,o=null,i):h},i.ratio=function(n){return arguments.length?(p=n,i):p},i.mode=function(n){return arguments.length?(g=n+"",i):g},Vu(i,a)},Xo.random={normal:function(n,t){var e=arguments.length;return 2>e&&(t=1),1>e&&(n=0),function(){var e,r,u;do e=2*Math.random()-1,r=2*Math.random()-1,u=e*e+r*r;while(!u||u>1);return n+t*e*Math.sqrt(-2*Math.log(u)/u)}},logNormal:function(){var n=Xo.random.normal.apply(Xo,arguments);return function(){return Math.exp(n())}},bates:function(n){var t=Xo.random.irwinHall(n);return function(){return t()/n}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t}}},Xo.scale={};var ls={floor:bt,ceil:bt};Xo.scale.linear=function(){return Hi([0,1],[0,1],fu,!1)};var fs={s:1,g:1,p:1,r:1,e:1};Xo.scale.log=function(){return $i(Xo.scale.linear().domain([0,1]),10,!0,[1,10])};var hs=Xo.format(".0e"),gs={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};Xo.scale.pow=function(){return Bi(Xo.scale.linear(),1,[0,1])},Xo.scale.sqrt=function(){return Xo.scale.pow().exponent(.5)},Xo.scale.ordinal=function(){return Ji([],{t:"range",a:[[]]})},Xo.scale.category10=function(){return Xo.scale.ordinal().range(ps)},Xo.scale.category20=function(){return Xo.scale.ordinal().range(vs)},Xo.scale.category20b=function(){return Xo.scale.ordinal().range(ds)},Xo.scale.category20c=function(){return Xo.scale.ordinal().range(ms)};var ps=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(ht),vs=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(ht),ds=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(ht),ms=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(ht);Xo.scale.quantile=function(){return Gi([],[]) | |
},Xo.scale.quantize=function(){return Ki(0,1,[0,1])},Xo.scale.threshold=function(){return Qi([.5],[0,1])},Xo.scale.identity=function(){return no([0,1])},Xo.svg={},Xo.svg.arc=function(){function n(){var n=t.apply(this,arguments),i=e.apply(this,arguments),o=r.apply(this,arguments)+ys,a=u.apply(this,arguments)+ys,c=(o>a&&(c=o,o=a,a=c),a-o),s=Sa>c?"0":"1",l=Math.cos(o),f=Math.sin(o),h=Math.cos(a),g=Math.sin(a);return c>=xs?n?"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"M0,"+n+"A"+n+","+n+" 0 1,0 0,"+-n+"A"+n+","+n+" 0 1,0 0,"+n+"Z":"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"Z":n?"M"+i*l+","+i*f+"A"+i+","+i+" 0 "+s+",1 "+i*h+","+i*g+"L"+n*h+","+n*g+"A"+n+","+n+" 0 "+s+",0 "+n*l+","+n*f+"Z":"M"+i*l+","+i*f+"A"+i+","+i+" 0 "+s+",1 "+i*h+","+i*g+"L0,0"+"Z"}var t=to,e=eo,r=ro,u=uo;return n.innerRadius=function(e){return arguments.length?(t=_t(e),n):t},n.outerRadius=function(t){return arguments.length?(e=_t(t),n):e},n.startAngle=function(t){return arguments.length?(r=_t(t),n):r},n.endAngle=function(t){return arguments.length?(u=_t(t),n):u},n.centroid=function(){var n=(t.apply(this,arguments)+e.apply(this,arguments))/2,i=(r.apply(this,arguments)+u.apply(this,arguments))/2+ys;return[Math.cos(i)*n,Math.sin(i)*n]},n};var ys=-Ea,xs=ka-Aa;Xo.svg.line=function(){return io(bt)};var Ms=Xo.map({linear:oo,"linear-closed":ao,step:co,"step-before":so,"step-after":lo,basis:mo,"basis-open":yo,"basis-closed":xo,bundle:Mo,cardinal:go,"cardinal-open":fo,"cardinal-closed":ho,monotone:Eo});Ms.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var _s=[0,2/3,1/3,0],bs=[0,1/3,2/3,0],ws=[0,1/6,2/3,1/6];Xo.svg.line.radial=function(){var n=io(Ao);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},so.reverse=lo,lo.reverse=so,Xo.svg.area=function(){return Co(bt)},Xo.svg.area.radial=function(){var n=Co(Ao);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},Xo.svg.chord=function(){function n(n,a){var c=t(this,i,n,a),s=t(this,o,n,a);return"M"+c.p0+r(c.r,c.p1,c.a1-c.a0)+(e(c,s)?u(c.r,c.p1,c.r,c.p0):u(c.r,c.p1,s.r,s.p0)+r(s.r,s.p1,s.a1-s.a0)+u(s.r,s.p1,c.r,c.p0))+"Z"}function t(n,t,e,r){var u=t.call(n,e,r),i=a.call(n,u,r),o=c.call(n,u,r)+ys,l=s.call(n,u,r)+ys;return{r:i,a0:o,a1:l,p0:[i*Math.cos(o),i*Math.sin(o)],p1:[i*Math.cos(l),i*Math.sin(l)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>Sa)+",1 "+t}function u(n,t,e,r){return"Q 0,0 "+r}var i=hr,o=gr,a=No,c=ro,s=uo;return n.radius=function(t){return arguments.length?(a=_t(t),n):a},n.source=function(t){return arguments.length?(i=_t(t),n):i},n.target=function(t){return arguments.length?(o=_t(t),n):o},n.startAngle=function(t){return arguments.length?(c=_t(t),n):c},n.endAngle=function(t){return arguments.length?(s=_t(t),n):s},n},Xo.svg.diagonal=function(){function n(n,u){var i=t.call(this,n,u),o=e.call(this,n,u),a=(i.y+o.y)/2,c=[i,{x:i.x,y:a},{x:o.x,y:a},o];return c=c.map(r),"M"+c[0]+"C"+c[1]+" "+c[2]+" "+c[3]}var t=hr,e=gr,r=Lo;return n.source=function(e){return arguments.length?(t=_t(e),n):t},n.target=function(t){return arguments.length?(e=_t(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},Xo.svg.diagonal.radial=function(){var n=Xo.svg.diagonal(),t=Lo,e=n.projection;return n.projection=function(n){return arguments.length?e(zo(t=n)):t},n},Xo.svg.symbol=function(){function n(n,r){return(Ss.get(t.call(this,n,r))||Ro)(e.call(this,n,r))}var t=To,e=qo;return n.type=function(e){return arguments.length?(t=_t(e),n):t},n.size=function(t){return arguments.length?(e=_t(t),n):e},n};var Ss=Xo.map({circle:Ro,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*Cs)),e=t*Cs;return"M0,"+-t+"L"+e+",0"+" 0,"+t+" "+-e+",0"+"Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/As),e=t*As/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/As),e=t*As/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});Xo.svg.symbolTypes=Ss.keys();var ks,Es,As=Math.sqrt(3),Cs=Math.tan(30*Na),Ns=[],Ls=0;Ns.call=da.call,Ns.empty=da.empty,Ns.node=da.node,Ns.size=da.size,Xo.transition=function(n){return arguments.length?ks?n.transition():n:xa.transition()},Xo.transition.prototype=Ns,Ns.select=function(n){var t,e,r,u=this.id,i=[];n=M(n);for(var o=-1,a=this.length;++o<a;){i.push(t=[]);for(var c=this[o],s=-1,l=c.length;++s<l;)(r=c[s])&&(e=n.call(r,r.__data__,s,o))?("__data__"in r&&(e.__data__=r.__data__),jo(e,s,u,r.__transition__[u]),t.push(e)):t.push(null)}return Do(i,u)},Ns.selectAll=function(n){var t,e,r,u,i,o=this.id,a=[];n=_(n);for(var c=-1,s=this.length;++c<s;)for(var l=this[c],f=-1,h=l.length;++f<h;)if(r=l[f]){i=r.__transition__[o],e=n.call(r,r.__data__,f,c),a.push(t=[]);for(var g=-1,p=e.length;++g<p;)(u=e[g])&&jo(u,g,o,i),t.push(u)}return Do(a,o)},Ns.filter=function(n){var t,e,r,u=[];"function"!=typeof n&&(n=q(n));for(var i=0,o=this.length;o>i;i++){u.push(t=[]);for(var e=this[i],a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a,i)&&t.push(r)}return Do(u,this.id)},Ns.tween=function(n,t){var e=this.id;return arguments.length<2?this.node().__transition__[e].tween.get(n):R(this,null==t?function(t){t.__transition__[e].tween.remove(n)}:function(r){r.__transition__[e].tween.set(n,t)})},Ns.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function u(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function i(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?Ru:fu,a=Xo.ns.qualify(n);return Po(this,"attr."+n,t,a.local?i:u)},Ns.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(u));return r&&function(n){this.setAttribute(u,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(u.space,u.local));return r&&function(n){this.setAttributeNS(u.space,u.local,r(n))}}var u=Xo.ns.qualify(n);return this.tween("attr."+n,u.local?r:e)},Ns.style=function(n,t,e){function r(){this.style.removeProperty(n)}function u(t){return null==t?r:(t+="",function(){var r,u=Go.getComputedStyle(this,null).getPropertyValue(n);return u!==t&&(r=fu(u,t),function(t){this.style.setProperty(n,r(t),e)})})}var i=arguments.length;if(3>i){if("string"!=typeof n){2>i&&(t="");for(e in n)this.style(e,n[e],t);return this}e=""}return Po(this,"style."+n,t,u)},Ns.styleTween=function(n,t,e){function r(r,u){var i=t.call(this,r,u,Go.getComputedStyle(this,null).getPropertyValue(n));return i&&function(t){this.style.setProperty(n,i(t),e)}}return arguments.length<3&&(e=""),this.tween("style."+n,r)},Ns.text=function(n){return Po(this,"text",n,Uo)},Ns.remove=function(){return this.each("end.transition",function(){var n;this.__transition__.count<2&&(n=this.parentNode)&&n.removeChild(this)})},Ns.ease=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].ease:("function"!=typeof n&&(n=Xo.ease.apply(Xo,arguments)),R(this,function(e){e.__transition__[t].ease=n}))},Ns.delay=function(n){var t=this.id;return R(this,"function"==typeof n?function(e,r,u){e.__transition__[t].delay=+n.call(e,e.__data__,r,u)}:(n=+n,function(e){e.__transition__[t].delay=n}))},Ns.duration=function(n){var t=this.id;return R(this,"function"==typeof n?function(e,r,u){e.__transition__[t].duration=Math.max(1,n.call(e,e.__data__,r,u))}:(n=Math.max(1,n),function(e){e.__transition__[t].duration=n}))},Ns.each=function(n,t){var e=this.id;if(arguments.length<2){var r=Es,u=ks;ks=e,R(this,function(t,r,u){Es=t.__transition__[e],n.call(t,t.__data__,r,u)}),Es=r,ks=u}else R(this,function(r){var u=r.__transition__[e];(u.event||(u.event=Xo.dispatch("start","end"))).on(n,t)});return this},Ns.transition=function(){for(var n,t,e,r,u=this.id,i=++Ls,o=[],a=0,c=this.length;c>a;a++){o.push(n=[]);for(var t=this[a],s=0,l=t.length;l>s;s++)(e=t[s])&&(r=Object.create(e.__transition__[u]),r.delay+=r.duration,jo(e,s,i,r)),n.push(e)}return Do(o,i)},Xo.svg.axis=function(){function n(n){n.each(function(){var n,s=Xo.select(this),l=this.__chart__||e,f=this.__chart__=e.copy(),h=null==c?f.ticks?f.ticks.apply(f,a):f.domain():c,g=null==t?f.tickFormat?f.tickFormat.apply(f,a):bt:t,p=s.selectAll(".tick").data(h,f),v=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Aa),d=Xo.transition(p.exit()).style("opacity",Aa).remove(),m=Xo.transition(p).style("opacity",1),y=Ri(f),x=s.selectAll(".domain").data([0]),M=(x.enter().append("path").attr("class","domain"),Xo.transition(x));v.append("line"),v.append("text");var _=v.select("line"),b=m.select("line"),w=p.select("text").text(g),S=v.select("text"),k=m.select("text");switch(r){case"bottom":n=Ho,_.attr("y2",u),S.attr("y",Math.max(u,0)+o),b.attr("x2",0).attr("y2",u),k.attr("x",0).attr("y",Math.max(u,0)+o),w.attr("dy",".71em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+i+"V0H"+y[1]+"V"+i);break;case"top":n=Ho,_.attr("y2",-u),S.attr("y",-(Math.max(u,0)+o)),b.attr("x2",0).attr("y2",-u),k.attr("x",0).attr("y",-(Math.max(u,0)+o)),w.attr("dy","0em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+-i+"V0H"+y[1]+"V"+-i);break;case"left":n=Fo,_.attr("x2",-u),S.attr("x",-(Math.max(u,0)+o)),b.attr("x2",-u).attr("y2",0),k.attr("x",-(Math.max(u,0)+o)).attr("y",0),w.attr("dy",".32em").style("text-anchor","end"),M.attr("d","M"+-i+","+y[0]+"H0V"+y[1]+"H"+-i);break;case"right":n=Fo,_.attr("x2",u),S.attr("x",Math.max(u,0)+o),b.attr("x2",u).attr("y2",0),k.attr("x",Math.max(u,0)+o).attr("y",0),w.attr("dy",".32em").style("text-anchor","start"),M.attr("d","M"+i+","+y[0]+"H0V"+y[1]+"H"+i)}if(f.rangeBand){var E=f,A=E.rangeBand()/2;l=f=function(n){return E(n)+A}}else l.rangeBand?l=f:d.call(n,f);v.call(n,l),m.call(n,f)})}var t,e=Xo.scale.linear(),r=zs,u=6,i=6,o=3,a=[10],c=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in qs?t+"":zs,n):r},n.ticks=function(){return arguments.length?(a=arguments,n):a},n.tickValues=function(t){return arguments.length?(c=t,n):c},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(u=+t,i=+arguments[e-1],n):u},n.innerTickSize=function(t){return arguments.length?(u=+t,n):u},n.outerTickSize=function(t){return arguments.length?(i=+t,n):i},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var zs="bottom",qs={top:1,right:1,bottom:1,left:1};Xo.svg.brush=function(){function n(i){i.each(function(){var i=Xo.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",u).on("touchstart.brush",u),o=i.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),i.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=i.selectAll(".resize").data(p,bt);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return Ts[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var l,f=Xo.transition(i),h=Xo.transition(o);c&&(l=Ri(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),e(f)),s&&(l=Ri(s),h.attr("y",l[0]).attr("height",l[1]-l[0]),r(f)),t(f)})}function t(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+l[+/e$/.test(n)]+","+f[+/^s/.test(n)]+")"})}function e(n){n.select(".extent").attr("x",l[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",l[1]-l[0])}function r(n){n.select(".extent").attr("y",f[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",f[1]-f[0])}function u(){function u(){32==Xo.event.keyCode&&(C||(x=null,L[0]-=l[1],L[1]-=f[1],C=2),d())}function p(){32==Xo.event.keyCode&&2==C&&(L[0]+=l[1],L[1]+=f[1],C=0,d())}function v(){var n=Xo.mouse(_),u=!1;M&&(n[0]+=M[0],n[1]+=M[1]),C||(Xo.event.altKey?(x||(x=[(l[0]+l[1])/2,(f[0]+f[1])/2]),L[0]=l[+(n[0]<x[0])],L[1]=f[+(n[1]<x[1])]):x=null),E&&m(n,c,0)&&(e(S),u=!0),A&&m(n,s,1)&&(r(S),u=!0),u&&(t(S),w({type:"brush",mode:C?"move":"resize"}))}function m(n,t,e){var r,u,a=Ri(t),c=a[0],s=a[1],p=L[e],v=e?f:l,d=v[1]-v[0];return C&&(c-=p,s-=d+p),r=(e?g:h)?Math.max(c,Math.min(s,n[e])):n[e],C?u=(r+=p)+d:(x&&(p=Math.max(c,Math.min(s,2*x[e]-r))),r>p?(u=r,r=p):u=p),v[0]!=r||v[1]!=u?(e?o=null:i=null,v[0]=r,v[1]=u,!0):void 0}function y(){v(),S.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),Xo.select("body").style("cursor",null),z.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),N(),w({type:"brushend"})}var x,M,_=this,b=Xo.select(Xo.event.target),w=a.of(_,arguments),S=Xo.select(_),k=b.datum(),E=!/^(n|s)$/.test(k)&&c,A=!/^(e|w)$/.test(k)&&s,C=b.classed("extent"),N=O(),L=Xo.mouse(_),z=Xo.select(Go).on("keydown.brush",u).on("keyup.brush",p);if(Xo.event.changedTouches?z.on("touchmove.brush",v).on("touchend.brush",y):z.on("mousemove.brush",v).on("mouseup.brush",y),S.interrupt().selectAll("*").interrupt(),C)L[0]=l[0]-L[0],L[1]=f[0]-L[1];else if(k){var q=+/w$/.test(k),T=+/^n/.test(k);M=[l[1-q]-L[0],f[1-T]-L[1]],L[0]=l[q],L[1]=f[T]}else Xo.event.altKey&&(x=L.slice());S.style("pointer-events","none").selectAll(".resize").style("display",null),Xo.select("body").style("cursor",b.style("cursor")),w({type:"brushstart"}),v()}var i,o,a=y(n,"brushstart","brush","brushend"),c=null,s=null,l=[0,0],f=[0,0],h=!0,g=!0,p=Rs[0];return n.event=function(n){n.each(function(){var n=a.of(this,arguments),t={x:l,y:f,i:i,j:o},e=this.__chart__||t;this.__chart__=t,ks?Xo.select(this).transition().each("start.brush",function(){i=e.i,o=e.j,l=e.x,f=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=hu(l,t.x),r=hu(f,t.y);return i=o=null,function(u){l=t.x=e(u),f=t.y=r(u),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){i=t.i,o=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(c=t,p=Rs[!c<<1|!s],n):c},n.y=function(t){return arguments.length?(s=t,p=Rs[!c<<1|!s],n):s},n.clamp=function(t){return arguments.length?(c&&s?(h=!!t[0],g=!!t[1]):c?h=!!t:s&&(g=!!t),n):c&&s?[h,g]:c?h:s?g:null},n.extent=function(t){var e,r,u,a,h;return arguments.length?(c&&(e=t[0],r=t[1],s&&(e=e[0],r=r[0]),i=[e,r],c.invert&&(e=c(e),r=c(r)),e>r&&(h=e,e=r,r=h),(e!=l[0]||r!=l[1])&&(l=[e,r])),s&&(u=t[0],a=t[1],c&&(u=u[1],a=a[1]),o=[u,a],s.invert&&(u=s(u),a=s(a)),u>a&&(h=u,u=a,a=h),(u!=f[0]||a!=f[1])&&(f=[u,a])),n):(c&&(i?(e=i[0],r=i[1]):(e=l[0],r=l[1],c.invert&&(e=c.invert(e),r=c.invert(r)),e>r&&(h=e,e=r,r=h))),s&&(o?(u=o[0],a=o[1]):(u=f[0],a=f[1],s.invert&&(u=s.invert(u),a=s.invert(a)),u>a&&(h=u,u=a,a=h))),c&&s?[[e,u],[r,a]]:c?[e,r]:s&&[u,a])},n.clear=function(){return n.empty()||(l=[0,0],f=[0,0],i=o=null),n},n.empty=function(){return!!c&&l[0]==l[1]||!!s&&f[0]==f[1]},Xo.rebind(n,a,"on")};var Ts={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Rs=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Ds=tc.format=ac.timeFormat,Ps=Ds.utc,Us=Ps("%Y-%m-%dT%H:%M:%S.%LZ");Ds.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Oo:Us,Oo.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},Oo.toString=Us.toString,tc.second=Rt(function(n){return new ec(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),tc.seconds=tc.second.range,tc.seconds.utc=tc.second.utc.range,tc.minute=Rt(function(n){return new ec(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),tc.minutes=tc.minute.range,tc.minutes.utc=tc.minute.utc.range,tc.hour=Rt(function(n){var t=n.getTimezoneOffset()/60;return new ec(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),tc.hours=tc.hour.range,tc.hours.utc=tc.hour.utc.range,tc.month=Rt(function(n){return n=tc.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),tc.months=tc.month.range,tc.months.utc=tc.month.utc.range;var js=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Hs=[[tc.second,1],[tc.second,5],[tc.second,15],[tc.second,30],[tc.minute,1],[tc.minute,5],[tc.minute,15],[tc.minute,30],[tc.hour,1],[tc.hour,3],[tc.hour,6],[tc.hour,12],[tc.day,1],[tc.day,2],[tc.week,1],[tc.month,1],[tc.month,3],[tc.year,1]],Fs=Ds.multi([[".%L",function(n){return n.getMilliseconds()}],[":%S",function(n){return n.getSeconds()}],["%I:%M",function(n){return n.getMinutes()}],["%I %p",function(n){return n.getHours()}],["%a %d",function(n){return n.getDay()&&1!=n.getDate()}],["%b %d",function(n){return 1!=n.getDate()}],["%B",function(n){return n.getMonth()}],["%Y",be]]),Os={range:function(n,t,e){return Xo.range(+n,+t,e).map(Io)},floor:bt,ceil:bt};Hs.year=tc.year,tc.scale=function(){return Yo(Xo.scale.linear(),Hs,Fs)};var Ys=Hs.map(function(n){return[n[0].utc,n[1]]}),Is=Ps.multi([[".%L",function(n){return n.getUTCMilliseconds()}],[":%S",function(n){return n.getUTCSeconds()}],["%I:%M",function(n){return n.getUTCMinutes()}],["%I %p",function(n){return n.getUTCHours()}],["%a %d",function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],["%b %d",function(n){return 1!=n.getUTCDate()}],["%B",function(n){return n.getUTCMonth()}],["%Y",be]]);Ys.year=tc.year.utc,tc.scale.utc=function(){return Yo(Xo.scale.linear(),Ys,Is)},Xo.text=wt(function(n){return n.responseText}),Xo.json=function(n,t){return St(n,"application/json",Zo,t)},Xo.html=function(n,t){return St(n,"text/html",Vo,t)},Xo.xml=wt(function(n){return n.responseXML}),"function"==typeof define&&define.amd?define(Xo):"object"==typeof module&&module.exports?module.exports=Xo:this.d3=Xo}(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[{ | |
"portfolio": { | |
"BBY": 120, | |
"INTC": 20 | |
}, | |
"values": [ | |
[1394453255.787, 10000], | |
[1394453256.787, 10875.263578010838], | |
[1394453257.787, 13388.123337699573], | |
[1394453258.787, 8363.81049784513], | |
[1394453259.787, 13188.011875779817], | |
[1394453260.787, 12247.010292227813], | |
[1394453261.787, 10988.889732618067], | |
[1394453262.787, 9063.46140576048], | |
[1394453263.787, 8448.087320554101], | |
[1394453264.787, 10652.037216612722], | |
[1394453265.787, 11075.674130718755], | |
[1394453266.787, 13089.422546248534], | |
[1394453267.787, 9962.238035242475], | |
[1394453268.787, 8881.976201019885], | |
[1394453269.787, 10221.236437139767], | |
[1394453270.787, 12506.631097637943], | |
[1394453271.787, 11676.74809836968], | |
[1394453272.787, 10058.291102664469], | |
[1394453273.788, 12766.768414576629], | |
[1394453274.788, 10483.649299517278], | |
[1394453275.788, 9439.738066102167], | |
[1394453276.788, 10471.367143867155], | |
[1394453277.788, 11040.069591722217], | |
[1394453278.788, 8747.448729525346], | |
[1394453279.788, 13742.16372052967], | |
[1394453280.788, 13922.179837209118], | |
[1394453281.788, 8628.999735622723], | |
[1394453282.788, 12126.70815527406], | |
[1394453283.788, 13633.689271691946], | |
[1394453284.788, 10284.501502525274] | |
], | |
"key": "Player 1" | |
}, { | |
"portfolio": { | |
"BBY": 120, | |
"INTC": 20 | |
}, | |
"values": [ | |
[1394453255.787, 10000], | |
[1394453256.787, 8528.088084222076], | |
[1394453257.787, 8336.045948244731], | |
[1394453258.787, 11379.438377087929], | |
[1394453259.787, 12415.931052225396], | |
[1394453260.787, 9674.855534037337], | |
[1394453261.787, 13506.370905972948], | |
[1394453262.787, 9599.325703807172], | |
[1394453263.787, 10471.782595466362], | |
[1394453264.787, 9494.893511776241], | |
[1394453265.787, 10157.8308637792], | |
[1394453266.787, 12355.739517105303], | |
[1394453267.787, 11152.375299257907], | |
[1394453268.787, 12857.558346384707], | |
[1394453269.787, 9660.56506056787], | |
[1394453270.787, 12335.509283453757], | |
[1394453271.787, 10510.968322433675], | |
[1394453272.787, 13392.302033301781], | |
[1394453273.788, 11385.655928676872], | |
[1394453274.788, 12754.595714548304], | |
[1394453275.788, 8601.75729779299], | |
[1394453276.788, 10648.648256926685], | |
[1394453277.788, 9418.156876481884], | |
[1394453278.788, 12125.687670846211], | |
[1394453279.788, 8702.293981533747], | |
[1394453280.788, 11151.626933196825], | |
[1394453281.788, 13583.337812319303], | |
[1394453282.788, 8427.48474179009], | |
[1394453283.788, 10616.09807999714], | |
[1394453284.788, 13596.255117183668] | |
], | |
"key": "Player 2" | |
}, { | |
"portfolio": { | |
"BBY": 120, | |
"INTC": 20 | |
}, | |
"values": [ | |
[1394453255.787, 10000], | |
[1394453256.787, 12953.800884006181], | |
[1394453257.787, 10008.293423576293], | |
[1394453258.787, 11764.799895259539], | |
[1394453259.787, 13247.201118274184], | |
[1394453260.787, 13966.521231085855], | |
[1394453261.787, 9824.04627191701], | |
[1394453262.787, 13116.43487319773], | |
[1394453263.787, 9330.910440448903], | |
[1394453264.787, 10642.01213347479], | |
[1394453265.787, 13491.12350375464], | |
[1394453266.787, 9377.793863726185], | |
[1394453267.787, 13000.504881900757], | |
[1394453268.787, 8562.704311969692], | |
[1394453269.787, 8008.801857766983], | |
[1394453270.787, 8356.499779302647], | |
[1394453271.787, 13857.553643298841], | |
[1394453272.787, 12260.876469905035], | |
[1394453273.788, 11701.838498796244], | |
[1394453274.788, 13457.712826557192], | |
[1394453275.788, 8129.758693822157], | |
[1394453276.788, 11897.917299167784], | |
[1394453277.788, 13736.977352219374], | |
[1394453278.788, 13542.235169157568], | |
[1394453279.788, 9950.694075805253], | |
[1394453280.788, 9123.813466712165], | |
[1394453281.788, 10484.01924679934], | |
[1394453282.788, 8157.802564094426], | |
[1394453283.788, 9313.534851771352], | |
[1394453284.788, 9398.171664893758] | |
], | |
"key": "Player 3" | |
}, { | |
"portfolio": { | |
"BBY": 120, | |
"INTC": 20 | |
}, | |
"values": [ | |
[1394453255.787, 10000], | |
[1394453256.787, 10634.021377796114], | |
[1394453257.787, 11496.855876697025], | |
[1394453258.787, 12825.48157358331], | |
[1394453259.787, 12410.76602104518], | |
[1394453260.787, 10504.330964499593], | |
[1394453261.787, 9266.370116904278], | |
[1394453262.787, 10525.988828129288], | |
[1394453263.787, 12405.792140609225], | |
[1394453264.787, 9463.220489640376], | |
[1394453265.787, 13920.009002055158], | |
[1394453266.787, 12962.218271659418], | |
[1394453267.787, 10044.309412776616], | |
[1394453268.787, 10122.321454994322], | |
[1394453269.787, 11814.107165150508], | |
[1394453270.787, 10961.157012432195], | |
[1394453271.787, 9166.425741629719], | |
[1394453272.787, 11560.018548704673], | |
[1394453273.788, 11851.654847018264], | |
[1394453274.788, 12242.605811992988], | |
[1394453275.788, 9736.580077501994], | |
[1394453276.788, 8994.770230707909], | |
[1394453277.788, 12890.790286997977], | |
[1394453278.788, 12167.27227189895], | |
[1394453279.788, 10572.050439571363], | |
[1394453280.788, 9544.460023849924], | |
[1394453281.788, 8965.87921982275], | |
[1394453282.788, 9265.387230597828], | |
[1394453283.788, 12508.90203888993], | |
[1394453284.788, 10785.193110100856] | |
], | |
"key": "Player 4" | |
}] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<title>Pythia portfolio comulative chart</title> | |
<script src="./js/jquery-1.9.1.js" type="text/javascript"></script> | |
<script src="./js/d3.min.js" type="text/javascript"></script> | |
<script src="./js/nv.d3.js" type="text/javascript"></script> | |
<link type="text/css" rel="stylesheet" href="./css/nv.d3.css"> | |
<style> | |
#chart { height: 400px; } | |
</style> | |
</head> | |
<body> | |
<div id="tooltipSel"> | |
<input id="defTooltip" name="radTool" type="radio">Use default tooltip</input> | |
<input id="cosTooltip" name="radTool" type="radio">Use costum tooltip</input> | |
</div> | |
<div id="chart"><svg></svg></div> | |
<script type="text/javascript"> | |
changeTooltipToCos(); | |
$("#defTooltip").click(function () { | |
if ($(this).is(':checked')) { | |
console.log("changing to default"); | |
changeTooltipToDef(); | |
} | |
}); | |
$("#cosTooltip").click(function () { | |
if ($(this).is(':checked')) { | |
console.log("changing to costum"); | |
changeTooltipToCos(); | |
} | |
}); | |
function changeTooltipToDef() { | |
d3.json('./data/data.js', function (data) { | |
nv.addGraph(function () { | |
var chart = nv.models.cumulativeLineChart() | |
.x(function (d) { return d[0] }) | |
.y(function (d) { return d[1] }) | |
.color(d3.scale.category10().range()) | |
.useVoronoi(true) | |
.useInteractiveGuideline(true); | |
chart.xAxis | |
.tickFormat(function (d) { | |
return d3.time.format('%X')(new Date(d)) | |
}); | |
chart.yAxis | |
.tickFormat(d3.format(',.1%')); | |
d3.select('#chart svg') | |
.datum(data) | |
.transition().duration(500) | |
.call(chart); | |
nv.utils.windowResize(chart.update); | |
return chart; | |
}); | |
}); | |
} | |
function changeTooltipToCos() { | |
d3.json('./data/data.js', function (data) { | |
nv.addGraph(function () { | |
var chart = nv.models.cumulativeLineChart() | |
.x(function (d) { return d[0] }) | |
.y(function (d) { return d[1] / 100 }) | |
.color(d3.scale.category10().range()) | |
.useInteractiveGuideline(false) | |
.tooltipContent(tp1) | |
.useVoronoi(false); ; | |
chart.xAxis | |
.tickFormat(function (d) { | |
return d3.time.format('%X')(new Date(d)) | |
}); | |
chart.yAxis | |
.tickFormat(d3.format(',.1%')); | |
d3.select('#chart svg') | |
.datum(data) | |
.transition().duration(500) | |
.call(chart); | |
nv.utils.windowResize(chart.update); | |
return chart; | |
}); | |
}); | |
} | |
var tp1 = function (key, x, y, e, graph) { | |
var portStr = '<h3>Portfolio content</h3>'; | |
for (var item in e.series.portfolio) { | |
portStr += '<p>' + item +': ' + e.series.portfolio[item] + '</p>' | |
} | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' on ' + x + '</p>' + | |
'<p>Current account value: ' + numberWithCommas(e.point[1].toFixed(0)) + '$</p>' + | |
portStr; | |
}; | |
var tp2 = function (key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>!!' + y + '!!</p>' + | |
'<p>Likes: ' + e.point.likes + '</p>'; | |
}; | |
function numberWithCommas(x) { | |
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); | |
} | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* jQuery JavaScript Library v1.9.1 | |
* http://jquery.com/ | |
* | |
* Includes Sizzle.js | |
* http://sizzlejs.com/ | |
* | |
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors | |
* Released under the MIT license | |
* http://jquery.org/license | |
* | |
* Date: 2013-2-4 | |
*/ | |
(function( window, undefined ) { | |
// Can't do this because several apps including ASP.NET trace | |
// the stack via arguments.caller.callee and Firefox dies if | |
// you try to trace through "use strict" call chains. (#13335) | |
// Support: Firefox 18+ | |
//"use strict"; | |
var | |
// The deferred used on DOM ready | |
readyList, | |
// A central reference to the root jQuery(document) | |
rootjQuery, | |
// Support: IE<9 | |
// For `typeof node.method` instead of `node.method !== undefined` | |
core_strundefined = typeof undefined, | |
// Use the correct document accordingly with window argument (sandbox) | |
document = window.document, | |
location = window.location, | |
// Map over jQuery in case of overwrite | |
_jQuery = window.jQuery, | |
// Map over the $ in case of overwrite | |
_$ = window.$, | |
// [[Class]] -> type pairs | |
class2type = {}, | |
// List of deleted data cache ids, so we can reuse them | |
core_deletedIds = [], | |
core_version = "1.9.1", | |
// Save a reference to some core methods | |
core_concat = core_deletedIds.concat, | |
core_push = core_deletedIds.push, | |
core_slice = core_deletedIds.slice, | |
core_indexOf = core_deletedIds.indexOf, | |
core_toString = class2type.toString, | |
core_hasOwn = class2type.hasOwnProperty, | |
core_trim = core_version.trim, | |
// Define a local copy of jQuery | |
jQuery = function( selector, context ) { | |
// The jQuery object is actually just the init constructor 'enhanced' | |
return new jQuery.fn.init( selector, context, rootjQuery ); | |
}, | |
// Used for matching numbers | |
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, | |
// Used for splitting on whitespace | |
core_rnotwhite = /\S+/g, | |
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) | |
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, | |
// A simple way to check for HTML strings | |
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521) | |
// Strict HTML recognition (#11290: must start with <) | |
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, | |
// Match a standalone tag | |
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, | |
// JSON RegExp | |
rvalidchars = /^[\],:{}\s]*$/, | |
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, | |
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, | |
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, | |
// Matches dashed string for camelizing | |
rmsPrefix = /^-ms-/, | |
rdashAlpha = /-([\da-z])/gi, | |
// Used by jQuery.camelCase as callback to replace() | |
fcamelCase = function( all, letter ) { | |
return letter.toUpperCase(); | |
}, | |
// The ready event handler | |
completed = function( event ) { | |
// readyState === "complete" is good enough for us to call the dom ready in oldIE | |
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { | |
detach(); | |
jQuery.ready(); | |
} | |
}, | |
// Clean-up method for dom ready events | |
detach = function() { | |
if ( document.addEventListener ) { | |
document.removeEventListener( "DOMContentLoaded", completed, false ); | |
window.removeEventListener( "load", completed, false ); | |
} else { | |
document.detachEvent( "onreadystatechange", completed ); | |
window.detachEvent( "onload", completed ); | |
} | |
}; | |
jQuery.fn = jQuery.prototype = { | |
// The current version of jQuery being used | |
jquery: core_version, | |
constructor: jQuery, | |
init: function( selector, context, rootjQuery ) { | |
var match, elem; | |
// HANDLE: $(""), $(null), $(undefined), $(false) | |
if ( !selector ) { | |
return this; | |
} | |
// Handle HTML strings | |
if ( typeof selector === "string" ) { | |
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { | |
// Assume that strings that start and end with <> are HTML and skip the regex check | |
match = [ null, selector, null ]; | |
} else { | |
match = rquickExpr.exec( selector ); | |
} | |
// Match html or make sure no context is specified for #id | |
if ( match && (match[1] || !context) ) { | |
// HANDLE: $(html) -> $(array) | |
if ( match[1] ) { | |
context = context instanceof jQuery ? context[0] : context; | |
// scripts is true for back-compat | |
jQuery.merge( this, jQuery.parseHTML( | |
match[1], | |
context && context.nodeType ? context.ownerDocument || context : document, | |
true | |
) ); | |
// HANDLE: $(html, props) | |
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { | |
for ( match in context ) { | |
// Properties of context are called as methods if possible | |
if ( jQuery.isFunction( this[ match ] ) ) { | |
this[ match ]( context[ match ] ); | |
// ...and otherwise set as attributes | |
} else { | |
this.attr( match, context[ match ] ); | |
} | |
} | |
} | |
return this; | |
// HANDLE: $(#id) | |
} else { | |
elem = document.getElementById( match[2] ); | |
// Check parentNode to catch when Blackberry 4.6 returns | |
// nodes that are no longer in the document #6963 | |
if ( elem && elem.parentNode ) { | |
// Handle the case where IE and Opera return items | |
// by name instead of ID | |
if ( elem.id !== match[2] ) { | |
return rootjQuery.find( selector ); | |
} | |
// Otherwise, we inject the element directly into the jQuery object | |
this.length = 1; | |
this[0] = elem; | |
} | |
this.context = document; | |
this.selector = selector; | |
return this; | |
} | |
// HANDLE: $(expr, $(...)) | |
} else if ( !context || context.jquery ) { | |
return ( context || rootjQuery ).find( selector ); | |
// HANDLE: $(expr, context) | |
// (which is just equivalent to: $(context).find(expr) | |
} else { | |
return this.constructor( context ).find( selector ); | |
} | |
// HANDLE: $(DOMElement) | |
} else if ( selector.nodeType ) { | |
this.context = this[0] = selector; | |
this.length = 1; | |
return this; | |
// HANDLE: $(function) | |
// Shortcut for document ready | |
} else if ( jQuery.isFunction( selector ) ) { | |
return rootjQuery.ready( selector ); | |
} | |
if ( selector.selector !== undefined ) { | |
this.selector = selector.selector; | |
this.context = selector.context; | |
} | |
return jQuery.makeArray( selector, this ); | |
}, | |
// Start with an empty selector | |
selector: "", | |
// The default length of a jQuery object is 0 | |
length: 0, | |
// The number of elements contained in the matched element set | |
size: function() { | |
return this.length; | |
}, | |
toArray: function() { | |
return core_slice.call( this ); | |
}, | |
// Get the Nth element in the matched element set OR | |
// Get the whole matched element set as a clean array | |
get: function( num ) { | |
return num == null ? | |
// Return a 'clean' array | |
this.toArray() : | |
// Return just the object | |
( num < 0 ? this[ this.length + num ] : this[ num ] ); | |
}, | |
// Take an array of elements and push it onto the stack | |
// (returning the new matched element set) | |
pushStack: function( elems ) { | |
// Build a new jQuery matched element set | |
var ret = jQuery.merge( this.constructor(), elems ); | |
// Add the old object onto the stack (as a reference) | |
ret.prevObject = this; | |
ret.context = this.context; | |
// Return the newly-formed element set | |
return ret; | |
}, | |
// Execute a callback for every element in the matched set. | |
// (You can seed the arguments with an array of args, but this is | |
// only used internally.) | |
each: function( callback, args ) { | |
return jQuery.each( this, callback, args ); | |
}, | |
ready: function( fn ) { | |
// Add the callback | |
jQuery.ready.promise().done( fn ); | |
return this; | |
}, | |
slice: function() { | |
return this.pushStack( core_slice.apply( this, arguments ) ); | |
}, | |
first: function() { | |
return this.eq( 0 ); | |
}, | |
last: function() { | |
return this.eq( -1 ); | |
}, | |
eq: function( i ) { | |
var len = this.length, | |
j = +i + ( i < 0 ? len : 0 ); | |
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); | |
}, | |
map: function( callback ) { | |
return this.pushStack( jQuery.map(this, function( elem, i ) { | |
return callback.call( elem, i, elem ); | |
})); | |
}, | |
end: function() { | |
return this.prevObject || this.constructor(null); | |
}, | |
// For internal use only. | |
// Behaves like an Array's method, not like a jQuery method. | |
push: core_push, | |
sort: [].sort, | |
splice: [].splice | |
}; | |
// Give the init function the jQuery prototype for later instantiation | |
jQuery.fn.init.prototype = jQuery.fn; | |
jQuery.extend = jQuery.fn.extend = function() { | |
var src, copyIsArray, copy, name, options, clone, | |
target = arguments[0] || {}, | |
i = 1, | |
length = arguments.length, | |
deep = false; | |
// Handle a deep copy situation | |
if ( typeof target === "boolean" ) { | |
deep = target; | |
target = arguments[1] || {}; | |
// skip the boolean and the target | |
i = 2; | |
} | |
// Handle case when target is a string or something (possible in deep copy) | |
if ( typeof target !== "object" && !jQuery.isFunction(target) ) { | |
target = {}; | |
} | |
// extend jQuery itself if only one argument is passed | |
if ( length === i ) { | |
target = this; | |
--i; | |
} | |
for ( ; i < length; i++ ) { | |
// Only deal with non-null/undefined values | |
if ( (options = arguments[ i ]) != null ) { | |
// Extend the base object | |
for ( name in options ) { | |
src = target[ name ]; | |
copy = options[ name ]; | |
// Prevent never-ending loop | |
if ( target === copy ) { | |
continue; | |
} | |
// Recurse if we're merging plain objects or arrays | |
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { | |
if ( copyIsArray ) { | |
copyIsArray = false; | |
clone = src && jQuery.isArray(src) ? src : []; | |
} else { | |
clone = src && jQuery.isPlainObject(src) ? src : {}; | |
} | |
// Never move original objects, clone them | |
target[ name ] = jQuery.extend( deep, clone, copy ); | |
// Don't bring in undefined values | |
} else if ( copy !== undefined ) { | |
target[ name ] = copy; | |
} | |
} | |
} | |
} | |
// Return the modified object | |
return target; | |
}; | |
jQuery.extend({ | |
noConflict: function( deep ) { | |
if ( window.$ === jQuery ) { | |
window.$ = _$; | |
} | |
if ( deep && window.jQuery === jQuery ) { | |
window.jQuery = _jQuery; | |
} | |
return jQuery; | |
}, | |
// Is the DOM ready to be used? Set to true once it occurs. | |
isReady: false, | |
// A counter to track how many items to wait for before | |
// the ready event fires. See #6781 | |
readyWait: 1, | |
// Hold (or release) the ready event | |
holdReady: function( hold ) { | |
if ( hold ) { | |
jQuery.readyWait++; | |
} else { | |
jQuery.ready( true ); | |
} | |
}, | |
// Handle when the DOM is ready | |
ready: function( wait ) { | |
// Abort if there are pending holds or we're already ready | |
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { | |
return; | |
} | |
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). | |
if ( !document.body ) { | |
return setTimeout( jQuery.ready ); | |
} | |
// Remember that the DOM is ready | |
jQuery.isReady = true; | |
// If a normal DOM Ready event fired, decrement, and wait if need be | |
if ( wait !== true && --jQuery.readyWait > 0 ) { | |
return; | |
} | |
// If there are functions bound, to execute | |
readyList.resolveWith( document, [ jQuery ] ); | |
// Trigger any bound ready events | |
if ( jQuery.fn.trigger ) { | |
jQuery( document ).trigger("ready").off("ready"); | |
} | |
}, | |
// See test/unit/core.js for details concerning isFunction. | |
// Since version 1.3, DOM methods and functions like alert | |
// aren't supported. They return false on IE (#2968). | |
isFunction: function( obj ) { | |
return jQuery.type(obj) === "function"; | |
}, | |
isArray: Array.isArray || function( obj ) { | |
return jQuery.type(obj) === "array"; | |
}, | |
isWindow: function( obj ) { | |
return obj != null && obj == obj.window; | |
}, | |
isNumeric: function( obj ) { | |
return !isNaN( parseFloat(obj) ) && isFinite( obj ); | |
}, | |
type: function( obj ) { | |
if ( obj == null ) { | |
return String( obj ); | |
} | |
return typeof obj === "object" || typeof obj === "function" ? | |
class2type[ core_toString.call(obj) ] || "object" : | |
typeof obj; | |
}, | |
isPlainObject: function( obj ) { | |
// Must be an Object. | |
// Because of IE, we also have to check the presence of the constructor property. | |
// Make sure that DOM nodes and window objects don't pass through, as well | |
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { | |
return false; | |
} | |
try { | |
// Not own constructor property must be Object | |
if ( obj.constructor && | |
!core_hasOwn.call(obj, "constructor") && | |
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { | |
return false; | |
} | |
} catch ( e ) { | |
// IE8,9 Will throw exceptions on certain host objects #9897 | |
return false; | |
} | |
// Own properties are enumerated firstly, so to speed up, | |
// if last one is own, then all properties are own. | |
var key; | |
for ( key in obj ) {} | |
return key === undefined || core_hasOwn.call( obj, key ); | |
}, | |
isEmptyObject: function( obj ) { | |
var name; | |
for ( name in obj ) { | |
return false; | |
} | |
return true; | |
}, | |
error: function( msg ) { | |
throw new Error( msg ); | |
}, | |
// data: string of html | |
// context (optional): If specified, the fragment will be created in this context, defaults to document | |
// keepScripts (optional): If true, will include scripts passed in the html string | |
parseHTML: function( data, context, keepScripts ) { | |
if ( !data || typeof data !== "string" ) { | |
return null; | |
} | |
if ( typeof context === "boolean" ) { | |
keepScripts = context; | |
context = false; | |
} | |
context = context || document; | |
var parsed = rsingleTag.exec( data ), | |
scripts = !keepScripts && []; | |
// Single tag | |
if ( parsed ) { | |
return [ context.createElement( parsed[1] ) ]; | |
} | |
parsed = jQuery.buildFragment( [ data ], context, scripts ); | |
if ( scripts ) { | |
jQuery( scripts ).remove(); | |
} | |
return jQuery.merge( [], parsed.childNodes ); | |
}, | |
parseJSON: function( data ) { | |
// Attempt to parse using the native JSON parser first | |
if ( window.JSON && window.JSON.parse ) { | |
return window.JSON.parse( data ); | |
} | |
if ( data === null ) { | |
return data; | |
} | |
if ( typeof data === "string" ) { | |
// Make sure leading/trailing whitespace is removed (IE can't handle it) | |
data = jQuery.trim( data ); | |
if ( data ) { | |
// Make sure the incoming data is actual JSON | |
// Logic borrowed from http://json.org/json2.js | |
if ( rvalidchars.test( data.replace( rvalidescape, "@" ) | |
.replace( rvalidtokens, "]" ) | |
.replace( rvalidbraces, "")) ) { | |
return ( new Function( "return " + data ) )(); | |
} | |
} | |
} | |
jQuery.error( "Invalid JSON: " + data ); | |
}, | |
// Cross-browser xml parsing | |
parseXML: function( data ) { | |
var xml, tmp; | |
if ( !data || typeof data !== "string" ) { | |
return null; | |
} | |
try { | |
if ( window.DOMParser ) { // Standard | |
tmp = new DOMParser(); | |
xml = tmp.parseFromString( data , "text/xml" ); | |
} else { // IE | |
xml = new ActiveXObject( "Microsoft.XMLDOM" ); | |
xml.async = "false"; | |
xml.loadXML( data ); | |
} | |
} catch( e ) { | |
xml = undefined; | |
} | |
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { | |
jQuery.error( "Invalid XML: " + data ); | |
} | |
return xml; | |
}, | |
noop: function() {}, | |
// Evaluates a script in a global context | |
// Workarounds based on findings by Jim Driscoll | |
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context | |
globalEval: function( data ) { | |
if ( data && jQuery.trim( data ) ) { | |
// We use execScript on Internet Explorer | |
// We use an anonymous function so that context is window | |
// rather than jQuery in Firefox | |
( window.execScript || function( data ) { | |
window[ "eval" ].call( window, data ); | |
} )( data ); | |
} | |
}, | |
// Convert dashed to camelCase; used by the css and data modules | |
// Microsoft forgot to hump their vendor prefix (#9572) | |
camelCase: function( string ) { | |
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); | |
}, | |
nodeName: function( elem, name ) { | |
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); | |
}, | |
// args is for internal usage only | |
each: function( obj, callback, args ) { | |
var value, | |
i = 0, | |
length = obj.length, | |
isArray = isArraylike( obj ); | |
if ( args ) { | |
if ( isArray ) { | |
for ( ; i < length; i++ ) { | |
value = callback.apply( obj[ i ], args ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} else { | |
for ( i in obj ) { | |
value = callback.apply( obj[ i ], args ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} | |
// A special, fast, case for the most common use of each | |
} else { | |
if ( isArray ) { | |
for ( ; i < length; i++ ) { | |
value = callback.call( obj[ i ], i, obj[ i ] ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} else { | |
for ( i in obj ) { | |
value = callback.call( obj[ i ], i, obj[ i ] ); | |
if ( value === false ) { | |
break; | |
} | |
} | |
} | |
} | |
return obj; | |
}, | |
// Use native String.trim function wherever possible | |
trim: core_trim && !core_trim.call("\uFEFF\xA0") ? | |
function( text ) { | |
return text == null ? | |
"" : | |
core_trim.call( text ); | |
} : | |
// Otherwise use our own trimming functionality | |
function( text ) { | |
return text == null ? | |
"" : | |
( text + "" ).replace( rtrim, "" ); | |
}, | |
// results is for internal usage only | |
makeArray: function( arr, results ) { | |
var ret = results || []; | |
if ( arr != null ) { | |
if ( isArraylike( Object(arr) ) ) { | |
jQuery.merge( ret, | |
typeof arr === "string" ? | |
[ arr ] : arr | |
); | |
} else { | |
core_push.call( ret, arr ); | |
} | |
} | |
return ret; | |
}, | |
inArray: function( elem, arr, i ) { | |
var len; | |
if ( arr ) { | |
if ( core_indexOf ) { | |
return core_indexOf.call( arr, elem, i ); | |
} | |
len = arr.length; | |
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; | |
for ( ; i < len; i++ ) { | |
// Skip accessing in sparse arrays | |
if ( i in arr && arr[ i ] === elem ) { | |
return i; | |
} | |
} | |
} | |
return -1; | |
}, | |
merge: function( first, second ) { | |
var l = second.length, | |
i = first.length, | |
j = 0; | |
if ( typeof l === "number" ) { | |
for ( ; j < l; j++ ) { | |
first[ i++ ] = second[ j ]; | |
} | |
} else { | |
while ( second[j] !== undefined ) { | |
first[ i++ ] = second[ j++ ]; | |
} | |
} | |
first.length = i; | |
return first; | |
}, | |
grep: function( elems, callback, inv ) { | |
var retVal, | |
ret = [], | |
i = 0, | |
length = elems.length; | |
inv = !!inv; | |
// Go through the array, only saving the items | |
// that pass the validator function | |
for ( ; i < length; i++ ) { | |
retVal = !!callback( elems[ i ], i ); | |
if ( inv !== retVal ) { | |
ret.push( elems[ i ] ); | |
} | |
} | |
return ret; | |
}, | |
// arg is for internal usage only | |
map: function( elems, callback, arg ) { | |
var value, | |
i = 0, | |
length = elems.length, | |
isArray = isArraylike( elems ), | |
ret = []; | |
// Go through the array, translating each of the items to their | |
if ( isArray ) { | |
for ( ; i < length; i++ ) { | |
value = callback( elems[ i ], i, arg ); | |
if ( value != null ) { | |
ret[ ret.length ] = value; | |
} | |
} | |
// Go through every key on the object, | |
} else { | |
for ( i in elems ) { | |
value = callback( elems[ i ], i, arg ); | |
if ( value != null ) { | |
ret[ ret.length ] = value; | |
} | |
} | |
} | |
// Flatten any nested arrays | |
return core_concat.apply( [], ret ); | |
}, | |
// A global GUID counter for objects | |
guid: 1, | |
// Bind a function to a context, optionally partially applying any | |
// arguments. | |
proxy: function( fn, context ) { | |
var args, proxy, tmp; | |
if ( typeof context === "string" ) { | |
tmp = fn[ context ]; | |
context = fn; | |
fn = tmp; | |
} | |
// Quick check to determine if target is callable, in the spec | |
// this throws a TypeError, but we will just return undefined. | |
if ( !jQuery.isFunction( fn ) ) { | |
return undefined; | |
} | |
// Simulated bind | |
args = core_slice.call( arguments, 2 ); | |
proxy = function() { | |
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); | |
}; | |
// Set the guid of unique handler to the same of original handler, so it can be removed | |
proxy.guid = fn.guid = fn.guid || jQuery.guid++; | |
return proxy; | |
}, | |
// Multifunctional method to get and set values of a collection | |
// The value/s can optionally be executed if it's a function | |
access: function( elems, fn, key, value, chainable, emptyGet, raw ) { | |
var i = 0, | |
length = elems.length, | |
bulk = key == null; | |
// Sets many values | |
if ( jQuery.type( key ) === "object" ) { | |
chainable = true; | |
for ( i in key ) { | |
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); | |
} | |
// Sets one value | |
} else if ( value !== undefined ) { | |
chainable = true; | |
if ( !jQuery.isFunction( value ) ) { | |
raw = true; | |
} | |
if ( bulk ) { | |
// Bulk operations run against the entire set | |
if ( raw ) { | |
fn.call( elems, value ); | |
fn = null; | |
// ...except when executing function values | |
} else { | |
bulk = fn; | |
fn = function( elem, key, value ) { | |
return bulk.call( jQuery( elem ), value ); | |
}; | |
} | |
} | |
if ( fn ) { | |
for ( ; i < length; i++ ) { | |
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); | |
} | |
} | |
} | |
return chainable ? | |
elems : | |
// Gets | |
bulk ? | |
fn.call( elems ) : | |
length ? fn( elems[0], key ) : emptyGet; | |
}, | |
now: function() { | |
return ( new Date() ).getTime(); | |
} | |
}); | |
jQuery.ready.promise = function( obj ) { | |
if ( !readyList ) { | |
readyList = jQuery.Deferred(); | |
// Catch cases where $(document).ready() is called after the browser event has already occurred. | |
// we once tried to use readyState "interactive" here, but it caused issues like the one | |
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 | |
if ( document.readyState === "complete" ) { | |
// Handle it asynchronously to allow scripts the opportunity to delay ready | |
setTimeout( jQuery.ready ); | |
// Standards-based browsers support DOMContentLoaded | |
} else if ( document.addEventListener ) { | |
// Use the handy event callback | |
document.addEventListener( "DOMContentLoaded", completed, false ); | |
// A fallback to window.onload, that will always work | |
window.addEventListener( "load", completed, false ); | |
// If IE event model is used | |
} else { | |
// Ensure firing before onload, maybe late but safe also for iframes | |
document.attachEvent( "onreadystatechange", completed ); | |
// A fallback to window.onload, that will always work | |
window.attachEvent( "onload", completed ); | |
// If IE and not a frame | |
// continually check to see if the document is ready | |
var top = false; | |
try { | |
top = window.frameElement == null && document.documentElement; | |
} catch(e) {} | |
if ( top && top.doScroll ) { | |
(function doScrollCheck() { | |
if ( !jQuery.isReady ) { | |
try { | |
// Use the trick by Diego Perini | |
// http://javascript.nwbox.com/IEContentLoaded/ | |
top.doScroll("left"); | |
} catch(e) { | |
return setTimeout( doScrollCheck, 50 ); | |
} | |
// detach all dom ready events | |
detach(); | |
// and execute any waiting functions | |
jQuery.ready(); | |
} | |
})(); | |
} | |
} | |
} | |
return readyList.promise( obj ); | |
}; | |
// Populate the class2type map | |
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { | |
class2type[ "[object " + name + "]" ] = name.toLowerCase(); | |
}); | |
function isArraylike( obj ) { | |
var length = obj.length, | |
type = jQuery.type( obj ); | |
if ( jQuery.isWindow( obj ) ) { | |
return false; | |
} | |
if ( obj.nodeType === 1 && length ) { | |
return true; | |
} | |
return type === "array" || type !== "function" && | |
( length === 0 || | |
typeof length === "number" && length > 0 && ( length - 1 ) in obj ); | |
} | |
// All jQuery objects should point back to these | |
rootjQuery = jQuery(document); | |
// String to Object options format cache | |
var optionsCache = {}; | |
// Convert String-formatted options into Object-formatted ones and store in cache | |
function createOptions( options ) { | |
var object = optionsCache[ options ] = {}; | |
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { | |
object[ flag ] = true; | |
}); | |
return object; | |
} | |
/* | |
* Create a callback list using the following parameters: | |
* | |
* options: an optional list of space-separated options that will change how | |
* the callback list behaves or a more traditional option object | |
* | |
* By default a callback list will act like an event callback list and can be | |
* "fired" multiple times. | |
* | |
* Possible options: | |
* | |
* once: will ensure the callback list can only be fired once (like a Deferred) | |
* | |
* memory: will keep track of previous values and will call any callback added | |
* after the list has been fired right away with the latest "memorized" | |
* values (like a Deferred) | |
* | |
* unique: will ensure a callback can only be added once (no duplicate in the list) | |
* | |
* stopOnFalse: interrupt callings when a callback returns false | |
* | |
*/ | |
jQuery.Callbacks = function( options ) { | |
// Convert options from String-formatted to Object-formatted if needed | |
// (we check in cache first) | |
options = typeof options === "string" ? | |
( optionsCache[ options ] || createOptions( options ) ) : | |
jQuery.extend( {}, options ); | |
var // Flag to know if list is currently firing | |
firing, | |
// Last fire value (for non-forgettable lists) | |
memory, | |
// Flag to know if list was already fired | |
fired, | |
// End of the loop when firing | |
firingLength, | |
// Index of currently firing callback (modified by remove if needed) | |
firingIndex, | |
// First callback to fire (used internally by add and fireWith) | |
firingStart, | |
// Actual callback list | |
list = [], | |
// Stack of fire calls for repeatable lists | |
stack = !options.once && [], | |
// Fire callbacks | |
fire = function( data ) { | |
memory = options.memory && data; | |
fired = true; | |
firingIndex = firingStart || 0; | |
firingStart = 0; | |
firingLength = list.length; | |
firing = true; | |
for ( ; list && firingIndex < firingLength; firingIndex++ ) { | |
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { | |
memory = false; // To prevent further calls using add | |
break; | |
} | |
} | |
firing = false; | |
if ( list ) { | |
if ( stack ) { | |
if ( stack.length ) { | |
fire( stack.shift() ); | |
} | |
} else if ( memory ) { | |
list = []; | |
} else { | |
self.disable(); | |
} | |
} | |
}, | |
// Actual Callbacks object | |
self = { | |
// Add a callback or a collection of callbacks to the list | |
add: function() { | |
if ( list ) { | |
// First, we save the current length | |
var start = list.length; | |
(function add( args ) { | |
jQuery.each( args, function( _, arg ) { | |
var type = jQuery.type( arg ); | |
if ( type === "function" ) { | |
if ( !options.unique || !self.has( arg ) ) { | |
list.push( arg ); | |
} | |
} else if ( arg && arg.length && type !== "string" ) { | |
// Inspect recursively | |
add( arg ); | |
} | |
}); | |
})( arguments ); | |
// Do we need to add the callbacks to the | |
// current firing batch? | |
if ( firing ) { | |
firingLength = list.length; | |
// With memory, if we're not firing then | |
// we should call right away | |
} else if ( memory ) { | |
firingStart = start; | |
fire( memory ); | |
} | |
} | |
return this; | |
}, | |
// Remove a callback from the list | |
remove: function() { | |
if ( list ) { | |
jQuery.each( arguments, function( _, arg ) { | |
var index; | |
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { | |
list.splice( index, 1 ); | |
// Handle firing indexes | |
if ( firing ) { | |
if ( index <= firingLength ) { | |
firingLength--; | |
} | |
if ( index <= firingIndex ) { | |
firingIndex--; | |
} | |
} | |
} | |
}); | |
} | |
return this; | |
}, | |
// Check if a given callback is in the list. | |
// If no argument is given, return whether or not list has callbacks attached. | |
has: function( fn ) { | |
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); | |
}, | |
// Remove all callbacks from the list | |
empty: function() { | |
list = []; | |
return this; | |
}, | |
// Have the list do nothing anymore | |
disable: function() { | |
list = stack = memory = undefined; | |
return this; | |
}, | |
// Is it disabled? | |
disabled: function() { | |
return !list; | |
}, | |
// Lock the list in its current state | |
lock: function() { | |
stack = undefined; | |
if ( !memory ) { | |
self.disable(); | |
} | |
return this; | |
}, | |
// Is it locked? | |
locked: function() { | |
return !stack; | |
}, | |
// Call all callbacks with the given context and arguments | |
fireWith: function( context, args ) { | |
args = args || []; | |
args = [ context, args.slice ? args.slice() : args ]; | |
if ( list && ( !fired || stack ) ) { | |
if ( firing ) { | |
stack.push( args ); | |
} else { | |
fire( args ); | |
} | |
} | |
return this; | |
}, | |
// Call all the callbacks with the given arguments | |
fire: function() { | |
self.fireWith( this, arguments ); | |
return this; | |
}, | |
// To know if the callbacks have already been called at least once | |
fired: function() { | |
return !!fired; | |
} | |
}; | |
return self; | |
}; | |
jQuery.extend({ | |
Deferred: function( func ) { | |
var tuples = [ | |
// action, add listener, listener list, final state | |
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], | |
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], | |
[ "notify", "progress", jQuery.Callbacks("memory") ] | |
], | |
state = "pending", | |
promise = { | |
state: function() { | |
return state; | |
}, | |
always: function() { | |
deferred.done( arguments ).fail( arguments ); | |
return this; | |
}, | |
then: function( /* fnDone, fnFail, fnProgress */ ) { | |
var fns = arguments; | |
return jQuery.Deferred(function( newDefer ) { | |
jQuery.each( tuples, function( i, tuple ) { | |
var action = tuple[ 0 ], | |
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; | |
// deferred[ done | fail | progress ] for forwarding actions to newDefer | |
deferred[ tuple[1] ](function() { | |
var returned = fn && fn.apply( this, arguments ); | |
if ( returned && jQuery.isFunction( returned.promise ) ) { | |
returned.promise() | |
.done( newDefer.resolve ) | |
.fail( newDefer.reject ) | |
.progress( newDefer.notify ); | |
} else { | |
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); | |
} | |
}); | |
}); | |
fns = null; | |
}).promise(); | |
}, | |
// Get a promise for this deferred | |
// If obj is provided, the promise aspect is added to the object | |
promise: function( obj ) { | |
return obj != null ? jQuery.extend( obj, promise ) : promise; | |
} | |
}, | |
deferred = {}; | |
// Keep pipe for back-compat | |
promise.pipe = promise.then; | |
// Add list-specific methods | |
jQuery.each( tuples, function( i, tuple ) { | |
var list = tuple[ 2 ], | |
stateString = tuple[ 3 ]; | |
// promise[ done | fail | progress ] = list.add | |
promise[ tuple[1] ] = list.add; | |
// Handle state | |
if ( stateString ) { | |
list.add(function() { | |
// state = [ resolved | rejected ] | |
state = stateString; | |
// [ reject_list | resolve_list ].disable; progress_list.lock | |
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); | |
} | |
// deferred[ resolve | reject | notify ] | |
deferred[ tuple[0] ] = function() { | |
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); | |
return this; | |
}; | |
deferred[ tuple[0] + "With" ] = list.fireWith; | |
}); | |
// Make the deferred a promise | |
promise.promise( deferred ); | |
// Call given func if any | |
if ( func ) { | |
func.call( deferred, deferred ); | |
} | |
// All done! | |
return deferred; | |
}, | |
// Deferred helper | |
when: function( subordinate /* , ..., subordinateN */ ) { | |
var i = 0, | |
resolveValues = core_slice.call( arguments ), | |
length = resolveValues.length, | |
// the count of uncompleted subordinates | |
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, | |
// the master Deferred. If resolveValues consist of only a single Deferred, just use that. | |
deferred = remaining === 1 ? subordinate : jQuery.Deferred(), | |
// Update function for both resolve and progress values | |
updateFunc = function( i, contexts, values ) { | |
return function( value ) { | |
contexts[ i ] = this; | |
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; | |
if( values === progressValues ) { | |
deferred.notifyWith( contexts, values ); | |
} else if ( !( --remaining ) ) { | |
deferred.resolveWith( contexts, values ); | |
} | |
}; | |
}, | |
progressValues, progressContexts, resolveContexts; | |
// add listeners to Deferred subordinates; treat others as resolved | |
if ( length > 1 ) { | |
progressValues = new Array( length ); | |
progressContexts = new Array( length ); | |
resolveContexts = new Array( length ); | |
for ( ; i < length; i++ ) { | |
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { | |
resolveValues[ i ].promise() | |
.done( updateFunc( i, resolveContexts, resolveValues ) ) | |
.fail( deferred.reject ) | |
.progress( updateFunc( i, progressContexts, progressValues ) ); | |
} else { | |
--remaining; | |
} | |
} | |
} | |
// if we're not waiting on anything, resolve the master | |
if ( !remaining ) { | |
deferred.resolveWith( resolveContexts, resolveValues ); | |
} | |
return deferred.promise(); | |
} | |
}); | |
jQuery.support = (function() { | |
var support, all, a, | |
input, select, fragment, | |
opt, eventName, isSupported, i, | |
div = document.createElement("div"); | |
// Setup | |
div.setAttribute( "className", "t" ); | |
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; | |
// Support tests won't run in some limited or non-browser environments | |
all = div.getElementsByTagName("*"); | |
a = div.getElementsByTagName("a")[ 0 ]; | |
if ( !all || !a || !all.length ) { | |
return {}; | |
} | |
// First batch of tests | |
select = document.createElement("select"); | |
opt = select.appendChild( document.createElement("option") ); | |
input = div.getElementsByTagName("input")[ 0 ]; | |
a.style.cssText = "top:1px;float:left;opacity:.5"; | |
support = { | |
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) | |
getSetAttribute: div.className !== "t", | |
// IE strips leading whitespace when .innerHTML is used | |
leadingWhitespace: div.firstChild.nodeType === 3, | |
// Make sure that tbody elements aren't automatically inserted | |
// IE will insert them into empty tables | |
tbody: !div.getElementsByTagName("tbody").length, | |
// Make sure that link elements get serialized correctly by innerHTML | |
// This requires a wrapper element in IE | |
htmlSerialize: !!div.getElementsByTagName("link").length, | |
// Get the style information from getAttribute | |
// (IE uses .cssText instead) | |
style: /top/.test( a.getAttribute("style") ), | |
// Make sure that URLs aren't manipulated | |
// (IE normalizes it by default) | |
hrefNormalized: a.getAttribute("href") === "/a", | |
// Make sure that element opacity exists | |
// (IE uses filter instead) | |
// Use a regex to work around a WebKit issue. See #5145 | |
opacity: /^0.5/.test( a.style.opacity ), | |
// Verify style float existence | |
// (IE uses styleFloat instead of cssFloat) | |
cssFloat: !!a.style.cssFloat, | |
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) | |
checkOn: !!input.value, | |
// Make sure that a selected-by-default option has a working selected property. | |
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup) | |
optSelected: opt.selected, | |
// Tests for enctype support on a form (#6743) | |
enctype: !!document.createElement("form").enctype, | |
// Makes sure cloning an html5 element does not cause problems | |
// Where outerHTML is undefined, this still works | |
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", | |
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode | |
boxModel: document.compatMode === "CSS1Compat", | |
// Will be defined later | |
deleteExpando: true, | |
noCloneEvent: true, | |
inlineBlockNeedsLayout: false, | |
shrinkWrapBlocks: false, | |
reliableMarginRight: true, | |
boxSizingReliable: true, | |
pixelPosition: false | |
}; | |
// Make sure checked status is properly cloned | |
input.checked = true; | |
support.noCloneChecked = input.cloneNode( true ).checked; | |
// Make sure that the options inside disabled selects aren't marked as disabled | |
// (WebKit marks them as disabled) | |
select.disabled = true; | |
support.optDisabled = !opt.disabled; | |
// Support: IE<9 | |
try { | |
delete div.test; | |
} catch( e ) { | |
support.deleteExpando = false; | |
} | |
// Check if we can trust getAttribute("value") | |
input = document.createElement("input"); | |
input.setAttribute( "value", "" ); | |
support.input = input.getAttribute( "value" ) === ""; | |
// Check if an input maintains its value after becoming a radio | |
input.value = "t"; | |
input.setAttribute( "type", "radio" ); | |
support.radioValue = input.value === "t"; | |
// #11217 - WebKit loses check when the name is after the checked attribute | |
input.setAttribute( "checked", "t" ); | |
input.setAttribute( "name", "t" ); | |
fragment = document.createDocumentFragment(); | |
fragment.appendChild( input ); | |
// Check if a disconnected checkbox will retain its checked | |
// value of true after appended to the DOM (IE6/7) | |
support.appendChecked = input.checked; | |
// WebKit doesn't clone checked state correctly in fragments | |
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; | |
// Support: IE<9 | |
// Opera does not clone events (and typeof div.attachEvent === undefined). | |
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click() | |
if ( div.attachEvent ) { | |
div.attachEvent( "onclick", function() { | |
support.noCloneEvent = false; | |
}); | |
div.cloneNode( true ).click(); | |
} | |
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) | |
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php | |
for ( i in { submit: true, change: true, focusin: true }) { | |
div.setAttribute( eventName = "on" + i, "t" ); | |
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; | |
} | |
div.style.backgroundClip = "content-box"; | |
div.cloneNode( true ).style.backgroundClip = ""; | |
support.clearCloneStyle = div.style.backgroundClip === "content-box"; | |
// Run tests that need a body at doc ready | |
jQuery(function() { | |
var container, marginDiv, tds, | |
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", | |
body = document.getElementsByTagName("body")[0]; | |
if ( !body ) { | |
// Return for frameset docs that don't have a body | |
return; | |
} | |
container = document.createElement("div"); | |
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; | |
body.appendChild( container ).appendChild( div ); | |
// Support: IE8 | |
// Check if table cells still have offsetWidth/Height when they are set | |
// to display:none and there are still other visible table cells in a | |
// table row; if so, offsetWidth/Height are not reliable for use when | |
// determining if an element has been hidden directly using | |
// display:none (it is still safe to use offsets if a parent element is | |
// hidden; don safety goggles and see bug #4512 for more information). | |
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; | |
tds = div.getElementsByTagName("td"); | |
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; | |
isSupported = ( tds[ 0 ].offsetHeight === 0 ); | |
tds[ 0 ].style.display = ""; | |
tds[ 1 ].style.display = "none"; | |
// Support: IE8 | |
// Check if empty table cells still have offsetWidth/Height | |
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); | |
// Check box-sizing and margin behavior | |
div.innerHTML = ""; | |
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; | |
support.boxSizing = ( div.offsetWidth === 4 ); | |
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); | |
// Use window.getComputedStyle because jsdom on node.js will break without it. | |
if ( window.getComputedStyle ) { | |
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; | |
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; | |
// Check if div with explicit width and no margin-right incorrectly | |
// gets computed margin-right based on width of container. (#3333) | |
// Fails in WebKit before Feb 2011 nightlies | |
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right | |
marginDiv = div.appendChild( document.createElement("div") ); | |
marginDiv.style.cssText = div.style.cssText = divReset; | |
marginDiv.style.marginRight = marginDiv.style.width = "0"; | |
div.style.width = "1px"; | |
support.reliableMarginRight = | |
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); | |
} | |
if ( typeof div.style.zoom !== core_strundefined ) { | |
// Support: IE<8 | |
// Check if natively block-level elements act like inline-block | |
// elements when setting their display to 'inline' and giving | |
// them layout | |
div.innerHTML = ""; | |
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; | |
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); | |
// Support: IE6 | |
// Check if elements with layout shrink-wrap their children | |
div.style.display = "block"; | |
div.innerHTML = "<div></div>"; | |
div.firstChild.style.width = "5px"; | |
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); | |
if ( support.inlineBlockNeedsLayout ) { | |
// Prevent IE 6 from affecting layout for positioned elements #11048 | |
// Prevent IE from shrinking the body in IE 7 mode #12869 | |
// Support: IE<8 | |
body.style.zoom = 1; | |
} | |
} | |
body.removeChild( container ); | |
// Null elements to avoid leaks in IE | |
container = div = tds = marginDiv = null; | |
}); | |
// Null elements to avoid leaks in IE | |
all = select = fragment = opt = a = input = null; | |
return support; | |
})(); | |
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, | |
rmultiDash = /([A-Z])/g; | |
function internalData( elem, name, data, pvt /* Internal Use Only */ ){ | |
if ( !jQuery.acceptData( elem ) ) { | |
return; | |
} | |
var thisCache, ret, | |
internalKey = jQuery.expando, | |
getByName = typeof name === "string", | |
// We have to handle DOM nodes and JS objects differently because IE6-7 | |
// can't GC object references properly across the DOM-JS boundary | |
isNode = elem.nodeType, | |
// Only DOM nodes need the global jQuery cache; JS object data is | |
// attached directly to the object so GC can occur automatically | |
cache = isNode ? jQuery.cache : elem, | |
// Only defining an ID for JS objects if its cache already exists allows | |
// the code to shortcut on the same path as a DOM node with no cache | |
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; | |
// Avoid doing any more work than we need to when trying to get data on an | |
// object that has no data at all | |
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { | |
return; | |
} | |
if ( !id ) { | |
// Only DOM nodes need a new unique ID for each element since their data | |
// ends up in the global cache | |
if ( isNode ) { | |
elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; | |
} else { | |
id = internalKey; | |
} | |
} | |
if ( !cache[ id ] ) { | |
cache[ id ] = {}; | |
// Avoids exposing jQuery metadata on plain JS objects when the object | |
// is serialized using JSON.stringify | |
if ( !isNode ) { | |
cache[ id ].toJSON = jQuery.noop; | |
} | |
} | |
// An object can be passed to jQuery.data instead of a key/value pair; this gets | |
// shallow copied over onto the existing cache | |
if ( typeof name === "object" || typeof name === "function" ) { | |
if ( pvt ) { | |
cache[ id ] = jQuery.extend( cache[ id ], name ); | |
} else { | |
cache[ id ].data = jQuery.extend( cache[ id ].data, name ); | |
} | |
} | |
thisCache = cache[ id ]; | |
// jQuery data() is stored in a separate object inside the object's internal data | |
// cache in order to avoid key collisions between internal data and user-defined | |
// data. | |
if ( !pvt ) { | |
if ( !thisCache.data ) { | |
thisCache.data = {}; | |
} | |
thisCache = thisCache.data; | |
} | |
if ( data !== undefined ) { | |
thisCache[ jQuery.camelCase( name ) ] = data; | |
} | |
// Check for both converted-to-camel and non-converted data property names | |
// If a data property was specified | |
if ( getByName ) { | |
// First Try to find as-is property data | |
ret = thisCache[ name ]; | |
// Test for null|undefined property data | |
if ( ret == null ) { | |
// Try to find the camelCased property | |
ret = thisCache[ jQuery.camelCase( name ) ]; | |
} | |
} else { | |
ret = thisCache; | |
} | |
return ret; | |
} | |
function internalRemoveData( elem, name, pvt ) { | |
if ( !jQuery.acceptData( elem ) ) { | |
return; | |
} | |
var i, l, thisCache, | |
isNode = elem.nodeType, | |
// See jQuery.data for more information | |
cache = isNode ? jQuery.cache : elem, | |
id = isNode ? elem[ jQuery.expando ] : jQuery.expando; | |
// If there is already no cache entry for this object, there is no | |
// purpose in continuing | |
if ( !cache[ id ] ) { | |
return; | |
} | |
if ( name ) { | |
thisCache = pvt ? cache[ id ] : cache[ id ].data; | |
if ( thisCache ) { | |
// Support array or space separated string names for data keys | |
if ( !jQuery.isArray( name ) ) { | |
// try the string as a key before any manipulation | |
if ( name in thisCache ) { | |
name = [ name ]; | |
} else { | |
// split the camel cased version by spaces unless a key with the spaces exists | |
name = jQuery.camelCase( name ); | |
if ( name in thisCache ) { | |
name = [ name ]; | |
} else { | |
name = name.split(" "); | |
} | |
} | |
} else { | |
// If "name" is an array of keys... | |
// When data is initially created, via ("key", "val") signature, | |
// keys will be converted to camelCase. | |
// Since there is no way to tell _how_ a key was added, remove | |
// both plain key and camelCase key. #12786 | |
// This will only penalize the array argument path. | |
name = name.concat( jQuery.map( name, jQuery.camelCase ) ); | |
} | |
for ( i = 0, l = name.length; i < l; i++ ) { | |
delete thisCache[ name[i] ]; | |
} | |
// If there is no data left in the cache, we want to continue | |
// and let the cache object itself get destroyed | |
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { | |
return; | |
} | |
} | |
} | |
// See jQuery.data for more information | |
if ( !pvt ) { | |
delete cache[ id ].data; | |
// Don't destroy the parent cache unless the internal data object | |
// had been the only thing left in it | |
if ( !isEmptyDataObject( cache[ id ] ) ) { | |
return; | |
} | |
} | |
// Destroy the cache | |
if ( isNode ) { | |
jQuery.cleanData( [ elem ], true ); | |
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) | |
} else if ( jQuery.support.deleteExpando || cache != cache.window ) { | |
delete cache[ id ]; | |
// When all else fails, null | |
} else { | |
cache[ id ] = null; | |
} | |
} | |
jQuery.extend({ | |
cache: {}, | |
// Unique for each copy of jQuery on the page | |
// Non-digits removed to match rinlinejQuery | |
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), | |
// The following elements throw uncatchable exceptions if you | |
// attempt to add expando properties to them. | |
noData: { | |
"embed": true, | |
// Ban all objects except for Flash (which handle expandos) | |
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", | |
"applet": true | |
}, | |
hasData: function( elem ) { | |
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; | |
return !!elem && !isEmptyDataObject( elem ); | |
}, | |
data: function( elem, name, data ) { | |
return internalData( elem, name, data ); | |
}, | |
removeData: function( elem, name ) { | |
return internalRemoveData( elem, name ); | |
}, | |
// For internal use only. | |
_data: function( elem, name, data ) { | |
return internalData( elem, name, data, true ); | |
}, | |
_removeData: function( elem, name ) { | |
return internalRemoveData( elem, name, true ); | |
}, | |
// A method for determining if a DOM node can handle the data expando | |
acceptData: function( elem ) { | |
// Do not set data on non-element because it will not be cleared (#8335). | |
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { | |
return false; | |
} | |
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; | |
// nodes accept data unless otherwise specified; rejection can be conditional | |
return !noData || noData !== true && elem.getAttribute("classid") === noData; | |
} | |
}); | |
jQuery.fn.extend({ | |
data: function( key, value ) { | |
var attrs, name, | |
elem = this[0], | |
i = 0, | |
data = null; | |
// Gets all values | |
if ( key === undefined ) { | |
if ( this.length ) { | |
data = jQuery.data( elem ); | |
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { | |
attrs = elem.attributes; | |
for ( ; i < attrs.length; i++ ) { | |
name = attrs[i].name; | |
if ( !name.indexOf( "data-" ) ) { | |
name = jQuery.camelCase( name.slice(5) ); | |
dataAttr( elem, name, data[ name ] ); | |
} | |
} | |
jQuery._data( elem, "parsedAttrs", true ); | |
} | |
} | |
return data; | |
} | |
// Sets multiple values | |
if ( typeof key === "object" ) { | |
return this.each(function() { | |
jQuery.data( this, key ); | |
}); | |
} | |
return jQuery.access( this, function( value ) { | |
if ( value === undefined ) { | |
// Try to fetch any internally stored data first | |
return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; | |
} | |
this.each(function() { | |
jQuery.data( this, key, value ); | |
}); | |
}, null, value, arguments.length > 1, null, true ); | |
}, | |
removeData: function( key ) { | |
return this.each(function() { | |
jQuery.removeData( this, key ); | |
}); | |
} | |
}); | |
function dataAttr( elem, key, data ) { | |
// If nothing was found internally, try to fetch any | |
// data from the HTML5 data-* attribute | |
if ( data === undefined && elem.nodeType === 1 ) { | |
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); | |
data = elem.getAttribute( name ); | |
if ( typeof data === "string" ) { | |
try { | |
data = data === "true" ? true : | |
data === "false" ? false : | |
data === "null" ? null : | |
// Only convert to a number if it doesn't change the string | |
+data + "" === data ? +data : | |
rbrace.test( data ) ? jQuery.parseJSON( data ) : | |
data; | |
} catch( e ) {} | |
// Make sure we set the data so it isn't changed later | |
jQuery.data( elem, key, data ); | |
} else { | |
data = undefined; | |
} | |
} | |
return data; | |
} | |
// checks a cache object for emptiness | |
function isEmptyDataObject( obj ) { | |
var name; | |
for ( name in obj ) { | |
// if the public data object is empty, the private is still empty | |
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { | |
continue; | |
} | |
if ( name !== "toJSON" ) { | |
return false; | |
} | |
} | |
return true; | |
} | |
jQuery.extend({ | |
queue: function( elem, type, data ) { | |
var queue; | |
if ( elem ) { | |
type = ( type || "fx" ) + "queue"; | |
queue = jQuery._data( elem, type ); | |
// Speed up dequeue by getting out quickly if this is just a lookup | |
if ( data ) { | |
if ( !queue || jQuery.isArray(data) ) { | |
queue = jQuery._data( elem, type, jQuery.makeArray(data) ); | |
} else { | |
queue.push( data ); | |
} | |
} | |
return queue || []; | |
} | |
}, | |
dequeue: function( elem, type ) { | |
type = type || "fx"; | |
var queue = jQuery.queue( elem, type ), | |
startLength = queue.length, | |
fn = queue.shift(), | |
hooks = jQuery._queueHooks( elem, type ), | |
next = function() { | |
jQuery.dequeue( elem, type ); | |
}; | |
// If the fx queue is dequeued, always remove the progress sentinel | |
if ( fn === "inprogress" ) { | |
fn = queue.shift(); | |
startLength--; | |
} | |
hooks.cur = fn; | |
if ( fn ) { | |
// Add a progress sentinel to prevent the fx queue from being | |
// automatically dequeued | |
if ( type === "fx" ) { | |
queue.unshift( "inprogress" ); | |
} | |
// clear up the last queue stop function | |
delete hooks.stop; | |
fn.call( elem, next, hooks ); | |
} | |
if ( !startLength && hooks ) { | |
hooks.empty.fire(); | |
} | |
}, | |
// not intended for public consumption - generates a queueHooks object, or returns the current one | |
_queueHooks: function( elem, type ) { | |
var key = type + "queueHooks"; | |
return jQuery._data( elem, key ) || jQuery._data( elem, key, { | |
empty: jQuery.Callbacks("once memory").add(function() { | |
jQuery._removeData( elem, type + "queue" ); | |
jQuery._removeData( elem, key ); | |
}) | |
}); | |
} | |
}); | |
jQuery.fn.extend({ | |
queue: function( type, data ) { | |
var setter = 2; | |
if ( typeof type !== "string" ) { | |
data = type; | |
type = "fx"; | |
setter--; | |
} | |
if ( arguments.length < setter ) { | |
return jQuery.queue( this[0], type ); | |
} | |
return data === undefined ? | |
this : | |
this.each(function() { | |
var queue = jQuery.queue( this, type, data ); | |
// ensure a hooks for this queue | |
jQuery._queueHooks( this, type ); | |
if ( type === "fx" && queue[0] !== "inprogress" ) { | |
jQuery.dequeue( this, type ); | |
} | |
}); | |
}, | |
dequeue: function( type ) { | |
return this.each(function() { | |
jQuery.dequeue( this, type ); | |
}); | |
}, | |
// Based off of the plugin by Clint Helfers, with permission. | |
// http://blindsignals.com/index.php/2009/07/jquery-delay/ | |
delay: function( time, type ) { | |
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; | |
type = type || "fx"; | |
return this.queue( type, function( next, hooks ) { | |
var timeout = setTimeout( next, time ); | |
hooks.stop = function() { | |
clearTimeout( timeout ); | |
}; | |
}); | |
}, | |
clearQueue: function( type ) { | |
return this.queue( type || "fx", [] ); | |
}, | |
// Get a promise resolved when queues of a certain type | |
// are emptied (fx is the type by default) | |
promise: function( type, obj ) { | |
var tmp, | |
count = 1, | |
defer = jQuery.Deferred(), | |
elements = this, | |
i = this.length, | |
resolve = function() { | |
if ( !( --count ) ) { | |
defer.resolveWith( elements, [ elements ] ); | |
} | |
}; | |
if ( typeof type !== "string" ) { | |
obj = type; | |
type = undefined; | |
} | |
type = type || "fx"; | |
while( i-- ) { | |
tmp = jQuery._data( elements[ i ], type + "queueHooks" ); | |
if ( tmp && tmp.empty ) { | |
count++; | |
tmp.empty.add( resolve ); | |
} | |
} | |
resolve(); | |
return defer.promise( obj ); | |
} | |
}); | |
var nodeHook, boolHook, | |
rclass = /[\t\r\n]/g, | |
rreturn = /\r/g, | |
rfocusable = /^(?:input|select|textarea|button|object)$/i, | |
rclickable = /^(?:a|area)$/i, | |
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, | |
ruseDefault = /^(?:checked|selected)$/i, | |
getSetAttribute = jQuery.support.getSetAttribute, | |
getSetInput = jQuery.support.input; | |
jQuery.fn.extend({ | |
attr: function( name, value ) { | |
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); | |
}, | |
removeAttr: function( name ) { | |
return this.each(function() { | |
jQuery.removeAttr( this, name ); | |
}); | |
}, | |
prop: function( name, value ) { | |
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); | |
}, | |
removeProp: function( name ) { | |
name = jQuery.propFix[ name ] || name; | |
return this.each(function() { | |
// try/catch handles cases where IE balks (such as removing a property on window) | |
try { | |
this[ name ] = undefined; | |
delete this[ name ]; | |
} catch( e ) {} | |
}); | |
}, | |
addClass: function( value ) { | |
var classes, elem, cur, clazz, j, | |
i = 0, | |
len = this.length, | |
proceed = typeof value === "string" && value; | |
if ( jQuery.isFunction( value ) ) { | |
return this.each(function( j ) { | |
jQuery( this ).addClass( value.call( this, j, this.className ) ); | |
}); | |
} | |
if ( proceed ) { | |
// The disjunction here is for better compressibility (see removeClass) | |
classes = ( value || "" ).match( core_rnotwhite ) || []; | |
for ( ; i < len; i++ ) { | |
elem = this[ i ]; | |
cur = elem.nodeType === 1 && ( elem.className ? | |
( " " + elem.className + " " ).replace( rclass, " " ) : | |
" " | |
); | |
if ( cur ) { | |
j = 0; | |
while ( (clazz = classes[j++]) ) { | |
if ( cur.indexOf( " " + clazz + " " ) < 0 ) { | |
cur += clazz + " "; | |
} | |
} | |
elem.className = jQuery.trim( cur ); | |
} | |
} | |
} | |
return this; | |
}, | |
removeClass: function( value ) { | |
var classes, elem, cur, clazz, j, | |
i = 0, | |
len = this.length, | |
proceed = arguments.length === 0 || typeof value === "string" && value; | |
if ( jQuery.isFunction( value ) ) { | |
return this.each(function( j ) { | |
jQuery( this ).removeClass( value.call( this, j, this.className ) ); | |
}); | |
} | |
if ( proceed ) { | |
classes = ( value || "" ).match( core_rnotwhite ) || []; | |
for ( ; i < len; i++ ) { | |
elem = this[ i ]; | |
// This expression is here for better compressibility (see addClass) | |
cur = elem.nodeType === 1 && ( elem.className ? | |
( " " + elem.className + " " ).replace( rclass, " " ) : | |
"" | |
); | |
if ( cur ) { | |
j = 0; | |
while ( (clazz = classes[j++]) ) { | |
// Remove *all* instances | |
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { | |
cur = cur.replace( " " + clazz + " ", " " ); | |
} | |
} | |
elem.className = value ? jQuery.trim( cur ) : ""; | |
} | |
} | |
} | |
return this; | |
}, | |
toggleClass: function( value, stateVal ) { | |
var type = typeof value, | |
isBool = typeof stateVal === "boolean"; | |
if ( jQuery.isFunction( value ) ) { | |
return this.each(function( i ) { | |
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); | |
}); | |
} | |
return this.each(function() { | |
if ( type === "string" ) { | |
// toggle individual class names | |
var className, | |
i = 0, | |
self = jQuery( this ), | |
state = stateVal, | |
classNames = value.match( core_rnotwhite ) || []; | |
while ( (className = classNames[ i++ ]) ) { | |
// check each className given, space separated list | |
state = isBool ? state : !self.hasClass( className ); | |
self[ state ? "addClass" : "removeClass" ]( className ); | |
} | |
// Toggle whole class name | |
} else if ( type === core_strundefined || type === "boolean" ) { | |
if ( this.className ) { | |
// store className if set | |
jQuery._data( this, "__className__", this.className ); | |
} | |
// If the element has a class name or if we're passed "false", | |
// then remove the whole classname (if there was one, the above saved it). | |
// Otherwise bring back whatever was previously saved (if anything), | |
// falling back to the empty string if nothing was stored. | |
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; | |
} | |
}); | |
}, | |
hasClass: function( selector ) { | |
var className = " " + selector + " ", | |
i = 0, | |
l = this.length; | |
for ( ; i < l; i++ ) { | |
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { | |
return true; | |
} | |
} | |
return false; | |
}, | |
val: function( value ) { | |
var ret, hooks, isFunction, | |
elem = this[0]; | |
if ( !arguments.length ) { | |
if ( elem ) { | |
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; | |
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { | |
return ret; | |
} | |
ret = elem.value; | |
return typeof ret === "string" ? | |
// handle most common string cases | |
ret.replace(rreturn, "") : | |
// handle cases where value is null/undef or number | |
ret == null ? "" : ret; | |
} | |
return; | |
} | |
isFunction = jQuery.isFunction( value ); | |
return this.each(function( i ) { | |
var val, | |
self = jQuery(this); | |
if ( this.nodeType !== 1 ) { | |
return; | |
} | |
if ( isFunction ) { | |
val = value.call( this, i, self.val() ); | |
} else { | |
val = value; | |
} | |
// Treat null/undefined as ""; convert numbers to string | |
if ( val == null ) { | |
val = ""; | |
} else if ( typeof val === "number" ) { | |
val += ""; | |
} else if ( jQuery.isArray( val ) ) { | |
val = jQuery.map(val, function ( value ) { | |
return value == null ? "" : value + ""; | |
}); | |
} | |
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; | |
// If set returns undefined, fall back to normal setting | |
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { | |
this.value = val; | |
} | |
}); | |
} | |
}); | |
jQuery.extend({ | |
valHooks: { | |
option: { | |
get: function( elem ) { | |
// attributes.value is undefined in Blackberry 4.7 but | |
// uses .value. See #6932 | |
var val = elem.attributes.value; | |
return !val || val.specified ? elem.value : elem.text; | |
} | |
}, | |
select: { | |
get: function( elem ) { | |
var value, option, | |
options = elem.options, | |
index = elem.selectedIndex, | |
one = elem.type === "select-one" || index < 0, | |
values = one ? null : [], | |
max = one ? index + 1 : options.length, | |
i = index < 0 ? | |
max : | |
one ? index : 0; | |
// Loop through all the selected options | |
for ( ; i < max; i++ ) { | |
option = options[ i ]; | |
// oldIE doesn't update selected after form reset (#2551) | |
if ( ( option.selected || i === index ) && | |
// Don't return options that are disabled or in a disabled optgroup | |
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && | |
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { | |
// Get the specific value for the option | |
value = jQuery( option ).val(); | |
// We don't need an array for one selects | |
if ( one ) { | |
return value; | |
} | |
// Multi-Selects return an array | |
values.push( value ); | |
} | |
} | |
return values; | |
}, | |
set: function( elem, value ) { | |
var values = jQuery.makeArray( value ); | |
jQuery(elem).find("option").each(function() { | |
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; | |
}); | |
if ( !values.length ) { | |
elem.selectedIndex = -1; | |
} | |
return values; | |
} | |
} | |
}, | |
attr: function( elem, name, value ) { | |
var hooks, notxml, ret, | |
nType = elem.nodeType; | |
// don't get/set attributes on text, comment and attribute nodes | |
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { | |
return; | |
} | |
// Fallback to prop when attributes are not supported | |
if ( typeof elem.getAttribute === core_strundefined ) { | |
return jQuery.prop( elem, name, value ); | |
} | |
notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); | |
// All attributes are lowercase | |
// Grab necessary hook if one is defined | |
if ( notxml ) { | |
name = name.toLowerCase(); | |
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); | |
} | |
if ( value !== undefined ) { | |
if ( value === null ) { | |
jQuery.removeAttr( elem, name ); | |
} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { | |
return ret; | |
} else { | |
elem.setAttribute( name, value + "" ); | |
return value; | |
} | |
} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { | |
return ret; | |
} else { | |
// In IE9+, Flash objects don't have .getAttribute (#12945) | |
// Support: IE9+ | |
if ( typeof elem.getAttribute !== core_strundefined ) { | |
ret = elem.getAttribute( name ); | |
} | |
// Non-existent attributes return null, we normalize to undefined | |
return ret == null ? | |
undefined : | |
ret; | |
} | |
}, | |
removeAttr: function( elem, value ) { | |
var name, propName, | |
i = 0, | |
attrNames = value && value.match( core_rnotwhite ); | |
if ( attrNames && elem.nodeType === 1 ) { | |
while ( (name = attrNames[i++]) ) { | |
propName = jQuery.propFix[ name ] || name; | |
// Boolean attributes get special treatment (#10870) | |
if ( rboolean.test( name ) ) { | |
// Set corresponding property to false for boolean attributes | |
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 | |
if ( !getSetAttribute && ruseDefault.test( name ) ) { | |
elem[ jQuery.camelCase( "default-" + name ) ] = | |
elem[ propName ] = false; | |
} else { | |
elem[ propName ] = false; | |
} | |
// See #9699 for explanation of this approach (setting first, then removal) | |
} else { | |
jQuery.attr( elem, name, "" ); | |
} | |
elem.removeAttribute( getSetAttribute ? name : propName ); | |
} | |
} | |
}, | |
attrHooks: { | |
type: { | |
set: function( elem, value ) { | |
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { | |
// Setting the type on a radio button after the value resets the value in IE6-9 | |
// Reset value to default in case type is set after value during creation | |
var val = elem.value; | |
elem.setAttribute( "type", value ); | |
if ( val ) { | |
elem.value = val; | |
} | |
return value; | |
} | |
} | |
} | |
}, | |
propFix: { | |
tabindex: "tabIndex", | |
readonly: "readOnly", | |
"for": "htmlFor", | |
"class": "className", | |
maxlength: "maxLength", | |
cellspacing: "cellSpacing", | |
cellpadding: "cellPadding", | |
rowspan: "rowSpan", | |
colspan: "colSpan", | |
usemap: "useMap", | |
frameborder: "frameBorder", | |
contenteditable: "contentEditable" | |
}, | |
prop: function( elem, name, value ) { | |
var ret, hooks, notxml, | |
nType = elem.nodeType; | |
// don't get/set properties on text, comment and attribute nodes | |
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { | |
return; | |
} | |
notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); | |
if ( notxml ) { | |
// Fix name and attach hooks | |
name = jQuery.propFix[ name ] || name; | |
hooks = jQuery.propHooks[ name ]; | |
} | |
if ( value !== undefined ) { | |
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { | |
return ret; | |
} else { | |
return ( elem[ name ] = value ); | |
} | |
} else { | |
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { | |
return ret; | |
} else { | |
return elem[ name ]; | |
} | |
} | |
}, | |
propHooks: { | |
tabIndex: { | |
get: function( elem ) { | |
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set | |
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ | |
var attributeNode = elem.getAttributeNode("tabindex"); | |
return attributeNode && attributeNode.specified ? | |
parseInt( attributeNode.value, 10 ) : | |
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? | |
0 : | |
undefined; | |
} | |
} | |
} | |
}); | |
// Hook for boolean attributes | |
boolHook = { | |
get: function( elem, name ) { | |
var | |
// Use .prop to determine if this attribute is understood as boolean | |
prop = jQuery.prop( elem, name ), | |
// Fetch it accordingly | |
attr = typeof prop === "boolean" && elem.getAttribute( name ), | |
detail = typeof prop === "boolean" ? | |
getSetInput && getSetAttribute ? | |
attr != null : | |
// oldIE fabricates an empty string for missing boolean attributes | |
// and conflates checked/selected into attroperties | |
ruseDefault.test( name ) ? | |
elem[ jQuery.camelCase( "default-" + name ) ] : | |
!!attr : | |
// fetch an attribute node for properties not recognized as boolean | |
elem.getAttributeNode( name ); | |
return detail && detail.value !== false ? | |
name.toLowerCase() : | |
undefined; | |
}, | |
set: function( elem, value, name ) { | |
if ( value === false ) { | |
// Remove boolean attributes when set to false | |
jQuery.removeAttr( elem, name ); | |
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { | |
// IE<8 needs the *property* name | |
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); | |
// Use defaultChecked and defaultSelected for oldIE | |
} else { | |
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; | |
} | |
return name; | |
} | |
}; | |
// fix oldIE value attroperty | |
if ( !getSetInput || !getSetAttribute ) { | |
jQuery.attrHooks.value = { | |
get: function( elem, name ) { | |
var ret = elem.getAttributeNode( name ); | |
return jQuery.nodeName( elem, "input" ) ? | |
// Ignore the value *property* by using defaultValue | |
elem.defaultValue : | |
ret && ret.specified ? ret.value : undefined; | |
}, | |
set: function( elem, value, name ) { | |
if ( jQuery.nodeName( elem, "input" ) ) { | |
// Does not return so that setAttribute is also used | |
elem.defaultValue = value; | |
} else { | |
// Use nodeHook if defined (#1954); otherwise setAttribute is fine | |
return nodeHook && nodeHook.set( elem, value, name ); | |
} | |
} | |
}; | |
} | |
// IE6/7 do not support getting/setting some attributes with get/setAttribute | |
if ( !getSetAttribute ) { | |
// Use this for any attribute in IE6/7 | |
// This fixes almost every IE6/7 issue | |
nodeHook = jQuery.valHooks.button = { | |
get: function( elem, name ) { | |
var ret = elem.getAttributeNode( name ); | |
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? | |
ret.value : | |
undefined; | |
}, | |
set: function( elem, value, name ) { | |
// Set the existing or create a new attribute node | |
var ret = elem.getAttributeNode( name ); | |
if ( !ret ) { | |
elem.setAttributeNode( | |
(ret = elem.ownerDocument.createAttribute( name )) | |
); | |
} | |
ret.value = value += ""; | |
// Break association with cloned elements by also using setAttribute (#9646) | |
return name === "value" || value === elem.getAttribute( name ) ? | |
value : | |
undefined; | |
} | |
}; | |
// Set contenteditable to false on removals(#10429) | |
// Setting to empty string throws an error as an invalid value | |
jQuery.attrHooks.contenteditable = { | |
get: nodeHook.get, | |
set: function( elem, value, name ) { | |
nodeHook.set( elem, value === "" ? false : value, name ); | |
} | |
}; | |
// Set width and height to auto instead of 0 on empty string( Bug #8150 ) | |
// This is for removals | |
jQuery.each([ "width", "height" ], function( i, name ) { | |
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { | |
set: function( elem, value ) { | |
if ( value === "" ) { | |
elem.setAttribute( name, "auto" ); | |
return value; | |
} | |
} | |
}); | |
}); | |
} | |
// Some attributes require a special call on IE | |
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx | |
if ( !jQuery.support.hrefNormalized ) { | |
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { | |
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { | |
get: function( elem ) { | |
var ret = elem.getAttribute( name, 2 ); | |
return ret == null ? undefined : ret; | |
} | |
}); | |
}); | |
// href/src property should get the full normalized URL (#10299/#12915) | |
jQuery.each([ "href", "src" ], function( i, name ) { | |
jQuery.propHooks[ name ] = { | |
get: function( elem ) { | |
return elem.getAttribute( name, 4 ); | |
} | |
}; | |
}); | |
} | |
if ( !jQuery.support.style ) { | |
jQuery.attrHooks.style = { | |
get: function( elem ) { | |
// Return undefined in the case of empty string | |
// Note: IE uppercases css property names, but if we were to .toLowerCase() | |
// .cssText, that would destroy case senstitivity in URL's, like in "background" | |
return elem.style.cssText || undefined; | |
}, | |
set: function( elem, value ) { | |
return ( elem.style.cssText = value + "" ); | |
} | |
}; | |
} | |
// Safari mis-reports the default selected property of an option | |
// Accessing the parent's selectedIndex property fixes it | |
if ( !jQuery.support.optSelected ) { | |
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { | |
get: function( elem ) { | |
var parent = elem.parentNode; | |
if ( parent ) { | |
parent.selectedIndex; | |
// Make sure that it also works with optgroups, see #5701 | |
if ( parent.parentNode ) { | |
parent.parentNode.selectedIndex; | |
} | |
} | |
return null; | |
} | |
}); | |
} | |
// IE6/7 call enctype encoding | |
if ( !jQuery.support.enctype ) { | |
jQuery.propFix.enctype = "encoding"; | |
} | |
// Radios and checkboxes getter/setter | |
if ( !jQuery.support.checkOn ) { | |
jQuery.each([ "radio", "checkbox" ], function() { | |
jQuery.valHooks[ this ] = { | |
get: function( elem ) { | |
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified | |
return elem.getAttribute("value") === null ? "on" : elem.value; | |
} | |
}; | |
}); | |
} | |
jQuery.each([ "radio", "checkbox" ], function() { | |
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { | |
set: function( elem, value ) { | |
if ( jQuery.isArray( value ) ) { | |
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); | |
} | |
} | |
}); | |
}); | |
var rformElems = /^(?:input|select|textarea)$/i, | |
rkeyEvent = /^key/, | |
rmouseEvent = /^(?:mouse|contextmenu)|click/, | |
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, | |
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; | |
function returnTrue() { | |
return true; | |
} | |
function returnFalse() { | |
return false; | |
} | |
/* | |
* Helper functions for managing events -- not part of the public interface. | |
* Props to Dean Edwards' addEvent library for many of the ideas. | |
*/ | |
jQuery.event = { | |
global: {}, | |
add: function( elem, types, handler, data, selector ) { | |
var tmp, events, t, handleObjIn, | |
special, eventHandle, handleObj, | |
handlers, type, namespaces, origType, | |
elemData = jQuery._data( elem ); | |
// Don't attach events to noData or text/comment nodes (but allow plain objects) | |
if ( !elemData ) { | |
return; | |
} | |
// Caller can pass in an object of custom data in lieu of the handler | |
if ( handler.handler ) { | |
handleObjIn = handler; | |
handler = handleObjIn.handler; | |
selector = handleObjIn.selector; | |
} | |
// Make sure that the handler has a unique ID, used to find/remove it later | |
if ( !handler.guid ) { | |
handler.guid = jQuery.guid++; | |
} | |
// Init the element's event structure and main handler, if this is the first | |
if ( !(events = elemData.events) ) { | |
events = elemData.events = {}; | |
} | |
if ( !(eventHandle = elemData.handle) ) { | |
eventHandle = elemData.handle = function( e ) { | |
// Discard the second event of a jQuery.event.trigger() and | |
// when an event is called after a page has unloaded | |
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? | |
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : | |
undefined; | |
}; | |
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events | |
eventHandle.elem = elem; | |
} | |
// Handle multiple events separated by a space | |
// jQuery(...).bind("mouseover mouseout", fn); | |
types = ( types || "" ).match( core_rnotwhite ) || [""]; | |
t = types.length; | |
while ( t-- ) { | |
tmp = rtypenamespace.exec( types[t] ) || []; | |
type = origType = tmp[1]; | |
namespaces = ( tmp[2] || "" ).split( "." ).sort(); | |
// If event changes its type, use the special event handlers for the changed type | |
special = jQuery.event.special[ type ] || {}; | |
// If selector defined, determine special event api type, otherwise given type | |
type = ( selector ? special.delegateType : special.bindType ) || type; | |
// Update special based on newly reset type | |
special = jQuery.event.special[ type ] || {}; | |
// handleObj is passed to all event handlers | |
handleObj = jQuery.extend({ | |
type: type, | |
origType: origType, | |
data: data, | |
handler: handler, | |
guid: handler.guid, | |
selector: selector, | |
needsContext: selector && jQuery.expr.match.needsContext.test( selector ), | |
namespace: namespaces.join(".") | |
}, handleObjIn ); | |
// Init the event handler queue if we're the first | |
if ( !(handlers = events[ type ]) ) { | |
handlers = events[ type ] = []; | |
handlers.delegateCount = 0; | |
// Only use addEventListener/attachEvent if the special events handler returns false | |
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { | |
// Bind the global event handler to the element | |
if ( elem.addEventListener ) { | |
elem.addEventListener( type, eventHandle, false ); | |
} else if ( elem.attachEvent ) { | |
elem.attachEvent( "on" + type, eventHandle ); | |
} | |
} | |
} | |
if ( special.add ) { | |
special.add.call( elem, handleObj ); | |
if ( !handleObj.handler.guid ) { | |
handleObj.handler.guid = handler.guid; | |
} | |
} | |
// Add to the element's handler list, delegates in front | |
if ( selector ) { | |
handlers.splice( handlers.delegateCount++, 0, handleObj ); | |
} else { | |
handlers.push( handleObj ); | |
} | |
// Keep track of which events have ever been used, for event optimization | |
jQuery.event.global[ type ] = true; | |
} | |
// Nullify elem to prevent memory leaks in IE | |
elem = null; | |
}, | |
// Detach an event or set of events from an element | |
remove: function( elem, types, handler, selector, mappedTypes ) { | |
var j, handleObj, tmp, | |
origCount, t, events, | |
special, handlers, type, | |
namespaces, origType, | |
elemData = jQuery.hasData( elem ) && jQuery._data( elem ); | |
if ( !elemData || !(events = elemData.events) ) { | |
return; | |
} | |
// Once for each type.namespace in types; type may be omitted | |
types = ( types || "" ).match( core_rnotwhite ) || [""]; | |
t = types.length; | |
while ( t-- ) { | |
tmp = rtypenamespace.exec( types[t] ) || []; | |
type = origType = tmp[1]; | |
namespaces = ( tmp[2] || "" ).split( "." ).sort(); | |
// Unbind all events (on this namespace, if provided) for the element | |
if ( !type ) { | |
for ( type in events ) { | |
jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); | |
} | |
continue; | |
} | |
special = jQuery.event.special[ type ] || {}; | |
type = ( selector ? special.delegateType : special.bindType ) || type; | |
handlers = events[ type ] || []; | |
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); | |
// Remove matching events | |
origCount = j = handlers.length; | |
while ( j-- ) { | |
handleObj = handlers[ j ]; | |
if ( ( mappedTypes || origType === handleObj.origType ) && | |
( !handler || handler.guid === handleObj.guid ) && | |
( !tmp || tmp.test( handleObj.namespace ) ) && | |
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { | |
handlers.splice( j, 1 ); | |
if ( handleObj.selector ) { | |
handlers.delegateCount--; | |
} | |
if ( special.remove ) { | |
special.remove.call( elem, handleObj ); | |
} | |
} | |
} | |
// Remove generic event handler if we removed something and no more handlers exist | |
// (avoids potential for endless recursion during removal of special event handlers) | |
if ( origCount && !handlers.length ) { | |
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { | |
jQuery.removeEvent( elem, type, elemData.handle ); | |
} | |
delete events[ type ]; | |
} | |
} | |
// Remove the expando if it's no longer used | |
if ( jQuery.isEmptyObject( events ) ) { | |
delete elemData.handle; | |
// removeData also checks for emptiness and clears the expando if empty | |
// so use it instead of delete | |
jQuery._removeData( elem, "events" ); | |
} | |
}, | |
trigger: function( event, data, elem, onlyHandlers ) { | |
var handle, ontype, cur, | |
bubbleType, special, tmp, i, | |
eventPath = [ elem || document ], | |
type = core_hasOwn.call( event, "type" ) ? event.type : event, | |
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; | |
cur = tmp = elem = elem || document; | |
// Don't do events on text and comment nodes | |
if ( elem.nodeType === 3 || elem.nodeType === 8 ) { | |
return; | |
} | |
// focus/blur morphs to focusin/out; ensure we're not firing them right now | |
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { | |
return; | |
} | |
if ( type.indexOf(".") >= 0 ) { | |
// Namespaced trigger; create a regexp to match event type in handle() | |
namespaces = type.split("."); | |
type = namespaces.shift(); | |
namespaces.sort(); | |
} | |
ontype = type.indexOf(":") < 0 && "on" + type; | |
// Caller can pass in a jQuery.Event object, Object, or just an event type string | |
event = event[ jQuery.expando ] ? | |
event : | |
new jQuery.Event( type, typeof event === "object" && event ); | |
event.isTrigger = true; | |
event.namespace = namespaces.join("."); | |
event.namespace_re = event.namespace ? | |
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : | |
null; | |
// Clean up the event in case it is being reused | |
event.result = undefined; | |
if ( !event.target ) { | |
event.target = elem; | |
} | |
// Clone any incoming data and prepend the event, creating the handler arg list | |
data = data == null ? | |
[ event ] : | |
jQuery.makeArray( data, [ event ] ); | |
// Allow special events to draw outside the lines | |
special = jQuery.event.special[ type ] || {}; | |
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { | |
return; | |
} | |
// Determine event propagation path in advance, per W3C events spec (#9951) | |
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724) | |
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { | |
bubbleType = special.delegateType || type; | |
if ( !rfocusMorph.test( bubbleType + type ) ) { | |
cur = cur.parentNode; | |
} | |
for ( ; cur; cur = cur.parentNode ) { | |
eventPath.push( cur ); | |
tmp = cur; | |
} | |
// Only add window if we got to document (e.g., not plain obj or detached DOM) | |
if ( tmp === (elem.ownerDocument || document) ) { | |
eventPath.push( tmp.defaultView || tmp.parentWindow || window ); | |
} | |
} | |
// Fire handlers on the event path | |
i = 0; | |
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { | |
event.type = i > 1 ? | |
bubbleType : | |
special.bindType || type; | |
// jQuery handler | |
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); | |
if ( handle ) { | |
handle.apply( cur, data ); | |
} | |
// Native handler | |
handle = ontype && cur[ ontype ]; | |
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { | |
event.preventDefault(); | |
} | |
} | |
event.type = type; | |
// If nobody prevented the default action, do it now | |
if ( !onlyHandlers && !event.isDefaultPrevented() ) { | |
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && | |
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { | |
// Call a native DOM method on the target with the same name name as the event. | |
// Can't use an .isFunction() check here because IE6/7 fails that test. | |
// Don't do default actions on window, that's where global variables be (#6170) | |
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { | |
// Don't re-trigger an onFOO event when we call its FOO() method | |
tmp = elem[ ontype ]; | |
if ( tmp ) { | |
elem[ ontype ] = null; | |
} | |
// Prevent re-triggering of the same event, since we already bubbled it above | |
jQuery.event.triggered = type; | |
try { | |
elem[ type ](); | |
} catch ( e ) { | |
// IE<9 dies on focus/blur to hidden element (#1486,#12518) | |
// only reproducible on winXP IE8 native, not IE9 in IE8 mode | |
} | |
jQuery.event.triggered = undefined; | |
if ( tmp ) { | |
elem[ ontype ] = tmp; | |
} | |
} | |
} | |
} | |
return event.result; | |
}, | |
dispatch: function( event ) { | |
// Make a writable jQuery.Event from the native event object | |
event = jQuery.event.fix( event ); | |
var i, ret, handleObj, matched, j, | |
handlerQueue = [], | |
args = core_slice.call( arguments ), | |
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], | |
special = jQuery.event.special[ event.type ] || {}; | |
// Use the fix-ed jQuery.Event rather than the (read-only) native event | |
args[0] = event; | |
event.delegateTarget = this; | |
// Call the preDispatch hook for the mapped type, and let it bail if desired | |
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { | |
return; | |
} | |
// Determine handlers | |
handlerQueue = jQuery.event.handlers.call( this, event, handlers ); | |
// Run delegates first; they may want to stop propagation beneath us | |
i = 0; | |
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { | |
event.currentTarget = matched.elem; | |
j = 0; | |
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { | |
// Triggered event must either 1) have no namespace, or | |
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). | |
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { | |
event.handleObj = handleObj; | |
event.data = handleObj.data; | |
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) | |
.apply( matched.elem, args ); | |
if ( ret !== undefined ) { | |
if ( (event.result = ret) === false ) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
} | |
} | |
} | |
} | |
} | |
// Call the postDispatch hook for the mapped type | |
if ( special.postDispatch ) { | |
special.postDispatch.call( this, event ); | |
} | |
return event.result; | |
}, | |
handlers: function( event, handlers ) { | |
var sel, handleObj, matches, i, | |
handlerQueue = [], | |
delegateCount = handlers.delegateCount, | |
cur = event.target; | |
// Find delegate handlers | |
// Black-hole SVG <use> instance trees (#13180) | |
// Avoid non-left-click bubbling in Firefox (#3861) | |
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { | |
for ( ; cur != this; cur = cur.parentNode || this ) { | |
// Don't check non-elements (#13208) | |
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) | |
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { | |
matches = []; | |
for ( i = 0; i < delegateCount; i++ ) { | |
handleObj = handlers[ i ]; | |
// Don't conflict with Object.prototype properties (#13203) | |
sel = handleObj.selector + " "; | |
if ( matches[ sel ] === undefined ) { | |
matches[ sel ] = handleObj.needsContext ? | |
jQuery( sel, this ).index( cur ) >= 0 : | |
jQuery.find( sel, this, null, [ cur ] ).length; | |
} | |
if ( matches[ sel ] ) { | |
matches.push( handleObj ); | |
} | |
} | |
if ( matches.length ) { | |
handlerQueue.push({ elem: cur, handlers: matches }); | |
} | |
} | |
} | |
} | |
// Add the remaining (directly-bound) handlers | |
if ( delegateCount < handlers.length ) { | |
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); | |
} | |
return handlerQueue; | |
}, | |
fix: function( event ) { | |
if ( event[ jQuery.expando ] ) { | |
return event; | |
} | |
// Create a writable copy of the event object and normalize some properties | |
var i, prop, copy, | |
type = event.type, | |
originalEvent = event, | |
fixHook = this.fixHooks[ type ]; | |
if ( !fixHook ) { | |
this.fixHooks[ type ] = fixHook = | |
rmouseEvent.test( type ) ? this.mouseHooks : | |
rkeyEvent.test( type ) ? this.keyHooks : | |
{}; | |
} | |
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; | |
event = new jQuery.Event( originalEvent ); | |
i = copy.length; | |
while ( i-- ) { | |
prop = copy[ i ]; | |
event[ prop ] = originalEvent[ prop ]; | |
} | |
// Support: IE<9 | |
// Fix target property (#1925) | |
if ( !event.target ) { | |
event.target = originalEvent.srcElement || document; | |
} | |
// Support: Chrome 23+, Safari? | |
// Target should not be a text node (#504, #13143) | |
if ( event.target.nodeType === 3 ) { | |
event.target = event.target.parentNode; | |
} | |
// Support: IE<9 | |
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328) | |
event.metaKey = !!event.metaKey; | |
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; | |
}, | |
// Includes some event props shared by KeyEvent and MouseEvent | |
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), | |
fixHooks: {}, | |
keyHooks: { | |
props: "char charCode key keyCode".split(" "), | |
filter: function( event, original ) { | |
// Add which for key events | |
if ( event.which == null ) { | |
event.which = original.charCode != null ? original.charCode : original.keyCode; | |
} | |
return event; | |
} | |
}, | |
mouseHooks: { | |
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), | |
filter: function( event, original ) { | |
var body, eventDoc, doc, | |
button = original.button, | |
fromElement = original.fromElement; | |
// Calculate pageX/Y if missing and clientX/Y available | |
if ( event.pageX == null && original.clientX != null ) { | |
eventDoc = event.target.ownerDocument || document; | |
doc = eventDoc.documentElement; | |
body = eventDoc.body; | |
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); | |
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); | |
} | |
// Add relatedTarget, if necessary | |
if ( !event.relatedTarget && fromElement ) { | |
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; | |
} | |
// Add which for click: 1 === left; 2 === middle; 3 === right | |
// Note: button is not normalized, so don't use it | |
if ( !event.which && button !== undefined ) { | |
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); | |
} | |
return event; | |
} | |
}, | |
special: { | |
load: { | |
// Prevent triggered image.load events from bubbling to window.load | |
noBubble: true | |
}, | |
click: { | |
// For checkbox, fire native event so checked state will be right | |
trigger: function() { | |
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { | |
this.click(); | |
return false; | |
} | |
} | |
}, | |
focus: { | |
// Fire native event if possible so blur/focus sequence is correct | |
trigger: function() { | |
if ( this !== document.activeElement && this.focus ) { | |
try { | |
this.focus(); | |
return false; | |
} catch ( e ) { | |
// Support: IE<9 | |
// If we error on focus to hidden element (#1486, #12518), | |
// let .trigger() run the handlers | |
} | |
} | |
}, | |
delegateType: "focusin" | |
}, | |
blur: { | |
trigger: function() { | |
if ( this === document.activeElement && this.blur ) { | |
this.blur(); | |
return false; | |
} | |
}, | |
delegateType: "focusout" | |
}, | |
beforeunload: { | |
postDispatch: function( event ) { | |
// Even when returnValue equals to undefined Firefox will still show alert | |
if ( event.result !== undefined ) { | |
event.originalEvent.returnValue = event.result; | |
} | |
} | |
} | |
}, | |
simulate: function( type, elem, event, bubble ) { | |
// Piggyback on a donor event to simulate a different one. | |
// Fake originalEvent to avoid donor's stopPropagation, but if the | |
// simulated event prevents default then we do the same on the donor. | |
var e = jQuery.extend( | |
new jQuery.Event(), | |
event, | |
{ type: type, | |
isSimulated: true, | |
originalEvent: {} | |
} | |
); | |
if ( bubble ) { | |
jQuery.event.trigger( e, null, elem ); | |
} else { | |
jQuery.event.dispatch.call( elem, e ); | |
} | |
if ( e.isDefaultPrevented() ) { | |
event.preventDefault(); | |
} | |
} | |
}; | |
jQuery.removeEvent = document.removeEventListener ? | |
function( elem, type, handle ) { | |
if ( elem.removeEventListener ) { | |
elem.removeEventListener( type, handle, false ); | |
} | |
} : | |
function( elem, type, handle ) { | |
var name = "on" + type; | |
if ( elem.detachEvent ) { | |
// #8545, #7054, preventing memory leaks for custom events in IE6-8 | |
// detachEvent needed property on element, by name of that event, to properly expose it to GC | |
if ( typeof elem[ name ] === core_strundefined ) { | |
elem[ name ] = null; | |
} | |
elem.detachEvent( name, handle ); | |
} | |
}; | |
jQuery.Event = function( src, props ) { | |
// Allow instantiation without the 'new' keyword | |
if ( !(this instanceof jQuery.Event) ) { | |
return new jQuery.Event( src, props ); | |
} | |
// Event object | |
if ( src && src.type ) { | |
this.originalEvent = src; | |
this.type = src.type; | |
// Events bubbling up the document may have been marked as prevented | |
// by a handler lower down the tree; reflect the correct value. | |
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || | |
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; | |
// Event type | |
} else { | |
this.type = src; | |
} | |
// Put explicitly provided properties onto the event object | |
if ( props ) { | |
jQuery.extend( this, props ); | |
} | |
// Create a timestamp if incoming event doesn't have one | |
this.timeStamp = src && src.timeStamp || jQuery.now(); | |
// Mark it as fixed | |
this[ jQuery.expando ] = true; | |
}; | |
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding | |
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html | |
jQuery.Event.prototype = { | |
isDefaultPrevented: returnFalse, | |
isPropagationStopped: returnFalse, | |
isImmediatePropagationStopped: returnFalse, | |
preventDefault: function() { | |
var e = this.originalEvent; | |
this.isDefaultPrevented = returnTrue; | |
if ( !e ) { | |
return; | |
} | |
// If preventDefault exists, run it on the original event | |
if ( e.preventDefault ) { | |
e.preventDefault(); | |
// Support: IE | |
// Otherwise set the returnValue property of the original event to false | |
} else { | |
e.returnValue = false; | |
} | |
}, | |
stopPropagation: function() { | |
var e = this.originalEvent; | |
this.isPropagationStopped = returnTrue; | |
if ( !e ) { | |
return; | |
} | |
// If stopPropagation exists, run it on the original event | |
if ( e.stopPropagation ) { | |
e.stopPropagation(); | |
} | |
// Support: IE | |
// Set the cancelBubble property of the original event to true | |
e.cancelBubble = true; | |
}, | |
stopImmediatePropagation: function() { | |
this.isImmediatePropagationStopped = returnTrue; | |
this.stopPropagation(); | |
} | |
}; | |
// Create mouseenter/leave events using mouseover/out and event-time checks | |
jQuery.each({ | |
mouseenter: "mouseover", | |
mouseleave: "mouseout" | |
}, function( orig, fix ) { | |
jQuery.event.special[ orig ] = { | |
delegateType: fix, | |
bindType: fix, | |
handle: function( event ) { | |
var ret, | |
target = this, | |
related = event.relatedTarget, | |
handleObj = event.handleObj; | |
// For mousenter/leave call the handler if related is outside the target. | |
// NB: No relatedTarget if the mouse left/entered the browser window | |
if ( !related || (related !== target && !jQuery.contains( target, related )) ) { | |
event.type = handleObj.origType; | |
ret = handleObj.handler.apply( this, arguments ); | |
event.type = fix; | |
} | |
return ret; | |
} | |
}; | |
}); | |
// IE submit delegation | |
if ( !jQuery.support.submitBubbles ) { | |
jQuery.event.special.submit = { | |
setup: function() { | |
// Only need this for delegated form submit events | |
if ( jQuery.nodeName( this, "form" ) ) { | |
return false; | |
} | |
// Lazy-add a submit handler when a descendant form may potentially be submitted | |
jQuery.event.add( this, "click._submit keypress._submit", function( e ) { | |
// Node name check avoids a VML-related crash in IE (#9807) | |
var elem = e.target, | |
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; | |
if ( form && !jQuery._data( form, "submitBubbles" ) ) { | |
jQuery.event.add( form, "submit._submit", function( event ) { | |
event._submit_bubble = true; | |
}); | |
jQuery._data( form, "submitBubbles", true ); | |
} | |
}); | |
// return undefined since we don't need an event listener | |
}, | |
postDispatch: function( event ) { | |
// If form was submitted by the user, bubble the event up the tree | |
if ( event._submit_bubble ) { | |
delete event._submit_bubble; | |
if ( this.parentNode && !event.isTrigger ) { | |
jQuery.event.simulate( "submit", this.parentNode, event, true ); | |
} | |
} | |
}, | |
teardown: function() { | |
// Only need this for delegated form submit events | |
if ( jQuery.nodeName( this, "form" ) ) { | |
return false; | |
} | |
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above | |
jQuery.event.remove( this, "._submit" ); | |
} | |
}; | |
} | |
// IE change delegation and checkbox/radio fix | |
if ( !jQuery.support.changeBubbles ) { | |
jQuery.event.special.change = { | |
setup: function() { | |
if ( rformElems.test( this.nodeName ) ) { | |
// IE doesn't fire change on a check/radio until blur; trigger it on click | |
// after a propertychange. Eat the blur-change in special.change.handle. | |
// This still fires onchange a second time for check/radio after blur. | |
if ( this.type === "checkbox" || this.type === "radio" ) { | |
jQuery.event.add( this, "propertychange._change", function( event ) { | |
if ( event.originalEvent.propertyName === "checked" ) { | |
this._just_changed = true; | |
} | |
}); | |
jQuery.event.add( this, "click._change", function( event ) { | |
if ( this._just_changed && !event.isTrigger ) { | |
this._just_changed = false; | |
} | |
// Allow triggered, simulated change events (#11500) | |
jQuery.event.simulate( "change", this, event, true ); | |
}); | |
} | |
return false; | |
} | |
// Delegated event; lazy-add a change handler on descendant inputs | |
jQuery.event.add( this, "beforeactivate._change", function( e ) { | |
var elem = e.target; | |
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { | |
jQuery.event.add( elem, "change._change", function( event ) { | |
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { | |
jQuery.event.simulate( "change", this.parentNode, event, true ); | |
} | |
}); | |
jQuery._data( elem, "changeBubbles", true ); | |
} | |
}); | |
}, | |
handle: function( event ) { | |
var elem = event.target; | |
// Swallow native change events from checkbox/radio, we already triggered them above | |
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { | |
return event.handleObj.handler.apply( this, arguments ); | |
} | |
}, | |
teardown: function() { | |
jQuery.event.remove( this, "._change" ); | |
return !rformElems.test( this.nodeName ); | |
} | |
}; | |
} | |
// Create "bubbling" focus and blur events | |
if ( !jQuery.support.focusinBubbles ) { | |
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { | |
// Attach a single capturing handler while someone wants focusin/focusout | |
var attaches = 0, | |
handler = function( event ) { | |
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); | |
}; | |
jQuery.event.special[ fix ] = { | |
setup: function() { | |
if ( attaches++ === 0 ) { | |
document.addEventListener( orig, handler, true ); | |
} | |
}, | |
teardown: function() { | |
if ( --attaches === 0 ) { | |
document.removeEventListener( orig, handler, true ); | |
} | |
} | |
}; | |
}); | |
} | |
jQuery.fn.extend({ | |
on: function( types, selector, data, fn, /*INTERNAL*/ one ) { | |
var type, origFn; | |
// Types can be a map of types/handlers | |
if ( typeof types === "object" ) { | |
// ( types-Object, selector, data ) | |
if ( typeof selector !== "string" ) { | |
// ( types-Object, data ) | |
data = data || selector; | |
selector = undefined; | |
} | |
for ( type in types ) { | |
this.on( type, selector, data, types[ type ], one ); | |
} | |
return this; | |
} | |
if ( data == null && fn == null ) { | |
// ( types, fn ) | |
fn = selector; | |
data = selector = undefined; | |
} else if ( fn == null ) { | |
if ( typeof selector === "string" ) { | |
// ( types, selector, fn ) | |
fn = data; | |
data = undefined; | |
} else { | |
// ( types, data, fn ) | |
fn = data; | |
data = selector; | |
selector = undefined; | |
} | |
} | |
if ( fn === false ) { | |
fn = returnFalse; | |
} else if ( !fn ) { | |
return this; | |
} | |
if ( one === 1 ) { | |
origFn = fn; | |
fn = function( event ) { | |
// Can use an empty set, since event contains the info | |
jQuery().off( event ); | |
return origFn.apply( this, arguments ); | |
}; | |
// Use same guid so caller can remove using origFn | |
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); | |
} | |
return this.each( function() { | |
jQuery.event.add( this, types, fn, data, selector ); | |
}); | |
}, | |
one: function( types, selector, data, fn ) { | |
return this.on( types, selector, data, fn, 1 ); | |
}, | |
off: function( types, selector, fn ) { | |
var handleObj, type; | |
if ( types && types.preventDefault && types.handleObj ) { | |
// ( event ) dispatched jQuery.Event | |
handleObj = types.handleObj; | |
jQuery( types.delegateTarget ).off( | |
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, | |
handleObj.selector, | |
handleObj.handler | |
); | |
return this; | |
} | |
if ( typeof types === "object" ) { | |
// ( types-object [, selector] ) | |
for ( type in types ) { | |
this.off( type, selector, types[ type ] ); | |
} | |
return this; | |
} | |
if ( selector === false || typeof selector === "function" ) { | |
// ( types [, fn] ) | |
fn = selector; | |
selector = undefined; | |
} | |
if ( fn === false ) { | |
fn = returnFalse; | |
} | |
return this.each(function() { | |
jQuery.event.remove( this, types, fn, selector ); | |
}); | |
}, | |
bind: function( types, data, fn ) { | |
return this.on( types, null, data, fn ); | |
}, | |
unbind: function( types, fn ) { | |
return this.off( types, null, fn ); | |
}, | |
delegate: function( selector, types, data, fn ) { | |
return this.on( types, selector, data, fn ); | |
}, | |
undelegate: function( selector, types, fn ) { | |
// ( namespace ) or ( selector, types [, fn] ) | |
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); | |
}, | |
trigger: function( type, data ) { | |
return this.each(function() { | |
jQuery.event.trigger( type, data, this ); | |
}); | |
}, | |
triggerHandler: function( type, data ) { | |
var elem = this[0]; | |
if ( elem ) { | |
return jQuery.event.trigger( type, data, elem, true ); | |
} | |
} | |
}); | |
/*! | |
* Sizzle CSS Selector Engine | |
* Copyright 2012 jQuery Foundation and other contributors | |
* Released under the MIT license | |
* http://sizzlejs.com/ | |
*/ | |
(function( window, undefined ) { | |
var i, | |
cachedruns, | |
Expr, | |
getText, | |
isXML, | |
compile, | |
hasDuplicate, | |
outermostContext, | |
// Local document vars | |
setDocument, | |
document, | |
docElem, | |
documentIsXML, | |
rbuggyQSA, | |
rbuggyMatches, | |
matches, | |
contains, | |
sortOrder, | |
// Instance-specific data | |
expando = "sizzle" + -(new Date()), | |
preferredDoc = window.document, | |
support = {}, | |
dirruns = 0, | |
done = 0, | |
classCache = createCache(), | |
tokenCache = createCache(), | |
compilerCache = createCache(), | |
// General-purpose constants | |
strundefined = typeof undefined, | |
MAX_NEGATIVE = 1 << 31, | |
// Array methods | |
arr = [], | |
pop = arr.pop, | |
push = arr.push, | |
slice = arr.slice, | |
// Use a stripped-down indexOf if we can't use a native one | |
indexOf = arr.indexOf || function( elem ) { | |
var i = 0, | |
len = this.length; | |
for ( ; i < len; i++ ) { | |
if ( this[i] === elem ) { | |
return i; | |
} | |
} | |
return -1; | |
}, | |
// Regular expressions | |
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace | |
whitespace = "[\\x20\\t\\r\\n\\f]", | |
// http://www.w3.org/TR/css3-syntax/#characters | |
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", | |
// Loosely modeled on CSS identifier characters | |
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors | |
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier | |
identifier = characterEncoding.replace( "w", "w#" ), | |
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors | |
operators = "([*^$|!~]?=)", | |
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + | |
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", | |
// Prefer arguments quoted, | |
// then not containing pseudos/brackets, | |
// then attribute selectors/non-parenthetical expressions, | |
// then anything else | |
// These preferences are here to reduce the number of selectors | |
// needing tokenize in the PSEUDO preFilter | |
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", | |
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter | |
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), | |
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), | |
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), | |
rpseudo = new RegExp( pseudos ), | |
ridentifier = new RegExp( "^" + identifier + "$" ), | |
matchExpr = { | |
"ID": new RegExp( "^#(" + characterEncoding + ")" ), | |
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), | |
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), | |
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), | |
"ATTR": new RegExp( "^" + attributes ), | |
"PSEUDO": new RegExp( "^" + pseudos ), | |
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + | |
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + | |
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ), | |
// For use in libraries implementing .is() | |
// We use this for POS matching in `select` | |
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + | |
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) | |
}, | |
rsibling = /[\x20\t\r\n\f]*[+~]/, | |
rnative = /^[^{]+\{\s*\[native code/, | |
// Easily-parseable/retrievable ID or TAG or CLASS selectors | |
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, | |
rinputs = /^(?:input|select|textarea|button)$/i, | |
rheader = /^h\d$/i, | |
rescape = /'|\\/g, | |
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, | |
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters | |
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, | |
funescape = function( _, escaped ) { | |
var high = "0x" + escaped - 0x10000; | |
// NaN means non-codepoint | |
return high !== high ? | |
escaped : | |
// BMP codepoint | |
high < 0 ? | |
String.fromCharCode( high + 0x10000 ) : | |
// Supplemental Plane codepoint (surrogate pair) | |
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); | |
}; | |
// Use a stripped-down slice if we can't use a native one | |
try { | |
slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; | |
} catch ( e ) { | |
slice = function( i ) { | |
var elem, | |
results = []; | |
while ( (elem = this[i++]) ) { | |
results.push( elem ); | |
} | |
return results; | |
}; | |
} | |
/** | |
* For feature detection | |
* @param {Function} fn The function to test for native support | |
*/ | |
function isNative( fn ) { | |
return rnative.test( fn + "" ); | |
} | |
/** | |
* Create key-value caches of limited size | |
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with | |
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) | |
* deleting the oldest entry | |
*/ | |
function createCache() { | |
var cache, | |
keys = []; | |
return (cache = function( key, value ) { | |
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157) | |
if ( keys.push( key += " " ) > Expr.cacheLength ) { | |
// Only keep the most recent entries | |
delete cache[ keys.shift() ]; | |
} | |
return (cache[ key ] = value); | |
}); | |
} | |
/** | |
* Mark a function for special use by Sizzle | |
* @param {Function} fn The function to mark | |
*/ | |
function markFunction( fn ) { | |
fn[ expando ] = true; | |
return fn; | |
} | |
/** | |
* Support testing using an element | |
* @param {Function} fn Passed the created div and expects a boolean result | |
*/ | |
function assert( fn ) { | |
var div = document.createElement("div"); | |
try { | |
return fn( div ); | |
} catch (e) { | |
return false; | |
} finally { | |
// release memory in IE | |
div = null; | |
} | |
} | |
function Sizzle( selector, context, results, seed ) { | |
var match, elem, m, nodeType, | |
// QSA vars | |
i, groups, old, nid, newContext, newSelector; | |
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { | |
setDocument( context ); | |
} | |
context = context || document; | |
results = results || []; | |
if ( !selector || typeof selector !== "string" ) { | |
return results; | |
} | |
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { | |
return []; | |
} | |
if ( !documentIsXML && !seed ) { | |
// Shortcuts | |
if ( (match = rquickExpr.exec( selector )) ) { | |
// Speed-up: Sizzle("#ID") | |
if ( (m = match[1]) ) { | |
if ( nodeType === 9 ) { | |
elem = context.getElementById( m ); | |
// Check parentNode to catch when Blackberry 4.6 returns | |
// nodes that are no longer in the document #6963 | |
if ( elem && elem.parentNode ) { | |
// Handle the case where IE, Opera, and Webkit return items | |
// by name instead of ID | |
if ( elem.id === m ) { | |
results.push( elem ); | |
return results; | |
} | |
} else { | |
return results; | |
} | |
} else { | |
// Context is not a document | |
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && | |
contains( context, elem ) && elem.id === m ) { | |
results.push( elem ); | |
return results; | |
} | |
} | |
// Speed-up: Sizzle("TAG") | |
} else if ( match[2] ) { | |
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); | |
return results; | |
// Speed-up: Sizzle(".CLASS") | |
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { | |
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); | |
return results; | |
} | |
} | |
// QSA path | |
if ( support.qsa && !rbuggyQSA.test(selector) ) { | |
old = true; | |
nid = expando; | |
newContext = context; | |
newSelector = nodeType === 9 && selector; | |
// qSA works strangely on Element-rooted queries | |
// We can work around this by specifying an extra ID on the root | |
// and working up from there (Thanks to Andrew Dupont for the technique) | |
// IE 8 doesn't work on object elements | |
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { | |
groups = tokenize( selector ); | |
if ( (old = context.getAttribute("id")) ) { | |
nid = old.replace( rescape, "\\$&" ); | |
} else { | |
context.setAttribute( "id", nid ); | |
} | |
nid = "[id='" + nid + "'] "; | |
i = groups.length; | |
while ( i-- ) { | |
groups[i] = nid + toSelector( groups[i] ); | |
} | |
newContext = rsibling.test( selector ) && context.parentNode || context; | |
newSelector = groups.join(","); | |
} | |
if ( newSelector ) { | |
try { | |
push.apply( results, slice.call( newContext.querySelectorAll( | |
newSelector | |
), 0 ) ); | |
return results; | |
} catch(qsaError) { | |
} finally { | |
if ( !old ) { | |
context.removeAttribute("id"); | |
} | |
} | |
} | |
} | |
} | |
// All others | |
return select( selector.replace( rtrim, "$1" ), context, results, seed ); | |
} | |
/** | |
* Detect xml | |
* @param {Element|Object} elem An element or a document | |
*/ | |
isXML = Sizzle.isXML = function( elem ) { | |
// documentElement is verified for cases where it doesn't yet exist | |
// (such as loading iframes in IE - #4833) | |
var documentElement = elem && (elem.ownerDocument || elem).documentElement; | |
return documentElement ? documentElement.nodeName !== "HTML" : false; | |
}; | |
/** | |
* Sets document-related variables once based on the current document | |
* @param {Element|Object} [doc] An element or document object to use to set the document | |
* @returns {Object} Returns the current document | |
*/ | |
setDocument = Sizzle.setDocument = function( node ) { | |
var doc = node ? node.ownerDocument || node : preferredDoc; | |
// If no document and documentElement is available, return | |
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { | |
return document; | |
} | |
// Set our document | |
document = doc; | |
docElem = doc.documentElement; | |
// Support tests | |
documentIsXML = isXML( doc ); | |
// Check if getElementsByTagName("*") returns only elements | |
support.tagNameNoComments = assert(function( div ) { | |
div.appendChild( doc.createComment("") ); | |
return !div.getElementsByTagName("*").length; | |
}); | |
// Check if attributes should be retrieved by attribute nodes | |
support.attributes = assert(function( div ) { | |
div.innerHTML = "<select></select>"; | |
var type = typeof div.lastChild.getAttribute("multiple"); | |
// IE8 returns a string for some attributes even when not present | |
return type !== "boolean" && type !== "string"; | |
}); | |
// Check if getElementsByClassName can be trusted | |
support.getByClassName = assert(function( div ) { | |
// Opera can't find a second classname (in 9.6) | |
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; | |
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { | |
return false; | |
} | |
// Safari 3.2 caches class attributes and doesn't catch changes | |
div.lastChild.className = "e"; | |
return div.getElementsByClassName("e").length === 2; | |
}); | |
// Check if getElementById returns elements by name | |
// Check if getElementsByName privileges form controls or returns elements by ID | |
support.getByName = assert(function( div ) { | |
// Inject content | |
div.id = expando + 0; | |
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; | |
docElem.insertBefore( div, docElem.firstChild ); | |
// Test | |
var pass = doc.getElementsByName && | |
// buggy browsers will return fewer than the correct 2 | |
doc.getElementsByName( expando ).length === 2 + | |
// buggy browsers will return more than the correct 0 | |
doc.getElementsByName( expando + 0 ).length; | |
support.getIdNotName = !doc.getElementById( expando ); | |
// Cleanup | |
docElem.removeChild( div ); | |
return pass; | |
}); | |
// IE6/7 return modified attributes | |
Expr.attrHandle = assert(function( div ) { | |
div.innerHTML = "<a href='#'></a>"; | |
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && | |
div.firstChild.getAttribute("href") === "#"; | |
}) ? | |
{} : | |
{ | |
"href": function( elem ) { | |
return elem.getAttribute( "href", 2 ); | |
}, | |
"type": function( elem ) { | |
return elem.getAttribute("type"); | |
} | |
}; | |
// ID find and filter | |
if ( support.getIdNotName ) { | |
Expr.find["ID"] = function( id, context ) { | |
if ( typeof context.getElementById !== strundefined && !documentIsXML ) { | |
var m = context.getElementById( id ); | |
// Check parentNode to catch when Blackberry 4.6 returns | |
// nodes that are no longer in the document #6963 | |
return m && m.parentNode ? [m] : []; | |
} | |
}; | |
Expr.filter["ID"] = function( id ) { | |
var attrId = id.replace( runescape, funescape ); | |
return function( elem ) { | |
return elem.getAttribute("id") === attrId; | |
}; | |
}; | |
} else { | |
Expr.find["ID"] = function( id, context ) { | |
if ( typeof context.getElementById !== strundefined && !documentIsXML ) { | |
var m = context.getElementById( id ); | |
return m ? | |
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? | |
[m] : | |
undefined : | |
[]; | |
} | |
}; | |
Expr.filter["ID"] = function( id ) { | |
var attrId = id.replace( runescape, funescape ); | |
return function( elem ) { | |
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); | |
return node && node.value === attrId; | |
}; | |
}; | |
} | |
// Tag | |
Expr.find["TAG"] = support.tagNameNoComments ? | |
function( tag, context ) { | |
if ( typeof context.getElementsByTagName !== strundefined ) { | |
return context.getElementsByTagName( tag ); | |
} | |
} : | |
function( tag, context ) { | |
var elem, | |
tmp = [], | |
i = 0, | |
results = context.getElementsByTagName( tag ); | |
// Filter out possible comments | |
if ( tag === "*" ) { | |
while ( (elem = results[i++]) ) { | |
if ( elem.nodeType === 1 ) { | |
tmp.push( elem ); | |
} | |
} | |
return tmp; | |
} | |
return results; | |
}; | |
// Name | |
Expr.find["NAME"] = support.getByName && function( tag, context ) { | |
if ( typeof context.getElementsByName !== strundefined ) { | |
return context.getElementsByName( name ); | |
} | |
}; | |
// Class | |
Expr.find["CLASS"] = support.getByClassName && function( className, context ) { | |
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { | |
return context.getElementsByClassName( className ); | |
} | |
}; | |
// QSA and matchesSelector support | |
// matchesSelector(:active) reports false when true (IE9/Opera 11.5) | |
rbuggyMatches = []; | |
// qSa(:focus) reports false when true (Chrome 21), | |
// no need to also add to buggyMatches since matches checks buggyQSA | |
// A support test would require too much code (would include document ready) | |
rbuggyQSA = [ ":focus" ]; | |
if ( (support.qsa = isNative(doc.querySelectorAll)) ) { | |
// Build QSA regex | |
// Regex strategy adopted from Diego Perini | |
assert(function( div ) { | |
// Select is set to empty string on purpose | |
// This is to test IE's treatment of not explictly | |
// setting a boolean content attribute, | |
// since its presence should be enough | |
// http://bugs.jquery.com/ticket/12359 | |
div.innerHTML = "<select><option selected=''></option></select>"; | |
// IE8 - Some boolean attributes are not treated correctly | |
if ( !div.querySelectorAll("[selected]").length ) { | |
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); | |
} | |
// Webkit/Opera - :checked should return selected option elements | |
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked | |
// IE8 throws error here and will not see later tests | |
if ( !div.querySelectorAll(":checked").length ) { | |
rbuggyQSA.push(":checked"); | |
} | |
}); | |
assert(function( div ) { | |
// Opera 10-12/IE8 - ^= $= *= and empty values | |
// Should not select anything | |
div.innerHTML = "<input type='hidden' i=''/>"; | |
if ( div.querySelectorAll("[i^='']").length ) { | |
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); | |
} | |
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) | |
// IE8 throws error here and will not see later tests | |
if ( !div.querySelectorAll(":enabled").length ) { | |
rbuggyQSA.push( ":enabled", ":disabled" ); | |
} | |
// Opera 10-11 does not throw on post-comma invalid pseudos | |
div.querySelectorAll("*,:x"); | |
rbuggyQSA.push(",.*:"); | |
}); | |
} | |
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || | |
docElem.mozMatchesSelector || | |
docElem.webkitMatchesSelector || | |
docElem.oMatchesSelector || | |
docElem.msMatchesSelector) )) ) { | |
assert(function( div ) { | |
// Check to see if it's possible to do matchesSelector | |
// on a disconnected node (IE 9) | |
support.disconnectedMatch = matches.call( div, "div" ); | |
// This should fail with an exception | |
// Gecko does not error, returns false instead | |
matches.call( div, "[s!='']:x" ); | |
rbuggyMatches.push( "!=", pseudos ); | |
}); | |
} | |
rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); | |
rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); | |
// Element contains another | |
// Purposefully does not implement inclusive descendent | |
// As in, an element does not contain itself | |
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? | |
function( a, b ) { | |
var adown = a.nodeType === 9 ? a.documentElement : a, | |
bup = b && b.parentNode; | |
return a === bup || !!( bup && bup.nodeType === 1 && ( | |
adown.contains ? | |
adown.contains( bup ) : | |
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 | |
)); | |
} : | |
function( a, b ) { | |
if ( b ) { | |
while ( (b = b.parentNode) ) { | |
if ( b === a ) { | |
return true; | |
} | |
} | |
} | |
return false; | |
}; | |
// Document order sorting | |
sortOrder = docElem.compareDocumentPosition ? | |
function( a, b ) { | |
var compare; | |
if ( a === b ) { | |
hasDuplicate = true; | |
return 0; | |
} | |
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { | |
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { | |
if ( a === doc || contains( preferredDoc, a ) ) { | |
return -1; | |
} | |
if ( b === doc || contains( preferredDoc, b ) ) { | |
return 1; | |
} | |
return 0; | |
} | |
return compare & 4 ? -1 : 1; | |
} | |
return a.compareDocumentPosition ? -1 : 1; | |
} : | |
function( a, b ) { | |
var cur, | |
i = 0, | |
aup = a.parentNode, | |
bup = b.parentNode, | |
ap = [ a ], | |
bp = [ b ]; | |
// Exit early if the nodes are identical | |
if ( a === b ) { | |
hasDuplicate = true; | |
return 0; | |
// Parentless nodes are either documents or disconnected | |
} else if ( !aup || !bup ) { | |
return a === doc ? -1 : | |
b === doc ? 1 : | |
aup ? -1 : | |
bup ? 1 : | |
0; | |
// If the nodes are siblings, we can do a quick check | |
} else if ( aup === bup ) { | |
return siblingCheck( a, b ); | |
} | |
// Otherwise we need full lists of their ancestors for comparison | |
cur = a; | |
while ( (cur = cur.parentNode) ) { | |
ap.unshift( cur ); | |
} | |
cur = b; | |
while ( (cur = cur.parentNode) ) { | |
bp.unshift( cur ); | |
} | |
// Walk down the tree looking for a discrepancy | |
while ( ap[i] === bp[i] ) { | |
i++; | |
} | |
return i ? | |
// Do a sibling check if the nodes have a common ancestor | |
siblingCheck( ap[i], bp[i] ) : | |
// Otherwise nodes in our document sort first | |
ap[i] === preferredDoc ? -1 : | |
bp[i] === preferredDoc ? 1 : | |
0; | |
}; | |
// Always assume the presence of duplicates if sort doesn't | |
// pass them to our comparison function (as in Google Chrome). | |
hasDuplicate = false; | |
[0, 0].sort( sortOrder ); | |
support.detectDuplicates = hasDuplicate; | |
return document; | |
}; | |
Sizzle.matches = function( expr, elements ) { | |
return Sizzle( expr, null, null, elements ); | |
}; | |
Sizzle.matchesSelector = function( elem, expr ) { | |
// Set document vars if needed | |
if ( ( elem.ownerDocument || elem ) !== document ) { | |
setDocument( elem ); | |
} | |
// Make sure that attribute selectors are quoted | |
expr = expr.replace( rattributeQuotes, "='$1']" ); | |
// rbuggyQSA always contains :focus, so no need for an existence check | |
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { | |
try { | |
var ret = matches.call( elem, expr ); | |
// IE 9's matchesSelector returns false on disconnected nodes | |
if ( ret || support.disconnectedMatch || | |
// As well, disconnected nodes are said to be in a document | |
// fragment in IE 9 | |
elem.document && elem.document.nodeType !== 11 ) { | |
return ret; | |
} | |
} catch(e) {} | |
} | |
return Sizzle( expr, document, null, [elem] ).length > 0; | |
}; | |
Sizzle.contains = function( context, elem ) { | |
// Set document vars if needed | |
if ( ( context.ownerDocument || context ) !== document ) { | |
setDocument( context ); | |
} | |
return contains( context, elem ); | |
}; | |
Sizzle.attr = function( elem, name ) { | |
var val; | |
// Set document vars if needed | |
if ( ( elem.ownerDocument || elem ) !== document ) { | |
setDocument( elem ); | |
} | |
if ( !documentIsXML ) { | |
name = name.toLowerCase(); | |
} | |
if ( (val = Expr.attrHandle[ name ]) ) { | |
return val( elem ); | |
} | |
if ( documentIsXML || support.attributes ) { | |
return elem.getAttribute( name ); | |
} | |
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? | |
name : | |
val && val.specified ? val.value : null; | |
}; | |
Sizzle.error = function( msg ) { | |
throw new Error( "Syntax error, unrecognized expression: " + msg ); | |
}; | |
// Document sorting and removing duplicates | |
Sizzle.uniqueSort = function( results ) { | |
var elem, | |
duplicates = [], | |
i = 1, | |
j = 0; | |
// Unless we *know* we can detect duplicates, assume their presence | |
hasDuplicate = !support.detectDuplicates; | |
results.sort( sortOrder ); | |
if ( hasDuplicate ) { | |
for ( ; (elem = results[i]); i++ ) { | |
if ( elem === results[ i - 1 ] ) { | |
j = duplicates.push( i ); | |
} | |
} | |
while ( j-- ) { | |
results.splice( duplicates[ j ], 1 ); | |
} | |
} | |
return results; | |
}; | |
function siblingCheck( a, b ) { | |
var cur = b && a, | |
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); | |
// Use IE sourceIndex if available on both nodes | |
if ( diff ) { | |
return diff; | |
} | |
// Check if b follows a | |
if ( cur ) { | |
while ( (cur = cur.nextSibling) ) { | |
if ( cur === b ) { | |
return -1; | |
} | |
} | |
} | |
return a ? 1 : -1; | |
} | |
// Returns a function to use in pseudos for input types | |
function createInputPseudo( type ) { | |
return function( elem ) { | |
var name = elem.nodeName.toLowerCase(); | |
return name === "input" && elem.type === type; | |
}; | |
} | |
// Returns a function to use in pseudos for buttons | |
function createButtonPseudo( type ) { | |
return function( elem ) { | |
var name = elem.nodeName.toLowerCase(); | |
return (name === "input" || name === "button") && elem.type === type; | |
}; | |
} | |
// Returns a function to use in pseudos for positionals | |
function createPositionalPseudo( fn ) { | |
return markFunction(function( argument ) { | |
argument = +argument; | |
return markFunction(function( seed, matches ) { | |
var j, | |
matchIndexes = fn( [], seed.length, argument ), | |
i = matchIndexes.length; | |
// Match elements found at the specified indexes | |
while ( i-- ) { | |
if ( seed[ (j = matchIndexes[i]) ] ) { | |
seed[j] = !(matches[j] = seed[j]); | |
} | |
} | |
}); | |
}); | |
} | |
/** | |
* Utility function for retrieving the text value of an array of DOM nodes | |
* @param {Array|Element} elem | |
*/ | |
getText = Sizzle.getText = function( elem ) { | |
var node, | |
ret = "", | |
i = 0, | |
nodeType = elem.nodeType; | |
if ( !nodeType ) { | |
// If no nodeType, this is expected to be an array | |
for ( ; (node = elem[i]); i++ ) { | |
// Do not traverse comment nodes | |
ret += getText( node ); | |
} | |
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { | |
// Use textContent for elements | |
// innerText usage removed for consistency of new lines (see #11153) | |
if ( typeof elem.textContent === "string" ) { | |
return elem.textContent; | |
} else { | |
// Traverse its children | |
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { | |
ret += getText( elem ); | |
} | |
} | |
} else if ( nodeType === 3 || nodeType === 4 ) { | |
return elem.nodeValue; | |
} | |
// Do not include comment or processing instruction nodes | |
return ret; | |
}; | |
Expr = Sizzle.selectors = { | |
// Can be adjusted by the user | |
cacheLength: 50, | |
createPseudo: markFunction, | |
match: matchExpr, | |
find: {}, | |
relative: { | |
">": { dir: "parentNode", first: true }, | |
" ": { dir: "parentNode" }, | |
"+": { dir: "previousSibling", first: true }, | |
"~": { dir: "previousSibling" } | |
}, | |
preFilter: { | |
"ATTR": function( match ) { | |
match[1] = match[1].replace( runescape, funescape ); | |
// Move the given value to match[3] whether quoted or unquoted | |
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); | |
if ( match[2] === "~=" ) { | |
match[3] = " " + match[3] + " "; | |
} | |
return match.slice( 0, 4 ); | |
}, | |
"CHILD": function( match ) { | |
/* matches from matchExpr["CHILD"] | |
1 type (only|nth|...) | |
2 what (child|of-type) | |
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) | |
4 xn-component of xn+y argument ([+-]?\d*n|) | |
5 sign of xn-component | |
6 x of xn-component | |
7 sign of y-component | |
8 y of y-component | |
*/ | |
match[1] = match[1].toLowerCase(); | |
if ( match[1].slice( 0, 3 ) === "nth" ) { | |
// nth-* requires argument | |
if ( !match[3] ) { | |
Sizzle.error( match[0] ); | |
} | |
// numeric x and y parameters for Expr.filter.CHILD | |
// remember that false/true cast respectively to 0/1 | |
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); | |
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); | |
// other types prohibit arguments | |
} else if ( match[3] ) { | |
Sizzle.error( match[0] ); | |
} | |
return match; | |
}, | |
"PSEUDO": function( match ) { | |
var excess, | |
unquoted = !match[5] && match[2]; | |
if ( matchExpr["CHILD"].test( match[0] ) ) { | |
return null; | |
} | |
// Accept quoted arguments as-is | |
if ( match[4] ) { | |
match[2] = match[4]; | |
// Strip excess characters from unquoted arguments | |
} else if ( unquoted && rpseudo.test( unquoted ) && | |
// Get excess from tokenize (recursively) | |
(excess = tokenize( unquoted, true )) && | |
// advance to the next closing parenthesis | |
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { | |
// excess is a negative index | |
match[0] = match[0].slice( 0, excess ); | |
match[2] = unquoted.slice( 0, excess ); | |
} | |
// Return only captures needed by the pseudo filter method (type and argument) | |
return match.slice( 0, 3 ); | |
} | |
}, | |
filter: { | |
"TAG": function( nodeName ) { | |
if ( nodeName === "*" ) { | |
return function() { return true; }; | |
} | |
nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); | |
return function( elem ) { | |
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; | |
}; | |
}, | |
"CLASS": function( className ) { | |
var pattern = classCache[ className + " " ]; | |
return pattern || | |
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && | |
classCache( className, function( elem ) { | |
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); | |
}); | |
}, | |
"ATTR": function( name, operator, check ) { | |
return function( elem ) { | |
var result = Sizzle.attr( elem, name ); | |
if ( result == null ) { | |
return operator === "!="; | |
} | |
if ( !operator ) { | |
return true; | |
} | |
result += ""; | |
return operator === "=" ? result === check : | |
operator === "!=" ? result !== check : | |
operator === "^=" ? check && result.indexOf( check ) === 0 : | |
operator === "*=" ? check && result.indexOf( check ) > -1 : | |
operator === "$=" ? check && result.slice( -check.length ) === check : | |
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : | |
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : | |
false; | |
}; | |
}, | |
"CHILD": function( type, what, argument, first, last ) { | |
var simple = type.slice( 0, 3 ) !== "nth", | |
forward = type.slice( -4 ) !== "last", | |
ofType = what === "of-type"; | |
return first === 1 && last === 0 ? | |
// Shortcut for :nth-*(n) | |
function( elem ) { | |
return !!elem.parentNode; | |
} : | |
function( elem, context, xml ) { | |
var cache, outerCache, node, diff, nodeIndex, start, | |
dir = simple !== forward ? "nextSibling" : "previousSibling", | |
parent = elem.parentNode, | |
name = ofType && elem.nodeName.toLowerCase(), | |
useCache = !xml && !ofType; | |
if ( parent ) { | |
// :(first|last|only)-(child|of-type) | |
if ( simple ) { | |
while ( dir ) { | |
node = elem; | |
while ( (node = node[ dir ]) ) { | |
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { | |
return false; | |
} | |
} | |
// Reverse direction for :only-* (if we haven't yet done so) | |
start = dir = type === "only" && !start && "nextSibling"; | |
} | |
return true; | |
} | |
start = [ forward ? parent.firstChild : parent.lastChild ]; | |
// non-xml :nth-child(...) stores cache data on `parent` | |
if ( forward && useCache ) { | |
// Seek `elem` from a previously-cached index | |
outerCache = parent[ expando ] || (parent[ expando ] = {}); | |
cache = outerCache[ type ] || []; | |
nodeIndex = cache[0] === dirruns && cache[1]; | |
diff = cache[0] === dirruns && cache[2]; | |
node = nodeIndex && parent.childNodes[ nodeIndex ]; | |
while ( (node = ++nodeIndex && node && node[ dir ] || | |
// Fallback to seeking `elem` from the start | |
(diff = nodeIndex = 0) || start.pop()) ) { | |
// When found, cache indexes on `parent` and break | |
if ( node.nodeType === 1 && ++diff && node === elem ) { | |
outerCache[ type ] = [ dirruns, nodeIndex, diff ]; | |
break; | |
} | |
} | |
// Use previously-cached element index if available | |
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { | |
diff = cache[1]; | |
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) | |
} else { | |
// Use the same loop as above to seek `elem` from the start | |
while ( (node = ++nodeIndex && node && node[ dir ] || | |
(diff = nodeIndex = 0) || start.pop()) ) { | |
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { | |
// Cache the index of each encountered element | |
if ( useCache ) { | |
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; | |
} | |
if ( node === elem ) { | |
break; | |
} | |
} | |
} | |
} | |
// Incorporate the offset, then check against cycle size | |
diff -= last; | |
return diff === first || ( diff % first === 0 && diff / first >= 0 ); | |
} | |
}; | |
}, | |
"PSEUDO": function( pseudo, argument ) { | |
// pseudo-class names are case-insensitive | |
// http://www.w3.org/TR/selectors/#pseudo-classes | |
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters | |
// Remember that setFilters inherits from pseudos | |
var args, | |
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || | |
Sizzle.error( "unsupported pseudo: " + pseudo ); | |
// The user may use createPseudo to indicate that | |
// arguments are needed to create the filter function | |
// just as Sizzle does | |
if ( fn[ expando ] ) { | |
return fn( argument ); | |
} | |
// But maintain support for old signatures | |
if ( fn.length > 1 ) { | |
args = [ pseudo, pseudo, "", argument ]; | |
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? | |
markFunction(function( seed, matches ) { | |
var idx, | |
matched = fn( seed, argument ), | |
i = matched.length; | |
while ( i-- ) { | |
idx = indexOf.call( seed, matched[i] ); | |
seed[ idx ] = !( matches[ idx ] = matched[i] ); | |
} | |
}) : | |
function( elem ) { | |
return fn( elem, 0, args ); | |
}; | |
} | |
return fn; | |
} | |
}, | |
pseudos: { | |
// Potentially complex pseudos | |
"not": markFunction(function( selector ) { | |
// Trim the selector passed to compile | |
// to avoid treating leading and trailing | |
// spaces as combinators | |
var input = [], | |
results = [], | |
matcher = compile( selector.replace( rtrim, "$1" ) ); | |
return matcher[ expando ] ? | |
markFunction(function( seed, matches, context, xml ) { | |
var elem, | |
unmatched = matcher( seed, null, xml, [] ), | |
i = seed.length; | |
// Match elements unmatched by `matcher` | |
while ( i-- ) { | |
if ( (elem = unmatched[i]) ) { | |
seed[i] = !(matches[i] = elem); | |
} | |
} | |
}) : | |
function( elem, context, xml ) { | |
input[0] = elem; | |
matcher( input, null, xml, results ); | |
return !results.pop(); | |
}; | |
}), | |
"has": markFunction(function( selector ) { | |
return function( elem ) { | |
return Sizzle( selector, elem ).length > 0; | |
}; | |
}), | |
"contains": markFunction(function( text ) { | |
return function( elem ) { | |
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; | |
}; | |
}), | |
// "Whether an element is represented by a :lang() selector | |
// is based solely on the element's language value | |
// being equal to the identifier C, | |
// or beginning with the identifier C immediately followed by "-". | |
// The matching of C against the element's language value is performed case-insensitively. | |
// The identifier C does not have to be a valid language name." | |
// http://www.w3.org/TR/selectors/#lang-pseudo | |
"lang": markFunction( function( lang ) { | |
// lang value must be a valid identifider | |
if ( !ridentifier.test(lang || "") ) { | |
Sizzle.error( "unsupported lang: " + lang ); | |
} | |
lang = lang.replace( runescape, funescape ).toLowerCase(); | |
return function( elem ) { | |
var elemLang; | |
do { | |
if ( (elemLang = documentIsXML ? | |
elem.getAttribute("xml:lang") || elem.getAttribute("lang") : | |
elem.lang) ) { | |
elemLang = elemLang.toLowerCase(); | |
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; | |
} | |
} while ( (elem = elem.parentNode) && elem.nodeType === 1 ); | |
return false; | |
}; | |
}), | |
// Miscellaneous | |
"target": function( elem ) { | |
var hash = window.location && window.location.hash; | |
return hash && hash.slice( 1 ) === elem.id; | |
}, | |
"root": function( elem ) { | |
return elem === docElem; | |
}, | |
"focus": function( elem ) { | |
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); | |
}, | |
// Boolean properties | |
"enabled": function( elem ) { | |
return elem.disabled === false; | |
}, | |
"disabled": function( elem ) { | |
return elem.disabled === true; | |
}, | |
"checked": function( elem ) { | |
// In CSS3, :checked should return both checked and selected elements | |
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked | |
var nodeName = elem.nodeName.toLowerCase(); | |
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); | |
}, | |
"selected": function( elem ) { | |
// Accessing this property makes selected-by-default | |
// options in Safari work properly | |
if ( elem.parentNode ) { | |
elem.parentNode.selectedIndex; | |
} | |
return elem.selected === true; | |
}, | |
// Contents | |
"empty": function( elem ) { | |
// http://www.w3.org/TR/selectors/#empty-pseudo | |
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), | |
// not comment, processing instructions, or others | |
// Thanks to Diego Perini for the nodeName shortcut | |
// Greater than "@" means alpha characters (specifically not starting with "#" or "?") | |
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { | |
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { | |
return false; | |
} | |
} | |
return true; | |
}, | |
"parent": function( elem ) { | |
return !Expr.pseudos["empty"]( elem ); | |
}, | |
// Element/input types | |
"header": function( elem ) { | |
return rheader.test( elem.nodeName ); | |
}, | |
"input": function( elem ) { | |
return rinputs.test( elem.nodeName ); | |
}, | |
"button": function( elem ) { | |
var name = elem.nodeName.toLowerCase(); | |
return name === "input" && elem.type === "button" || name === "button"; | |
}, | |
"text": function( elem ) { | |
var attr; | |
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) | |
// use getAttribute instead to test this case | |
return elem.nodeName.toLowerCase() === "input" && | |
elem.type === "text" && | |
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); | |
}, | |
// Position-in-collection | |
"first": createPositionalPseudo(function() { | |
return [ 0 ]; | |
}), | |
"last": createPositionalPseudo(function( matchIndexes, length ) { | |
return [ length - 1 ]; | |
}), | |
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) { | |
return [ argument < 0 ? argument + length : argument ]; | |
}), | |
"even": createPositionalPseudo(function( matchIndexes, length ) { | |
var i = 0; | |
for ( ; i < length; i += 2 ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}), | |
"odd": createPositionalPseudo(function( matchIndexes, length ) { | |
var i = 1; | |
for ( ; i < length; i += 2 ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}), | |
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) { | |
var i = argument < 0 ? argument + length : argument; | |
for ( ; --i >= 0; ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}), | |
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) { | |
var i = argument < 0 ? argument + length : argument; | |
for ( ; ++i < length; ) { | |
matchIndexes.push( i ); | |
} | |
return matchIndexes; | |
}) | |
} | |
}; | |
// Add button/input type pseudos | |
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { | |
Expr.pseudos[ i ] = createInputPseudo( i ); | |
} | |
for ( i in { submit: true, reset: true } ) { | |
Expr.pseudos[ i ] = createButtonPseudo( i ); | |
} | |
function tokenize( selector, parseOnly ) { | |
var matched, match, tokens, type, | |
soFar, groups, preFilters, | |
cached = tokenCache[ selector + " " ]; | |
if ( cached ) { | |
return parseOnly ? 0 : cached.slice( 0 ); | |
} | |
soFar = selector; | |
groups = []; | |
preFilters = Expr.preFilter; | |
while ( soFar ) { | |
// Comma and first run | |
if ( !matched || (match = rcomma.exec( soFar )) ) { | |
if ( match ) { | |
// Don't consume trailing commas as valid | |
soFar = soFar.slice( match[0].length ) || soFar; | |
} | |
groups.push( tokens = [] ); | |
} | |
matched = false; | |
// Combinators | |
if ( (match = rcombinators.exec( soFar )) ) { | |
matched = match.shift(); | |
tokens.push( { | |
value: matched, | |
// Cast descendant combinators to space | |
type: match[0].replace( rtrim, " " ) | |
} ); | |
soFar = soFar.slice( matched.length ); | |
} | |
// Filters | |
for ( type in Expr.filter ) { | |
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || | |
(match = preFilters[ type ]( match ))) ) { | |
matched = match.shift(); | |
tokens.push( { | |
value: matched, | |
type: type, | |
matches: match | |
} ); | |
soFar = soFar.slice( matched.length ); | |
} | |
} | |
if ( !matched ) { | |
break; | |
} | |
} | |
// Return the length of the invalid excess | |
// if we're just parsing | |
// Otherwise, throw an error or return tokens | |
return parseOnly ? | |
soFar.length : | |
soFar ? | |
Sizzle.error( selector ) : | |
// Cache the tokens | |
tokenCache( selector, groups ).slice( 0 ); | |
} | |
function toSelector( tokens ) { | |
var i = 0, | |
len = tokens.length, | |
selector = ""; | |
for ( ; i < len; i++ ) { | |
selector += tokens[i].value; | |
} | |
return selector; | |
} | |
function addCombinator( matcher, combinator, base ) { | |
var dir = combinator.dir, | |
checkNonElements = base && dir === "parentNode", | |
doneName = done++; | |
return combinator.first ? | |
// Check against closest ancestor/preceding element | |
function( elem, context, xml ) { | |
while ( (elem = elem[ dir ]) ) { | |
if ( elem.nodeType === 1 || checkNonElements ) { | |
return matcher( elem, context, xml ); | |
} | |
} | |
} : | |
// Check against all ancestor/preceding elements | |
function( elem, context, xml ) { | |
var data, cache, outerCache, | |
dirkey = dirruns + " " + doneName; | |
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching | |
if ( xml ) { | |
while ( (elem = elem[ dir ]) ) { | |
if ( elem.nodeType === 1 || checkNonElements ) { | |
if ( matcher( elem, context, xml ) ) { | |
return true; | |
} | |
} | |
} | |
} else { | |
while ( (elem = elem[ dir ]) ) { | |
if ( elem.nodeType === 1 || checkNonElements ) { | |
outerCache = elem[ expando ] || (elem[ expando ] = {}); | |
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { | |
if ( (data = cache[1]) === true || data === cachedruns ) { | |
return data === true; | |
} | |
} else { | |
cache = outerCache[ dir ] = [ dirkey ]; | |
cache[1] = matcher( elem, context, xml ) || cachedruns; | |
if ( cache[1] === true ) { | |
return true; | |
} | |
} | |
} | |
} | |
} | |
}; | |
} | |
function elementMatcher( matchers ) { | |
return matchers.length > 1 ? | |
function( elem, context, xml ) { | |
var i = matchers.length; | |
while ( i-- ) { | |
if ( !matchers[i]( elem, context, xml ) ) { | |
return false; | |
} | |
} | |
return true; | |
} : | |
matchers[0]; | |
} | |
function condense( unmatched, map, filter, context, xml ) { | |
var elem, | |
newUnmatched = [], | |
i = 0, | |
len = unmatched.length, | |
mapped = map != null; | |
for ( ; i < len; i++ ) { | |
if ( (elem = unmatched[i]) ) { | |
if ( !filter || filter( elem, context, xml ) ) { | |
newUnmatched.push( elem ); | |
if ( mapped ) { | |
map.push( i ); | |
} | |
} | |
} | |
} | |
return newUnmatched; | |
} | |
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { | |
if ( postFilter && !postFilter[ expando ] ) { | |
postFilter = setMatcher( postFilter ); | |
} | |
if ( postFinder && !postFinder[ expando ] ) { | |
postFinder = setMatcher( postFinder, postSelector ); | |
} | |
return markFunction(function( seed, results, context, xml ) { | |
var temp, i, elem, | |
preMap = [], | |
postMap = [], | |
preexisting = results.length, | |
// Get initial elements from seed or context | |
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), | |
// Prefilter to get matcher input, preserving a map for seed-results synchronization | |
matcherIn = preFilter && ( seed || !selector ) ? | |
condense( elems, preMap, preFilter, context, xml ) : | |
elems, | |
matcherOut = matcher ? | |
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, | |
postFinder || ( seed ? preFilter : preexisting || postFilter ) ? | |
// ...intermediate processing is necessary | |
[] : | |
// ...otherwise use results directly | |
results : | |
matcherIn; | |
// Find primary matches | |
if ( matcher ) { | |
matcher( matcherIn, matcherOut, context, xml ); | |
} | |
// Apply postFilter | |
if ( postFilter ) { | |
temp = condense( matcherOut, postMap ); | |
postFilter( temp, [], context, xml ); | |
// Un-match failing elements by moving them back to matcherIn | |
i = temp.length; | |
while ( i-- ) { | |
if ( (elem = temp[i]) ) { | |
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); | |
} | |
} | |
} | |
if ( seed ) { | |
if ( postFinder || preFilter ) { | |
if ( postFinder ) { | |
// Get the final matcherOut by condensing this intermediate into postFinder contexts | |
temp = []; | |
i = matcherOut.length; | |
while ( i-- ) { | |
if ( (elem = matcherOut[i]) ) { | |
// Restore matcherIn since elem is not yet a final match | |
temp.push( (matcherIn[i] = elem) ); | |
} | |
} | |
postFinder( null, (matcherOut = []), temp, xml ); | |
} | |
// Move matched elements from seed to results to keep them synchronized | |
i = matcherOut.length; | |
while ( i-- ) { | |
if ( (elem = matcherOut[i]) && | |
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { | |
seed[temp] = !(results[temp] = elem); | |
} | |
} | |
} | |
// Add elements to results, through postFinder if defined | |
} else { | |
matcherOut = condense( | |
matcherOut === results ? | |
matcherOut.splice( preexisting, matcherOut.length ) : | |
matcherOut | |
); | |
if ( postFinder ) { | |
postFinder( null, results, matcherOut, xml ); | |
} else { | |
push.apply( results, matcherOut ); | |
} | |
} | |
}); | |
} | |
function matcherFromTokens( tokens ) { | |
var checkContext, matcher, j, | |
len = tokens.length, | |
leadingRelative = Expr.relative[ tokens[0].type ], | |
implicitRelative = leadingRelative || Expr.relative[" "], | |
i = leadingRelative ? 1 : 0, | |
// The foundational matcher ensures that elements are reachable from top-level context(s) | |
matchContext = addCombinator( function( elem ) { | |
return elem === checkContext; | |
}, implicitRelative, true ), | |
matchAnyContext = addCombinator( function( elem ) { | |
return indexOf.call( checkContext, elem ) > -1; | |
}, implicitRelative, true ), | |
matchers = [ function( elem, context, xml ) { | |
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( | |
(checkContext = context).nodeType ? | |
matchContext( elem, context, xml ) : | |
matchAnyContext( elem, context, xml ) ); | |
} ]; | |
for ( ; i < len; i++ ) { | |
if ( (matcher = Expr.relative[ tokens[i].type ]) ) { | |
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; | |
} else { | |
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); | |
// Return special upon seeing a positional matcher | |
if ( matcher[ expando ] ) { | |
// Find the next relative operator (if any) for proper handling | |
j = ++i; | |
for ( ; j < len; j++ ) { | |
if ( Expr.relative[ tokens[j].type ] ) { | |
break; | |
} | |
} | |
return setMatcher( | |
i > 1 && elementMatcher( matchers ), | |
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), | |
matcher, | |
i < j && matcherFromTokens( tokens.slice( i, j ) ), | |
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), | |
j < len && toSelector( tokens ) | |
); | |
} | |
matchers.push( matcher ); | |
} | |
} | |
return elementMatcher( matchers ); | |
} | |
function matcherFromGroupMatchers( elementMatchers, setMatchers ) { | |
// A counter to specify which element is currently being matched | |
var matcherCachedRuns = 0, | |
bySet = setMatchers.length > 0, | |
byElement = elementMatchers.length > 0, | |
superMatcher = function( seed, context, xml, results, expandContext ) { | |
var elem, j, matcher, | |
setMatched = [], | |
matchedCount = 0, | |
i = "0", | |
unmatched = seed && [], | |
outermost = expandContext != null, | |
contextBackup = outermostContext, | |
// We must always have either seed elements or context | |
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), | |
// Use integer dirruns iff this is the outermost matcher | |
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); | |
if ( outermost ) { | |
outermostContext = context !== document && context; | |
cachedruns = matcherCachedRuns; | |
} | |
// Add elements passing elementMatchers directly to results | |
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below | |
for ( ; (elem = elems[i]) != null; i++ ) { | |
if ( byElement && elem ) { | |
j = 0; | |
while ( (matcher = elementMatchers[j++]) ) { | |
if ( matcher( elem, context, xml ) ) { | |
results.push( elem ); | |
break; | |
} | |
} | |
if ( outermost ) { | |
dirruns = dirrunsUnique; | |
cachedruns = ++matcherCachedRuns; | |
} | |
} | |
// Track unmatched elements for set filters | |
if ( bySet ) { | |
// They will have gone through all possible matchers | |
if ( (elem = !matcher && elem) ) { | |
matchedCount--; | |
} | |
// Lengthen the array for every element, matched or not | |
if ( seed ) { | |
unmatched.push( elem ); | |
} | |
} | |
} | |
// Apply set filters to unmatched elements | |
matchedCount += i; | |
if ( bySet && i !== matchedCount ) { | |
j = 0; | |
while ( (matcher = setMatchers[j++]) ) { | |
matcher( unmatched, setMatched, context, xml ); | |
} | |
if ( seed ) { | |
// Reintegrate element matches to eliminate the need for sorting | |
if ( matchedCount > 0 ) { | |
while ( i-- ) { | |
if ( !(unmatched[i] || setMatched[i]) ) { | |
setMatched[i] = pop.call( results ); | |
} | |
} | |
} | |
// Discard index placeholder values to get only actual matches | |
setMatched = condense( setMatched ); | |
} | |
// Add matches to results | |
push.apply( results, setMatched ); | |
// Seedless set matches succeeding multiple successful matchers stipulate sorting | |
if ( outermost && !seed && setMatched.length > 0 && | |
( matchedCount + setMatchers.length ) > 1 ) { | |
Sizzle.uniqueSort( results ); | |
} | |
} | |
// Override manipulation of globals by nested matchers | |
if ( outermost ) { | |
dirruns = dirrunsUnique; | |
outermostContext = contextBackup; | |
} | |
return unmatched; | |
}; | |
return bySet ? | |
markFunction( superMatcher ) : | |
superMatcher; | |
} | |
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { | |
var i, | |
setMatchers = [], | |
elementMatchers = [], | |
cached = compilerCache[ selector + " " ]; | |
if ( !cached ) { | |
// Generate a function of recursive functions that can be used to check each element | |
if ( !group ) { | |
group = tokenize( selector ); | |
} | |
i = group.length; | |
while ( i-- ) { | |
cached = matcherFromTokens( group[i] ); | |
if ( cached[ expando ] ) { | |
setMatchers.push( cached ); | |
} else { | |
elementMatchers.push( cached ); | |
} | |
} | |
// Cache the compiled function | |
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); | |
} | |
return cached; | |
}; | |
function multipleContexts( selector, contexts, results ) { | |
var i = 0, | |
len = contexts.length; | |
for ( ; i < len; i++ ) { | |
Sizzle( selector, contexts[i], results ); | |
} | |
return results; | |
} | |
function select( selector, context, results, seed ) { | |
var i, tokens, token, type, find, | |
match = tokenize( selector ); | |
if ( !seed ) { | |
// Try to minimize operations if there is only one group | |
if ( match.length === 1 ) { | |
// Take a shortcut and set the context if the root selector is an ID | |
tokens = match[0] = match[0].slice( 0 ); | |
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && | |
context.nodeType === 9 && !documentIsXML && | |
Expr.relative[ tokens[1].type ] ) { | |
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; | |
if ( !context ) { | |
return results; | |
} | |
selector = selector.slice( tokens.shift().value.length ); | |
} | |
// Fetch a seed set for right-to-left matching | |
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; | |
while ( i-- ) { | |
token = tokens[i]; | |
// Abort if we hit a combinator | |
if ( Expr.relative[ (type = token.type) ] ) { | |
break; | |
} | |
if ( (find = Expr.find[ type ]) ) { | |
// Search, expanding context for leading sibling combinators | |
if ( (seed = find( | |
token.matches[0].replace( runescape, funescape ), | |
rsibling.test( tokens[0].type ) && context.parentNode || context | |
)) ) { | |
// If seed is empty or no tokens remain, we can return early | |
tokens.splice( i, 1 ); | |
selector = seed.length && toSelector( tokens ); | |
if ( !selector ) { | |
push.apply( results, slice.call( seed, 0 ) ); | |
return results; | |
} | |
break; | |
} | |
} | |
} | |
} | |
} | |
// Compile and execute a filtering function | |
// Provide `match` to avoid retokenization if we modified the selector above | |
compile( selector, match )( | |
seed, | |
context, | |
documentIsXML, | |
results, | |
rsibling.test( selector ) | |
); | |
return results; | |
} | |
// Deprecated | |
Expr.pseudos["nth"] = Expr.pseudos["eq"]; | |
// Easy API for creating new setFilters | |
function setFilters() {} | |
Expr.filters = setFilters.prototype = Expr.pseudos; | |
Expr.setFilters = new setFilters(); | |
// Initialize with the default document | |
setDocument(); | |
// Override sizzle attribute retrieval | |
Sizzle.attr = jQuery.attr; | |
jQuery.find = Sizzle; | |
jQuery.expr = Sizzle.selectors; | |
jQuery.expr[":"] = jQuery.expr.pseudos; | |
jQuery.unique = Sizzle.uniqueSort; | |
jQuery.text = Sizzle.getText; | |
jQuery.isXMLDoc = Sizzle.isXML; | |
jQuery.contains = Sizzle.contains; | |
})( window ); | |
var runtil = /Until$/, | |
rparentsprev = /^(?:parents|prev(?:Until|All))/, | |
isSimple = /^.[^:#\[\.,]*$/, | |
rneedsContext = jQuery.expr.match.needsContext, | |
// methods guaranteed to produce a unique set when starting from a unique set | |
guaranteedUnique = { | |
children: true, | |
contents: true, | |
next: true, | |
prev: true | |
}; | |
jQuery.fn.extend({ | |
find: function( selector ) { | |
var i, ret, self, | |
len = this.length; | |
if ( typeof selector !== "string" ) { | |
self = this; | |
return this.pushStack( jQuery( selector ).filter(function() { | |
for ( i = 0; i < len; i++ ) { | |
if ( jQuery.contains( self[ i ], this ) ) { | |
return true; | |
} | |
} | |
}) ); | |
} | |
ret = []; | |
for ( i = 0; i < len; i++ ) { | |
jQuery.find( selector, this[ i ], ret ); | |
} | |
// Needed because $( selector, context ) becomes $( context ).find( selector ) | |
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); | |
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; | |
return ret; | |
}, | |
has: function( target ) { | |
var i, | |
targets = jQuery( target, this ), | |
len = targets.length; | |
return this.filter(function() { | |
for ( i = 0; i < len; i++ ) { | |
if ( jQuery.contains( this, targets[i] ) ) { | |
return true; | |
} | |
} | |
}); | |
}, | |
not: function( selector ) { | |
return this.pushStack( winnow(this, selector, false) ); | |
}, | |
filter: function( selector ) { | |
return this.pushStack( winnow(this, selector, true) ); | |
}, | |
is: function( selector ) { | |
return !!selector && ( | |
typeof selector === "string" ? | |
// If this is a positional/relative selector, check membership in the returned set | |
// so $("p:first").is("p:last") won't return true for a doc with two "p". | |
rneedsContext.test( selector ) ? | |
jQuery( selector, this.context ).index( this[0] ) >= 0 : | |
jQuery.filter( selector, this ).length > 0 : | |
this.filter( selector ).length > 0 ); | |
}, | |
closest: function( selectors, context ) { | |
var cur, | |
i = 0, | |
l = this.length, | |
ret = [], | |
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? | |
jQuery( selectors, context || this.context ) : | |
0; | |
for ( ; i < l; i++ ) { | |
cur = this[i]; | |
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { | |
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { | |
ret.push( cur ); | |
break; | |
} | |
cur = cur.parentNode; | |
} | |
} | |
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); | |
}, | |
// Determine the position of an element within | |
// the matched set of elements | |
index: function( elem ) { | |
// No argument, return index in parent | |
if ( !elem ) { | |
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; | |
} | |
// index in selector | |
if ( typeof elem === "string" ) { | |
return jQuery.inArray( this[0], jQuery( elem ) ); | |
} | |
// Locate the position of the desired element | |
return jQuery.inArray( | |
// If it receives a jQuery object, the first element is used | |
elem.jquery ? elem[0] : elem, this ); | |
}, | |
add: function( selector, context ) { | |
var set = typeof selector === "string" ? | |
jQuery( selector, context ) : | |
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), | |
all = jQuery.merge( this.get(), set ); | |
return this.pushStack( jQuery.unique(all) ); | |
}, | |
addBack: function( selector ) { | |
return this.add( selector == null ? | |
this.prevObject : this.prevObject.filter(selector) | |
); | |
} | |
}); | |
jQuery.fn.andSelf = jQuery.fn.addBack; | |
function sibling( cur, dir ) { | |
do { | |
cur = cur[ dir ]; | |
} while ( cur && cur.nodeType !== 1 ); | |
return cur; | |
} | |
jQuery.each({ | |
parent: function( elem ) { | |
var parent = elem.parentNode; | |
return parent && parent.nodeType !== 11 ? parent : null; | |
}, | |
parents: function( elem ) { | |
return jQuery.dir( elem, "parentNode" ); | |
}, | |
parentsUntil: function( elem, i, until ) { | |
return jQuery.dir( elem, "parentNode", until ); | |
}, | |
next: function( elem ) { | |
return sibling( elem, "nextSibling" ); | |
}, | |
prev: function( elem ) { | |
return sibling( elem, "previousSibling" ); | |
}, | |
nextAll: function( elem ) { | |
return jQuery.dir( elem, "nextSibling" ); | |
}, | |
prevAll: function( elem ) { | |
return jQuery.dir( elem, "previousSibling" ); | |
}, | |
nextUntil: function( elem, i, until ) { | |
return jQuery.dir( elem, "nextSibling", until ); | |
}, | |
prevUntil: function( elem, i, until ) { | |
return jQuery.dir( elem, "previousSibling", until ); | |
}, | |
siblings: function( elem ) { | |
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); | |
}, | |
children: function( elem ) { | |
return jQuery.sibling( elem.firstChild ); | |
}, | |
contents: function( elem ) { | |
return jQuery.nodeName( elem, "iframe" ) ? | |
elem.contentDocument || elem.contentWindow.document : | |
jQuery.merge( [], elem.childNodes ); | |
} | |
}, function( name, fn ) { | |
jQuery.fn[ name ] = function( until, selector ) { | |
var ret = jQuery.map( this, fn, until ); | |
if ( !runtil.test( name ) ) { | |
selector = until; | |
} | |
if ( selector && typeof selector === "string" ) { | |
ret = jQuery.filter( selector, ret ); | |
} | |
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; | |
if ( this.length > 1 && rparentsprev.test( name ) ) { | |
ret = ret.reverse(); | |
} | |
return this.pushStack( ret ); | |
}; | |
}); | |
jQuery.extend({ | |
filter: function( expr, elems, not ) { | |
if ( not ) { | |
expr = ":not(" + expr + ")"; | |
} | |
return elems.length === 1 ? | |
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : | |
jQuery.find.matches(expr, elems); | |
}, | |
dir: function( elem, dir, until ) { | |
var matched = [], | |
cur = elem[ dir ]; | |
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { | |
if ( cur.nodeType === 1 ) { | |
matched.push( cur ); | |
} | |
cur = cur[dir]; | |
} | |
return matched; | |
}, | |
sibling: function( n, elem ) { | |
var r = []; | |
for ( ; n; n = n.nextSibling ) { | |
if ( n.nodeType === 1 && n !== elem ) { | |
r.push( n ); | |
} | |
} | |
return r; | |
} | |
}); | |
// Implement the identical functionality for filter and not | |
function winnow( elements, qualifier, keep ) { | |
// Can't pass null or undefined to indexOf in Firefox 4 | |
// Set to 0 to skip string check | |
qualifier = qualifier || 0; | |
if ( jQuery.isFunction( qualifier ) ) { | |
return jQuery.grep(elements, function( elem, i ) { | |
var retVal = !!qualifier.call( elem, i, elem ); | |
return retVal === keep; | |
}); | |
} else if ( qualifier.nodeType ) { | |
return jQuery.grep(elements, function( elem ) { | |
return ( elem === qualifier ) === keep; | |
}); | |
} else if ( typeof qualifier === "string" ) { | |
var filtered = jQuery.grep(elements, function( elem ) { | |
return elem.nodeType === 1; | |
}); | |
if ( isSimple.test( qualifier ) ) { | |
return jQuery.filter(qualifier, filtered, !keep); | |
} else { | |
qualifier = jQuery.filter( qualifier, filtered ); | |
} | |
} | |
return jQuery.grep(elements, function( elem ) { | |
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; | |
}); | |
} | |
function createSafeFragment( document ) { | |
var list = nodeNames.split( "|" ), | |
safeFrag = document.createDocumentFragment(); | |
if ( safeFrag.createElement ) { | |
while ( list.length ) { | |
safeFrag.createElement( | |
list.pop() | |
); | |
} | |
} | |
return safeFrag; | |
} | |
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + | |
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", | |
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, | |
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), | |
rleadingWhitespace = /^\s+/, | |
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, | |
rtagName = /<([\w:]+)/, | |
rtbody = /<tbody/i, | |
rhtml = /<|&#?\w+;/, | |
rnoInnerhtml = /<(?:script|style|link)/i, | |
manipulation_rcheckableType = /^(?:checkbox|radio)$/i, | |
// checked="checked" or checked | |
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, | |
rscriptType = /^$|\/(?:java|ecma)script/i, | |
rscriptTypeMasked = /^true\/(.*)/, | |
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, | |
// We have to close these tags to support XHTML (#13200) | |
wrapMap = { | |
option: [ 1, "<select multiple='multiple'>", "</select>" ], | |
legend: [ 1, "<fieldset>", "</fieldset>" ], | |
area: [ 1, "<map>", "</map>" ], | |
param: [ 1, "<object>", "</object>" ], | |
thead: [ 1, "<table>", "</table>" ], | |
tr: [ 2, "<table><tbody>", "</tbody></table>" ], | |
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], | |
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], | |
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, | |
// unless wrapped in a div with non-breaking characters in front of it. | |
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] | |
}, | |
safeFragment = createSafeFragment( document ), | |
fragmentDiv = safeFragment.appendChild( document.createElement("div") ); | |
wrapMap.optgroup = wrapMap.option; | |
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; | |
wrapMap.th = wrapMap.td; | |
jQuery.fn.extend({ | |
text: function( value ) { | |
return jQuery.access( this, function( value ) { | |
return value === undefined ? | |
jQuery.text( this ) : | |
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); | |
}, null, value, arguments.length ); | |
}, | |
wrapAll: function( html ) { | |
if ( jQuery.isFunction( html ) ) { | |
return this.each(function(i) { | |
jQuery(this).wrapAll( html.call(this, i) ); | |
}); | |
} | |
if ( this[0] ) { | |
// The elements to wrap the target around | |
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); | |
if ( this[0].parentNode ) { | |
wrap.insertBefore( this[0] ); | |
} | |
wrap.map(function() { | |
var elem = this; | |
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { | |
elem = elem.firstChild; | |
} | |
return elem; | |
}).append( this ); | |
} | |
return this; | |
}, | |
wrapInner: function( html ) { | |
if ( jQuery.isFunction( html ) ) { | |
return this.each(function(i) { | |
jQuery(this).wrapInner( html.call(this, i) ); | |
}); | |
} | |
return this.each(function() { | |
var self = jQuery( this ), | |
contents = self.contents(); | |
if ( contents.length ) { | |
contents.wrapAll( html ); | |
} else { | |
self.append( html ); | |
} | |
}); | |
}, | |
wrap: function( html ) { | |
var isFunction = jQuery.isFunction( html ); | |
return this.each(function(i) { | |
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); | |
}); | |
}, | |
unwrap: function() { | |
return this.parent().each(function() { | |
if ( !jQuery.nodeName( this, "body" ) ) { | |
jQuery( this ).replaceWith( this.childNodes ); | |
} | |
}).end(); | |
}, | |
append: function() { | |
return this.domManip(arguments, true, function( elem ) { | |
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { | |
this.appendChild( elem ); | |
} | |
}); | |
}, | |
prepend: function() { | |
return this.domManip(arguments, true, function( elem ) { | |
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { | |
this.insertBefore( elem, this.firstChild ); | |
} | |
}); | |
}, | |
before: function() { | |
return this.domManip( arguments, false, function( elem ) { | |
if ( this.parentNode ) { | |
this.parentNode.insertBefore( elem, this ); | |
} | |
}); | |
}, | |
after: function() { | |
return this.domManip( arguments, false, function( elem ) { | |
if ( this.parentNode ) { | |
this.parentNode.insertBefore( elem, this.nextSibling ); | |
} | |
}); | |
}, | |
// keepData is for internal use only--do not document | |
remove: function( selector, keepData ) { | |
var elem, | |
i = 0; | |
for ( ; (elem = this[i]) != null; i++ ) { | |
if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { | |
if ( !keepData && elem.nodeType === 1 ) { | |
jQuery.cleanData( getAll( elem ) ); | |
} | |
if ( elem.parentNode ) { | |
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { | |
setGlobalEval( getAll( elem, "script" ) ); | |
} | |
elem.parentNode.removeChild( elem ); | |
} | |
} | |
} | |
return this; | |
}, | |
empty: function() { | |
var elem, | |
i = 0; | |
for ( ; (elem = this[i]) != null; i++ ) { | |
// Remove element nodes and prevent memory leaks | |
if ( elem.nodeType === 1 ) { | |
jQuery.cleanData( getAll( elem, false ) ); | |
} | |
// Remove any remaining nodes | |
while ( elem.firstChild ) { | |
elem.removeChild( elem.firstChild ); | |
} | |
// If this is a select, ensure that it displays empty (#12336) | |
// Support: IE<9 | |
if ( elem.options && jQuery.nodeName( elem, "select" ) ) { | |
elem.options.length = 0; | |
} | |
} | |
return this; | |
}, | |
clone: function( dataAndEvents, deepDataAndEvents ) { | |
dataAndEvents = dataAndEvents == null ? false : dataAndEvents; | |
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; | |
return this.map( function () { | |
return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); | |
}); | |
}, | |
html: function( value ) { | |
return jQuery.access( this, function( value ) { | |
var elem = this[0] || {}, | |
i = 0, | |
l = this.length; | |
if ( value === undefined ) { | |
return elem.nodeType === 1 ? | |
elem.innerHTML.replace( rinlinejQuery, "" ) : | |
undefined; | |
} | |
// See if we can take a shortcut and just use innerHTML | |
if ( typeof value === "string" && !rnoInnerhtml.test( value ) && | |
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && | |
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && | |
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { | |
value = value.replace( rxhtmlTag, "<$1></$2>" ); | |
try { | |
for (; i < l; i++ ) { | |
// Remove element nodes and prevent memory leaks | |
elem = this[i] || {}; | |
if ( elem.nodeType === 1 ) { | |
jQuery.cleanData( getAll( elem, false ) ); | |
elem.innerHTML = value; | |
} | |
} | |
elem = 0; | |
// If using innerHTML throws an exception, use the fallback method | |
} catch(e) {} | |
} | |
if ( elem ) { | |
this.empty().append( value ); | |
} | |
}, null, value, arguments.length ); | |
}, | |
replaceWith: function( value ) { | |
var isFunc = jQuery.isFunction( value ); | |
// Make sure that the elements are removed from the DOM before they are inserted | |
// this can help fix replacing a parent with child elements | |
if ( !isFunc && typeof value !== "string" ) { | |
value = jQuery( value ).not( this ).detach(); | |
} | |
return this.domManip( [ value ], true, function( elem ) { | |
var next = this.nextSibling, | |
parent = this.parentNode; | |
if ( parent ) { | |
jQuery( this ).remove(); | |
parent.insertBefore( elem, next ); | |
} | |
}); | |
}, | |
detach: function( selector ) { | |
return this.remove( selector, true ); | |
}, | |
domManip: function( args, table, callback ) { | |
// Flatten any nested arrays | |
args = core_concat.apply( [], args ); | |
var first, node, hasScripts, | |
scripts, doc, fragment, | |
i = 0, | |
l = this.length, | |
set = this, | |
iNoClone = l - 1, | |
value = args[0], | |
isFunction = jQuery.isFunction( value ); | |
// We can't cloneNode fragments that contain checked, in WebKit | |
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { | |
return this.each(function( index ) { | |
var self = set.eq( index ); | |
if ( isFunction ) { | |
args[0] = value.call( this, index, table ? self.html() : undefined ); | |
} | |
self.domManip( args, table, callback ); | |
}); | |
} | |
if ( l ) { | |
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); | |
first = fragment.firstChild; | |
if ( fragment.childNodes.length === 1 ) { | |
fragment = first; | |
} | |
if ( first ) { | |
table = table && jQuery.nodeName( first, "tr" ); | |
scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); | |
hasScripts = scripts.length; | |
// Use the original fragment for the last item instead of the first because it can end up | |
// being emptied incorrectly in certain situations (#8070). | |
for ( ; i < l; i++ ) { | |
node = fragment; | |
if ( i !== iNoClone ) { | |
node = jQuery.clone( node, true, true ); | |
// Keep references to cloned scripts for later restoration | |
if ( hasScripts ) { | |
jQuery.merge( scripts, getAll( node, "script" ) ); | |
} | |
} | |
callback.call( | |
table && jQuery.nodeName( this[i], "table" ) ? | |
findOrAppend( this[i], "tbody" ) : | |
this[i], | |
node, | |
i | |
); | |
} | |
if ( hasScripts ) { | |
doc = scripts[ scripts.length - 1 ].ownerDocument; | |
// Reenable scripts | |
jQuery.map( scripts, restoreScript ); | |
// Evaluate executable scripts on first document insertion | |
for ( i = 0; i < hasScripts; i++ ) { | |
node = scripts[ i ]; | |
if ( rscriptType.test( node.type || "" ) && | |
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { | |
if ( node.src ) { | |
// Hope ajax is available... | |
jQuery.ajax({ | |
url: node.src, | |
type: "GET", | |
dataType: "script", | |
async: false, | |
global: false, | |
"throws": true | |
}); | |
} else { | |
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); | |
} | |
} | |
} | |
} | |
// Fix #11809: Avoid leaking memory | |
fragment = first = null; | |
} | |
} | |
return this; | |
} | |
}); | |
function findOrAppend( elem, tag ) { | |
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); | |
} | |
// Replace/restore the type attribute of script elements for safe DOM manipulation | |
function disableScript( elem ) { | |
var attr = elem.getAttributeNode("type"); | |
elem.type = ( attr && attr.specified ) + "/" + elem.type; | |
return elem; | |
} | |
function restoreScript( elem ) { | |
var match = rscriptTypeMasked.exec( elem.type ); | |
if ( match ) { | |
elem.type = match[1]; | |
} else { | |
elem.removeAttribute("type"); | |
} | |
return elem; | |
} | |
// Mark scripts as having already been evaluated | |
function setGlobalEval( elems, refElements ) { | |
var elem, | |
i = 0; | |
for ( ; (elem = elems[i]) != null; i++ ) { | |
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); | |
} | |
} | |
function cloneCopyEvent( src, dest ) { | |
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { | |
return; | |
} | |
var type, i, l, | |
oldData = jQuery._data( src ), | |
curData = jQuery._data( dest, oldData ), | |
events = oldData.events; | |
if ( events ) { | |
delete curData.handle; | |
curData.events = {}; | |
for ( type in events ) { | |
for ( i = 0, l = events[ type ].length; i < l; i++ ) { | |
jQuery.event.add( dest, type, events[ type ][ i ] ); | |
} | |
} | |
} | |
// make the cloned public data object a copy from the original | |
if ( curData.data ) { | |
curData.data = jQuery.extend( {}, curData.data ); | |
} | |
} | |
function fixCloneNodeIssues( src, dest ) { | |
var nodeName, e, data; | |
// We do not need to do anything for non-Elements | |
if ( dest.nodeType !== 1 ) { | |
return; | |
} | |
nodeName = dest.nodeName.toLowerCase(); | |
// IE6-8 copies events bound via attachEvent when using cloneNode. | |
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { | |
data = jQuery._data( dest ); | |
for ( e in data.events ) { | |
jQuery.removeEvent( dest, e, data.handle ); | |
} | |
// Event data gets referenced instead of copied if the expando gets copied too | |
dest.removeAttribute( jQuery.expando ); | |
} | |
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text | |
if ( nodeName === "script" && dest.text !== src.text ) { | |
disableScript( dest ).text = src.text; | |
restoreScript( dest ); | |
// IE6-10 improperly clones children of object elements using classid. | |
// IE10 throws NoModificationAllowedError if parent is null, #12132. | |
} else if ( nodeName === "object" ) { | |
if ( dest.parentNode ) { | |
dest.outerHTML = src.outerHTML; | |
} | |
// This path appears unavoidable for IE9. When cloning an object | |
// element in IE9, the outerHTML strategy above is not sufficient. | |
// If the src has innerHTML and the destination does not, | |
// copy the src.innerHTML into the dest.innerHTML. #10324 | |
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { | |
dest.innerHTML = src.innerHTML; | |
} | |
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { | |
// IE6-8 fails to persist the checked state of a cloned checkbox | |
// or radio button. Worse, IE6-7 fail to give the cloned element | |
// a checked appearance if the defaultChecked value isn't also set | |
dest.defaultChecked = dest.checked = src.checked; | |
// IE6-7 get confused and end up setting the value of a cloned | |
// checkbox/radio button to an empty string instead of "on" | |
if ( dest.value !== src.value ) { | |
dest.value = src.value; | |
} | |
// IE6-8 fails to return the selected option to the default selected | |
// state when cloning options | |
} else if ( nodeName === "option" ) { | |
dest.defaultSelected = dest.selected = src.defaultSelected; | |
// IE6-8 fails to set the defaultValue to the correct value when | |
// cloning other types of input fields | |
} else if ( nodeName === "input" || nodeName === "textarea" ) { | |
dest.defaultValue = src.defaultValue; | |
} | |
} | |
jQuery.each({ | |
appendTo: "append", | |
prependTo: "prepend", | |
insertBefore: "before", | |
insertAfter: "after", | |
replaceAll: "replaceWith" | |
}, function( name, original ) { | |
jQuery.fn[ name ] = function( selector ) { | |
var elems, | |
i = 0, | |
ret = [], | |
insert = jQuery( selector ), | |
last = insert.length - 1; | |
for ( ; i <= last; i++ ) { | |
elems = i === last ? this : this.clone(true); | |
jQuery( insert[i] )[ original ]( elems ); | |
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() | |
core_push.apply( ret, elems.get() ); | |
} | |
return this.pushStack( ret ); | |
}; | |
}); | |
function getAll( context, tag ) { | |
var elems, elem, | |
i = 0, | |
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : | |
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : | |
undefined; | |
if ( !found ) { | |
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { | |
if ( !tag || jQuery.nodeName( elem, tag ) ) { | |
found.push( elem ); | |
} else { | |
jQuery.merge( found, getAll( elem, tag ) ); | |
} | |
} | |
} | |
return tag === undefined || tag && jQuery.nodeName( context, tag ) ? | |
jQuery.merge( [ context ], found ) : | |
found; | |
} | |
// Used in buildFragment, fixes the defaultChecked property | |
function fixDefaultChecked( elem ) { | |
if ( manipulation_rcheckableType.test( elem.type ) ) { | |
elem.defaultChecked = elem.checked; | |
} | |
} | |
jQuery.extend({ | |
clone: function( elem, dataAndEvents, deepDataAndEvents ) { | |
var destElements, node, clone, i, srcElements, | |
inPage = jQuery.contains( elem.ownerDocument, elem ); | |
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { | |
clone = elem.cloneNode( true ); | |
// IE<=8 does not properly clone detached, unknown element nodes | |
} else { | |
fragmentDiv.innerHTML = elem.outerHTML; | |
fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); | |
} | |
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && | |
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { | |
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 | |
destElements = getAll( clone ); | |
srcElements = getAll( elem ); | |
// Fix all IE cloning issues | |
for ( i = 0; (node = srcElements[i]) != null; ++i ) { | |
// Ensure that the destination node is not null; Fixes #9587 | |
if ( destElements[i] ) { | |
fixCloneNodeIssues( node, destElements[i] ); | |
} | |
} | |
} | |
// Copy the events from the original to the clone | |
if ( dataAndEvents ) { | |
if ( deepDataAndEvents ) { | |
srcElements = srcElements || getAll( elem ); | |
destElements = destElements || getAll( clone ); | |
for ( i = 0; (node = srcElements[i]) != null; i++ ) { | |
cloneCopyEvent( node, destElements[i] ); | |
} | |
} else { | |
cloneCopyEvent( elem, clone ); | |
} | |
} | |
// Preserve script evaluation history | |
destElements = getAll( clone, "script" ); | |
if ( destElements.length > 0 ) { | |
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); | |
} | |
destElements = srcElements = node = null; | |
// Return the cloned set | |
return clone; | |
}, | |
buildFragment: function( elems, context, scripts, selection ) { | |
var j, elem, contains, | |
tmp, tag, tbody, wrap, | |
l = elems.length, | |
// Ensure a safe fragment | |
safe = createSafeFragment( context ), | |
nodes = [], | |
i = 0; | |
for ( ; i < l; i++ ) { | |
elem = elems[ i ]; | |
if ( elem || elem === 0 ) { | |
// Add nodes directly | |
if ( jQuery.type( elem ) === "object" ) { | |
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); | |
// Convert non-html into a text node | |
} else if ( !rhtml.test( elem ) ) { | |
nodes.push( context.createTextNode( elem ) ); | |
// Convert html into DOM nodes | |
} else { | |
tmp = tmp || safe.appendChild( context.createElement("div") ); | |
// Deserialize a standard representation | |
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); | |
wrap = wrapMap[ tag ] || wrapMap._default; | |
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; | |
// Descend through wrappers to the right content | |
j = wrap[0]; | |
while ( j-- ) { | |
tmp = tmp.lastChild; | |
} | |
// Manually add leading whitespace removed by IE | |
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { | |
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); | |
} | |
// Remove IE's autoinserted <tbody> from table fragments | |
if ( !jQuery.support.tbody ) { | |
// String was a <table>, *may* have spurious <tbody> | |
elem = tag === "table" && !rtbody.test( elem ) ? | |
tmp.firstChild : | |
// String was a bare <thead> or <tfoot> | |
wrap[1] === "<table>" && !rtbody.test( elem ) ? | |
tmp : | |
0; | |
j = elem && elem.childNodes.length; | |
while ( j-- ) { | |
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { | |
elem.removeChild( tbody ); | |
} | |
} | |
} | |
jQuery.merge( nodes, tmp.childNodes ); | |
// Fix #12392 for WebKit and IE > 9 | |
tmp.textContent = ""; | |
// Fix #12392 for oldIE | |
while ( tmp.firstChild ) { | |
tmp.removeChild( tmp.firstChild ); | |
} | |
// Remember the top-level container for proper cleanup | |
tmp = safe.lastChild; | |
} | |
} | |
} | |
// Fix #11356: Clear elements from fragment | |
if ( tmp ) { | |
safe.removeChild( tmp ); | |
} | |
// Reset defaultChecked for any radios and checkboxes | |
// about to be appended to the DOM in IE 6/7 (#8060) | |
if ( !jQuery.support.appendChecked ) { | |
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); | |
} | |
i = 0; | |
while ( (elem = nodes[ i++ ]) ) { | |
// #4087 - If origin and destination elements are the same, and this is | |
// that element, do not do anything | |
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { | |
continue; | |
} | |
contains = jQuery.contains( elem.ownerDocument, elem ); | |
// Append to fragment | |
tmp = getAll( safe.appendChild( elem ), "script" ); | |
// Preserve script evaluation history | |
if ( contains ) { | |
setGlobalEval( tmp ); | |
} | |
// Capture executables | |
if ( scripts ) { | |
j = 0; | |
while ( (elem = tmp[ j++ ]) ) { | |
if ( rscriptType.test( elem.type || "" ) ) { | |
scripts.push( elem ); | |
} | |
} | |
} | |
} | |
tmp = null; | |
return safe; | |
}, | |
cleanData: function( elems, /* internal */ acceptData ) { | |
var elem, type, id, data, | |
i = 0, | |
internalKey = jQuery.expando, | |
cache = jQuery.cache, | |
deleteExpando = jQuery.support.deleteExpando, | |
special = jQuery.event.special; | |
for ( ; (elem = elems[i]) != null; i++ ) { | |
if ( acceptData || jQuery.acceptData( elem ) ) { | |
id = elem[ internalKey ]; | |
data = id && cache[ id ]; | |
if ( data ) { | |
if ( data.events ) { | |
for ( type in data.events ) { | |
if ( special[ type ] ) { | |
jQuery.event.remove( elem, type ); | |
// This is a shortcut to avoid jQuery.event.remove's overhead | |
} else { | |
jQuery.removeEvent( elem, type, data.handle ); | |
} | |
} | |
} | |
// Remove cache only if it was not already removed by jQuery.event.remove | |
if ( cache[ id ] ) { | |
delete cache[ id ]; | |
// IE does not allow us to delete expando properties from nodes, | |
// nor does it have a removeAttribute function on Document nodes; | |
// we must handle all of these cases | |
if ( deleteExpando ) { | |
delete elem[ internalKey ]; | |
} else if ( typeof elem.removeAttribute !== core_strundefined ) { | |
elem.removeAttribute( internalKey ); | |
} else { | |
elem[ internalKey ] = null; | |
} | |
core_deletedIds.push( id ); | |
} | |
} | |
} | |
} | |
} | |
}); | |
var iframe, getStyles, curCSS, | |
ralpha = /alpha\([^)]*\)/i, | |
ropacity = /opacity\s*=\s*([^)]*)/, | |
rposition = /^(top|right|bottom|left)$/, | |
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption" | |
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display | |
rdisplayswap = /^(none|table(?!-c[ea]).+)/, | |
rmargin = /^margin/, | |
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), | |
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), | |
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), | |
elemdisplay = { BODY: "block" }, | |
cssShow = { position: "absolute", visibility: "hidden", display: "block" }, | |
cssNormalTransform = { | |
letterSpacing: 0, | |
fontWeight: 400 | |
}, | |
cssExpand = [ "Top", "Right", "Bottom", "Left" ], | |
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; | |
// return a css property mapped to a potentially vendor prefixed property | |
function vendorPropName( style, name ) { | |
// shortcut for names that are not vendor prefixed | |
if ( name in style ) { | |
return name; | |
} | |
// check for vendor prefixed names | |
var capName = name.charAt(0).toUpperCase() + name.slice(1), | |
origName = name, | |
i = cssPrefixes.length; | |
while ( i-- ) { | |
name = cssPrefixes[ i ] + capName; | |
if ( name in style ) { | |
return name; | |
} | |
} | |
return origName; | |
} | |
function isHidden( elem, el ) { | |
// isHidden might be called from jQuery#filter function; | |
// in that case, element will be second argument | |
elem = el || elem; | |
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); | |
} | |
function showHide( elements, show ) { | |
var display, elem, hidden, | |
values = [], | |
index = 0, | |
length = elements.length; | |
for ( ; index < length; index++ ) { | |
elem = elements[ index ]; | |
if ( !elem.style ) { | |
continue; | |
} | |
values[ index ] = jQuery._data( elem, "olddisplay" ); | |
display = elem.style.display; | |
if ( show ) { | |
// Reset the inline display of this element to learn if it is | |
// being hidden by cascaded rules or not | |
if ( !values[ index ] && display === "none" ) { | |
elem.style.display = ""; | |
} | |
// Set elements which have been overridden with display: none | |
// in a stylesheet to whatever the default browser style is | |
// for such an element | |
if ( elem.style.display === "" && isHidden( elem ) ) { | |
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); | |
} | |
} else { | |
if ( !values[ index ] ) { | |
hidden = isHidden( elem ); | |
if ( display && display !== "none" || !hidden ) { | |
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); | |
} | |
} | |
} | |
} | |
// Set the display of most of the elements in a second loop | |
// to avoid the constant reflow | |
for ( index = 0; index < length; index++ ) { | |
elem = elements[ index ]; | |
if ( !elem.style ) { | |
continue; | |
} | |
if ( !show || elem.style.display === "none" || elem.style.display === "" ) { | |
elem.style.display = show ? values[ index ] || "" : "none"; | |
} | |
} | |
return elements; | |
} | |
jQuery.fn.extend({ | |
css: function( name, value ) { | |
return jQuery.access( this, function( elem, name, value ) { | |
var len, styles, | |
map = {}, | |
i = 0; | |
if ( jQuery.isArray( name ) ) { | |
styles = getStyles( elem ); | |
len = name.length; | |
for ( ; i < len; i++ ) { | |
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); | |
} | |
return map; | |
} | |
return value !== undefined ? | |
jQuery.style( elem, name, value ) : | |
jQuery.css( elem, name ); | |
}, name, value, arguments.length > 1 ); | |
}, | |
show: function() { | |
return showHide( this, true ); | |
}, | |
hide: function() { | |
return showHide( this ); | |
}, | |
toggle: function( state ) { | |
var bool = typeof state === "boolean"; | |
return this.each(function() { | |
if ( bool ? state : isHidden( this ) ) { | |
jQuery( this ).show(); | |
} else { | |
jQuery( this ).hide(); | |
} | |
}); | |
} | |
}); | |
jQuery.extend({ | |
// Add in style property hooks for overriding the default | |
// behavior of getting and setting a style property | |
cssHooks: { | |
opacity: { | |
get: function( elem, computed ) { | |
if ( computed ) { | |
// We should always get a number back from opacity | |
var ret = curCSS( elem, "opacity" ); | |
return ret === "" ? "1" : ret; | |
} | |
} | |
} | |
}, | |
// Exclude the following css properties to add px | |
cssNumber: { | |
"columnCount": true, | |
"fillOpacity": true, | |
"fontWeight": true, | |
"lineHeight": true, | |
"opacity": true, | |
"orphans": true, | |
"widows": true, | |
"zIndex": true, | |
"zoom": true | |
}, | |
// Add in properties whose names you wish to fix before | |
// setting or getting the value | |
cssProps: { | |
// normalize float css property | |
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" | |
}, | |
// Get and set the style property on a DOM Node | |
style: function( elem, name, value, extra ) { | |
// Don't set styles on text and comment nodes | |
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { | |
return; | |
} | |
// Make sure that we're working with the right name | |
var ret, type, hooks, | |
origName = jQuery.camelCase( name ), | |
style = elem.style; | |
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); | |
// gets hook for the prefixed version | |
// followed by the unprefixed version | |
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; | |
// Check if we're setting a value | |
if ( value !== undefined ) { | |
type = typeof value; | |
// convert relative number strings (+= or -=) to relative numbers. #7345 | |
if ( type === "string" && (ret = rrelNum.exec( value )) ) { | |
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); | |
// Fixes bug #9237 | |
type = "number"; | |
} | |
// Make sure that NaN and null values aren't set. See: #7116 | |
if ( value == null || type === "number" && isNaN( value ) ) { | |
return; | |
} | |
// If a number was passed in, add 'px' to the (except for certain CSS properties) | |
if ( type === "number" && !jQuery.cssNumber[ origName ] ) { | |
value += "px"; | |
} | |
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks, | |
// but it would mean to define eight (for every problematic property) identical functions | |
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { | |
style[ name ] = "inherit"; | |
} | |
// If a hook was provided, use that value, otherwise just set the specified value | |
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { | |
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided | |
// Fixes bug #5509 | |
try { | |
style[ name ] = value; | |
} catch(e) {} | |
} | |
} else { | |
// If a hook was provided get the non-computed value from there | |
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { | |
return ret; | |
} | |
// Otherwise just get the value from the style object | |
return style[ name ]; | |
} | |
}, | |
css: function( elem, name, extra, styles ) { | |
var num, val, hooks, | |
origName = jQuery.camelCase( name ); | |
// Make sure that we're working with the right name | |
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); | |
// gets hook for the prefixed version | |
// followed by the unprefixed version | |
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; | |
// If a hook was provided get the computed value from there | |
if ( hooks && "get" in hooks ) { | |
val = hooks.get( elem, true, extra ); | |
} | |
// Otherwise, if a way to get the computed value exists, use that | |
if ( val === undefined ) { | |
val = curCSS( elem, name, styles ); | |
} | |
//convert "normal" to computed value | |
if ( val === "normal" && name in cssNormalTransform ) { | |
val = cssNormalTransform[ name ]; | |
} | |
// Return, converting to number if forced or a qualifier was provided and val looks numeric | |
if ( extra === "" || extra ) { | |
num = parseFloat( val ); | |
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; | |
} | |
return val; | |
}, | |
// A method for quickly swapping in/out CSS properties to get correct calculations | |
swap: function( elem, options, callback, args ) { | |
var ret, name, | |
old = {}; | |
// Remember the old values, and insert the new ones | |
for ( name in options ) { | |
old[ name ] = elem.style[ name ]; | |
elem.style[ name ] = options[ name ]; | |
} | |
ret = callback.apply( elem, args || [] ); | |
// Revert the old values | |
for ( name in options ) { | |
elem.style[ name ] = old[ name ]; | |
} | |
return ret; | |
} | |
}); | |
// NOTE: we've included the "window" in window.getComputedStyle | |
// because jsdom on node.js will break without it. | |
if ( window.getComputedStyle ) { | |
getStyles = function( elem ) { | |
return window.getComputedStyle( elem, null ); | |
}; | |
curCSS = function( elem, name, _computed ) { | |
var width, minWidth, maxWidth, | |
computed = _computed || getStyles( elem ), | |
// getPropertyValue is only needed for .css('filter') in IE9, see #12537 | |
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, | |
style = elem.style; | |
if ( computed ) { | |
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { | |
ret = jQuery.style( elem, name ); | |
} | |
// A tribute to the "awesome hack by Dean Edwards" | |
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right | |
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels | |
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values | |
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { | |
// Remember the original values | |
width = style.width; | |
minWidth = style.minWidth; | |
maxWidth = style.maxWidth; | |
// Put in the new values to get a computed value out | |
style.minWidth = style.maxWidth = style.width = ret; | |
ret = computed.width; | |
// Revert the changed values | |
style.width = width; | |
style.minWidth = minWidth; | |
style.maxWidth = maxWidth; | |
} | |
} | |
return ret; | |
}; | |
} else if ( document.documentElement.currentStyle ) { | |
getStyles = function( elem ) { | |
return elem.currentStyle; | |
}; | |
curCSS = function( elem, name, _computed ) { | |
var left, rs, rsLeft, | |
computed = _computed || getStyles( elem ), | |
ret = computed ? computed[ name ] : undefined, | |
style = elem.style; | |
// Avoid setting ret to empty string here | |
// so we don't default to auto | |
if ( ret == null && style && style[ name ] ) { | |
ret = style[ name ]; | |
} | |
// From the awesome hack by Dean Edwards | |
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 | |
// If we're not dealing with a regular pixel number | |
// but a number that has a weird ending, we need to convert it to pixels | |
// but not position css attributes, as those are proportional to the parent element instead | |
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem | |
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { | |
// Remember the original values | |
left = style.left; | |
rs = elem.runtimeStyle; | |
rsLeft = rs && rs.left; | |
// Put in the new values to get a computed value out | |
if ( rsLeft ) { | |
rs.left = elem.currentStyle.left; | |
} | |
style.left = name === "fontSize" ? "1em" : ret; | |
ret = style.pixelLeft + "px"; | |
// Revert the changed values | |
style.left = left; | |
if ( rsLeft ) { | |
rs.left = rsLeft; | |
} | |
} | |
return ret === "" ? "auto" : ret; | |
}; | |
} | |
function setPositiveNumber( elem, value, subtract ) { | |
var matches = rnumsplit.exec( value ); | |
return matches ? | |
// Guard against undefined "subtract", e.g., when used as in cssHooks | |
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : | |
value; | |
} | |
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { | |
var i = extra === ( isBorderBox ? "border" : "content" ) ? | |
// If we already have the right measurement, avoid augmentation | |
4 : | |
// Otherwise initialize for horizontal or vertical properties | |
name === "width" ? 1 : 0, | |
val = 0; | |
for ( ; i < 4; i += 2 ) { | |
// both box models exclude margin, so add it if we want it | |
if ( extra === "margin" ) { | |
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); | |
} | |
if ( isBorderBox ) { | |
// border-box includes padding, so remove it if we want content | |
if ( extra === "content" ) { | |
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); | |
} | |
// at this point, extra isn't border nor margin, so remove border | |
if ( extra !== "margin" ) { | |
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); | |
} | |
} else { | |
// at this point, extra isn't content, so add padding | |
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); | |
// at this point, extra isn't content nor padding, so add border | |
if ( extra !== "padding" ) { | |
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); | |
} | |
} | |
} | |
return val; | |
} | |
function getWidthOrHeight( elem, name, extra ) { | |
// Start with offset property, which is equivalent to the border-box value | |
var valueIsBorderBox = true, | |
val = name === "width" ? elem.offsetWidth : elem.offsetHeight, | |
styles = getStyles( elem ), | |
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; | |
// some non-html elements return undefined for offsetWidth, so check for null/undefined | |
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 | |
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 | |
if ( val <= 0 || val == null ) { | |
// Fall back to computed then uncomputed css if necessary | |
val = curCSS( elem, name, styles ); | |
if ( val < 0 || val == null ) { | |
val = elem.style[ name ]; | |
} | |
// Computed unit is not pixels. Stop here and return. | |
if ( rnumnonpx.test(val) ) { | |
return val; | |
} | |
// we need the check for style in case a browser which returns unreliable values | |
// for getComputedStyle silently falls back to the reliable elem.style | |
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); | |
// Normalize "", auto, and prepare for extra | |
val = parseFloat( val ) || 0; | |
} | |
// use the active box-sizing model to add/subtract irrelevant styles | |
return ( val + | |
augmentWidthOrHeight( | |
elem, | |
name, | |
extra || ( isBorderBox ? "border" : "content" ), | |
valueIsBorderBox, | |
styles | |
) | |
) + "px"; | |
} | |
// Try to determine the default display value of an element | |
function css_defaultDisplay( nodeName ) { | |
var doc = document, | |
display = elemdisplay[ nodeName ]; | |
if ( !display ) { | |
display = actualDisplay( nodeName, doc ); | |
// If the simple way fails, read from inside an iframe | |
if ( display === "none" || !display ) { | |
// Use the already-created iframe if possible | |
iframe = ( iframe || | |
jQuery("<iframe frameborder='0' width='0' height='0'/>") | |
.css( "cssText", "display:block !important" ) | |
).appendTo( doc.documentElement ); | |
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse | |
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; | |
doc.write("<!doctype html><html><body>"); | |
doc.close(); | |
display = actualDisplay( nodeName, doc ); | |
iframe.detach(); | |
} | |
// Store the correct default display | |
elemdisplay[ nodeName ] = display; | |
} | |
return display; | |
} | |
// Called ONLY from within css_defaultDisplay | |
function actualDisplay( name, doc ) { | |
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), | |
display = jQuery.css( elem[0], "display" ); | |
elem.remove(); | |
return display; | |
} | |
jQuery.each([ "height", "width" ], function( i, name ) { | |
jQuery.cssHooks[ name ] = { | |
get: function( elem, computed, extra ) { | |
if ( computed ) { | |
// certain elements can have dimension info if we invisibly show them | |
// however, it must have a current display style that would benefit from this | |
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? | |
jQuery.swap( elem, cssShow, function() { | |
return getWidthOrHeight( elem, name, extra ); | |
}) : | |
getWidthOrHeight( elem, name, extra ); | |
} | |
}, | |
set: function( elem, value, extra ) { | |
var styles = extra && getStyles( elem ); | |
return setPositiveNumber( elem, value, extra ? | |
augmentWidthOrHeight( | |
elem, | |
name, | |
extra, | |
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", | |
styles | |
) : 0 | |
); | |
} | |
}; | |
}); | |
if ( !jQuery.support.opacity ) { | |
jQuery.cssHooks.opacity = { | |
get: function( elem, computed ) { | |
// IE uses filters for opacity | |
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? | |
( 0.01 * parseFloat( RegExp.$1 ) ) + "" : | |
computed ? "1" : ""; | |
}, | |
set: function( elem, value ) { | |
var style = elem.style, | |
currentStyle = elem.currentStyle, | |
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", | |
filter = currentStyle && currentStyle.filter || style.filter || ""; | |
// IE has trouble with opacity if it does not have layout | |
// Force it by setting the zoom level | |
style.zoom = 1; | |
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 | |
// if value === "", then remove inline opacity #12685 | |
if ( ( value >= 1 || value === "" ) && | |
jQuery.trim( filter.replace( ralpha, "" ) ) === "" && | |
style.removeAttribute ) { | |
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText | |
// if "filter:" is present at all, clearType is disabled, we want to avoid this | |
// style.removeAttribute is IE Only, but so apparently is this code path... | |
style.removeAttribute( "filter" ); | |
// if there is no filter style applied in a css rule or unset inline opacity, we are done | |
if ( value === "" || currentStyle && !currentStyle.filter ) { | |
return; | |
} | |
} | |
// otherwise, set new filter values | |
style.filter = ralpha.test( filter ) ? | |
filter.replace( ralpha, opacity ) : | |
filter + " " + opacity; | |
} | |
}; | |
} | |
// These hooks cannot be added until DOM ready because the support test | |
// for it is not run until after DOM ready | |
jQuery(function() { | |
if ( !jQuery.support.reliableMarginRight ) { | |
jQuery.cssHooks.marginRight = { | |
get: function( elem, computed ) { | |
if ( computed ) { | |
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right | |
// Work around by temporarily setting element display to inline-block | |
return jQuery.swap( elem, { "display": "inline-block" }, | |
curCSS, [ elem, "marginRight" ] ); | |
} | |
} | |
}; | |
} | |
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 | |
// getComputedStyle returns percent when specified for top/left/bottom/right | |
// rather than make the css module depend on the offset module, we just check for it here | |
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { | |
jQuery.each( [ "top", "left" ], function( i, prop ) { | |
jQuery.cssHooks[ prop ] = { | |
get: function( elem, computed ) { | |
if ( computed ) { | |
computed = curCSS( elem, prop ); | |
// if curCSS returns percentage, fallback to offset | |
return rnumnonpx.test( computed ) ? | |
jQuery( elem ).position()[ prop ] + "px" : | |
computed; | |
} | |
} | |
}; | |
}); | |
} | |
}); | |
if ( jQuery.expr && jQuery.expr.filters ) { | |
jQuery.expr.filters.hidden = function( elem ) { | |
// Support: Opera <= 12.12 | |
// Opera reports offsetWidths and offsetHeights less than zero on some elements | |
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || | |
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); | |
}; | |
jQuery.expr.filters.visible = function( elem ) { | |
return !jQuery.expr.filters.hidden( elem ); | |
}; | |
} | |
// These hooks are used by animate to expand properties | |
jQuery.each({ | |
margin: "", | |
padding: "", | |
border: "Width" | |
}, function( prefix, suffix ) { | |
jQuery.cssHooks[ prefix + suffix ] = { | |
expand: function( value ) { | |
var i = 0, | |
expanded = {}, | |
// assumes a single number if not a string | |
parts = typeof value === "string" ? value.split(" ") : [ value ]; | |
for ( ; i < 4; i++ ) { | |
expanded[ prefix + cssExpand[ i ] + suffix ] = | |
parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; | |
} | |
return expanded; | |
} | |
}; | |
if ( !rmargin.test( prefix ) ) { | |
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; | |
} | |
}); | |
var r20 = /%20/g, | |
rbracket = /\[\]$/, | |
rCRLF = /\r?\n/g, | |
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, | |
rsubmittable = /^(?:input|select|textarea|keygen)/i; | |
jQuery.fn.extend({ | |
serialize: function() { | |
return jQuery.param( this.serializeArray() ); | |
}, | |
serializeArray: function() { | |
return this.map(function(){ | |
// Can add propHook for "elements" to filter or add form elements | |
var elements = jQuery.prop( this, "elements" ); | |
return elements ? jQuery.makeArray( elements ) : this; | |
}) | |
.filter(function(){ | |
var type = this.type; | |
// Use .is(":disabled") so that fieldset[disabled] works | |
return this.name && !jQuery( this ).is( ":disabled" ) && | |
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && | |
( this.checked || !manipulation_rcheckableType.test( type ) ); | |
}) | |
.map(function( i, elem ){ | |
var val = jQuery( this ).val(); | |
return val == null ? | |
null : | |
jQuery.isArray( val ) ? | |
jQuery.map( val, function( val ){ | |
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; | |
}) : | |
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; | |
}).get(); | |
} | |
}); | |
//Serialize an array of form elements or a set of | |
//key/values into a query string | |
jQuery.param = function( a, traditional ) { | |
var prefix, | |
s = [], | |
add = function( key, value ) { | |
// If value is a function, invoke it and return its value | |
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); | |
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); | |
}; | |
// Set traditional to true for jQuery <= 1.3.2 behavior. | |
if ( traditional === undefined ) { | |
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; | |
} | |
// If an array was passed in, assume that it is an array of form elements. | |
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { | |
// Serialize the form elements | |
jQuery.each( a, function() { | |
add( this.name, this.value ); | |
}); | |
} else { | |
// If traditional, encode the "old" way (the way 1.3.2 or older | |
// did it), otherwise encode params recursively. | |
for ( prefix in a ) { | |
buildParams( prefix, a[ prefix ], traditional, add ); | |
} | |
} | |
// Return the resulting serialization | |
return s.join( "&" ).replace( r20, "+" ); | |
}; | |
function buildParams( prefix, obj, traditional, add ) { | |
var name; | |
if ( jQuery.isArray( obj ) ) { | |
// Serialize array item. | |
jQuery.each( obj, function( i, v ) { | |
if ( traditional || rbracket.test( prefix ) ) { | |
// Treat each array item as a scalar. | |
add( prefix, v ); | |
} else { | |
// Item is non-scalar (array or object), encode its numeric index. | |
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); | |
} | |
}); | |
} else if ( !traditional && jQuery.type( obj ) === "object" ) { | |
// Serialize object item. | |
for ( name in obj ) { | |
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); | |
} | |
} else { | |
// Serialize scalar item. | |
add( prefix, obj ); | |
} | |
} | |
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + | |
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + | |
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { | |
// Handle event binding | |
jQuery.fn[ name ] = function( data, fn ) { | |
return arguments.length > 0 ? | |
this.on( name, null, data, fn ) : | |
this.trigger( name ); | |
}; | |
}); | |
jQuery.fn.hover = function( fnOver, fnOut ) { | |
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); | |
}; | |
var | |
// Document location | |
ajaxLocParts, | |
ajaxLocation, | |
ajax_nonce = jQuery.now(), | |
ajax_rquery = /\?/, | |
rhash = /#.*$/, | |
rts = /([?&])_=[^&]*/, | |
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL | |
// #7653, #8125, #8152: local protocol detection | |
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, | |
rnoContent = /^(?:GET|HEAD)$/, | |
rprotocol = /^\/\//, | |
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, | |
// Keep a copy of the old load method | |
_load = jQuery.fn.load, | |
/* Prefilters | |
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) | |
* 2) These are called: | |
* - BEFORE asking for a transport | |
* - AFTER param serialization (s.data is a string if s.processData is true) | |
* 3) key is the dataType | |
* 4) the catchall symbol "*" can be used | |
* 5) execution will start with transport dataType and THEN continue down to "*" if needed | |
*/ | |
prefilters = {}, | |
/* Transports bindings | |
* 1) key is the dataType | |
* 2) the catchall symbol "*" can be used | |
* 3) selection will start with transport dataType and THEN go to "*" if needed | |
*/ | |
transports = {}, | |
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression | |
allTypes = "*/".concat("*"); | |
// #8138, IE may throw an exception when accessing | |
// a field from window.location if document.domain has been set | |
try { | |
ajaxLocation = location.href; | |
} catch( e ) { | |
// Use the href attribute of an A element | |
// since IE will modify it given document.location | |
ajaxLocation = document.createElement( "a" ); | |
ajaxLocation.href = ""; | |
ajaxLocation = ajaxLocation.href; | |
} | |
// Segment location into parts | |
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; | |
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport | |
function addToPrefiltersOrTransports( structure ) { | |
// dataTypeExpression is optional and defaults to "*" | |
return function( dataTypeExpression, func ) { | |
if ( typeof dataTypeExpression !== "string" ) { | |
func = dataTypeExpression; | |
dataTypeExpression = "*"; | |
} | |
var dataType, | |
i = 0, | |
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; | |
if ( jQuery.isFunction( func ) ) { | |
// For each dataType in the dataTypeExpression | |
while ( (dataType = dataTypes[i++]) ) { | |
// Prepend if requested | |
if ( dataType[0] === "+" ) { | |
dataType = dataType.slice( 1 ) || "*"; | |
(structure[ dataType ] = structure[ dataType ] || []).unshift( func ); | |
// Otherwise append | |
} else { | |
(structure[ dataType ] = structure[ dataType ] || []).push( func ); | |
} | |
} | |
} | |
}; | |
} | |
// Base inspection function for prefilters and transports | |
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { | |
var inspected = {}, | |
seekingTransport = ( structure === transports ); | |
function inspect( dataType ) { | |
var selected; | |
inspected[ dataType ] = true; | |
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { | |
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); | |
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { | |
options.dataTypes.unshift( dataTypeOrTransport ); | |
inspect( dataTypeOrTransport ); | |
return false; | |
} else if ( seekingTransport ) { | |
return !( selected = dataTypeOrTransport ); | |
} | |
}); | |
return selected; | |
} | |
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); | |
} | |
// A special extend for ajax options | |
// that takes "flat" options (not to be deep extended) | |
// Fixes #9887 | |
function ajaxExtend( target, src ) { | |
var deep, key, | |
flatOptions = jQuery.ajaxSettings.flatOptions || {}; | |
for ( key in src ) { | |
if ( src[ key ] !== undefined ) { | |
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; | |
} | |
} | |
if ( deep ) { | |
jQuery.extend( true, target, deep ); | |
} | |
return target; | |
} | |
jQuery.fn.load = function( url, params, callback ) { | |
if ( typeof url !== "string" && _load ) { | |
return _load.apply( this, arguments ); | |
} | |
var selector, response, type, | |
self = this, | |
off = url.indexOf(" "); | |
if ( off >= 0 ) { | |
selector = url.slice( off, url.length ); | |
url = url.slice( 0, off ); | |
} | |
// If it's a function | |
if ( jQuery.isFunction( params ) ) { | |
// We assume that it's the callback | |
callback = params; | |
params = undefined; | |
// Otherwise, build a param string | |
} else if ( params && typeof params === "object" ) { | |
type = "POST"; | |
} | |
// If we have elements to modify, make the request | |
if ( self.length > 0 ) { | |
jQuery.ajax({ | |
url: url, | |
// if "type" variable is undefined, then "GET" method will be used | |
type: type, | |
dataType: "html", | |
data: params | |
}).done(function( responseText ) { | |
// Save response for use in complete callback | |
response = arguments; | |
self.html( selector ? | |
// If a selector was specified, locate the right elements in a dummy div | |
// Exclude scripts to avoid IE 'Permission Denied' errors | |
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : | |
// Otherwise use the full result | |
responseText ); | |
}).complete( callback && function( jqXHR, status ) { | |
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); | |
}); | |
} | |
return this; | |
}; | |
// Attach a bunch of functions for handling common AJAX events | |
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ | |
jQuery.fn[ type ] = function( fn ){ | |
return this.on( type, fn ); | |
}; | |
}); | |
jQuery.each( [ "get", "post" ], function( i, method ) { | |
jQuery[ method ] = function( url, data, callback, type ) { | |
// shift arguments if data argument was omitted | |
if ( jQuery.isFunction( data ) ) { | |
type = type || callback; | |
callback = data; | |
data = undefined; | |
} | |
return jQuery.ajax({ | |
url: url, | |
type: method, | |
dataType: type, | |
data: data, | |
success: callback | |
}); | |
}; | |
}); | |
jQuery.extend({ | |
// Counter for holding the number of active queries | |
active: 0, | |
// Last-Modified header cache for next request | |
lastModified: {}, | |
etag: {}, | |
ajaxSettings: { | |
url: ajaxLocation, | |
type: "GET", | |
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), | |
global: true, | |
processData: true, | |
async: true, | |
contentType: "application/x-www-form-urlencoded; charset=UTF-8", | |
/* | |
timeout: 0, | |
data: null, | |
dataType: null, | |
username: null, | |
password: null, | |
cache: null, | |
throws: false, | |
traditional: false, | |
headers: {}, | |
*/ | |
accepts: { | |
"*": allTypes, | |
text: "text/plain", | |
html: "text/html", | |
xml: "application/xml, text/xml", | |
json: "application/json, text/javascript" | |
}, | |
contents: { | |
xml: /xml/, | |
html: /html/, | |
json: /json/ | |
}, | |
responseFields: { | |
xml: "responseXML", | |
text: "responseText" | |
}, | |
// Data converters | |
// Keys separate source (or catchall "*") and destination types with a single space | |
converters: { | |
// Convert anything to text | |
"* text": window.String, | |
// Text to html (true = no transformation) | |
"text html": true, | |
// Evaluate text as a json expression | |
"text json": jQuery.parseJSON, | |
// Parse text as xml | |
"text xml": jQuery.parseXML | |
}, | |
// For options that shouldn't be deep extended: | |
// you can add your own custom options here if | |
// and when you create one that shouldn't be | |
// deep extended (see ajaxExtend) | |
flatOptions: { | |
url: true, | |
context: true | |
} | |
}, | |
// Creates a full fledged settings object into target | |
// with both ajaxSettings and settings fields. | |
// If target is omitted, writes into ajaxSettings. | |
ajaxSetup: function( target, settings ) { | |
return settings ? | |
// Building a settings object | |
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : | |
// Extending ajaxSettings | |
ajaxExtend( jQuery.ajaxSettings, target ); | |
}, | |
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), | |
ajaxTransport: addToPrefiltersOrTransports( transports ), | |
// Main method | |
ajax: function( url, options ) { | |
// If url is an object, simulate pre-1.5 signature | |
if ( typeof url === "object" ) { | |
options = url; | |
url = undefined; | |
} | |
// Force options to be an object | |
options = options || {}; | |
var // Cross-domain detection vars | |
parts, | |
// Loop variable | |
i, | |
// URL without anti-cache param | |
cacheURL, | |
// Response headers as string | |
responseHeadersString, | |
// timeout handle | |
timeoutTimer, | |
// To know if global events are to be dispatched | |
fireGlobals, | |
transport, | |
// Response headers | |
responseHeaders, | |
// Create the final options object | |
s = jQuery.ajaxSetup( {}, options ), | |
// Callbacks context | |
callbackContext = s.context || s, | |
// Context for global events is callbackContext if it is a DOM node or jQuery collection | |
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? | |
jQuery( callbackContext ) : | |
jQuery.event, | |
// Deferreds | |
deferred = jQuery.Deferred(), | |
completeDeferred = jQuery.Callbacks("once memory"), | |
// Status-dependent callbacks | |
statusCode = s.statusCode || {}, | |
// Headers (they are sent all at once) | |
requestHeaders = {}, | |
requestHeadersNames = {}, | |
// The jqXHR state | |
state = 0, | |
// Default abort message | |
strAbort = "canceled", | |
// Fake xhr | |
jqXHR = { | |
readyState: 0, | |
// Builds headers hashtable if needed | |
getResponseHeader: function( key ) { | |
var match; | |
if ( state === 2 ) { | |
if ( !responseHeaders ) { | |
responseHeaders = {}; | |
while ( (match = rheaders.exec( responseHeadersString )) ) { | |
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; | |
} | |
} | |
match = responseHeaders[ key.toLowerCase() ]; | |
} | |
return match == null ? null : match; | |
}, | |
// Raw string | |
getAllResponseHeaders: function() { | |
return state === 2 ? responseHeadersString : null; | |
}, | |
// Caches the header | |
setRequestHeader: function( name, value ) { | |
var lname = name.toLowerCase(); | |
if ( !state ) { | |
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; | |
requestHeaders[ name ] = value; | |
} | |
return this; | |
}, | |
// Overrides response content-type header | |
overrideMimeType: function( type ) { | |
if ( !state ) { | |
s.mimeType = type; | |
} | |
return this; | |
}, | |
// Status-dependent callbacks | |
statusCode: function( map ) { | |
var code; | |
if ( map ) { | |
if ( state < 2 ) { | |
for ( code in map ) { | |
// Lazy-add the new callback in a way that preserves old ones | |
statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; | |
} | |
} else { | |
// Execute the appropriate callbacks | |
jqXHR.always( map[ jqXHR.status ] ); | |
} | |
} | |
return this; | |
}, | |
// Cancel the request | |
abort: function( statusText ) { | |
var finalText = statusText || strAbort; | |
if ( transport ) { | |
transport.abort( finalText ); | |
} | |
done( 0, finalText ); | |
return this; | |
} | |
}; | |
// Attach deferreds | |
deferred.promise( jqXHR ).complete = completeDeferred.add; | |
jqXHR.success = jqXHR.done; | |
jqXHR.error = jqXHR.fail; | |
// Remove hash character (#7531: and string promotion) | |
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls) | |
// Handle falsy url in the settings object (#10093: consistency with old signature) | |
// We also use the url parameter if available | |
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); | |
// Alias method option to type as per ticket #12004 | |
s.type = options.method || options.type || s.method || s.type; | |
// Extract dataTypes list | |
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; | |
// A cross-domain request is in order when we have a protocol:host:port mismatch | |
if ( s.crossDomain == null ) { | |
parts = rurl.exec( s.url.toLowerCase() ); | |
s.crossDomain = !!( parts && | |
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || | |
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != | |
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) | |
); | |
} | |
// Convert data if not already a string | |
if ( s.data && s.processData && typeof s.data !== "string" ) { | |
s.data = jQuery.param( s.data, s.traditional ); | |
} | |
// Apply prefilters | |
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); | |
// If request was aborted inside a prefilter, stop there | |
if ( state === 2 ) { | |
return jqXHR; | |
} | |
// We can fire global events as of now if asked to | |
fireGlobals = s.global; | |
// Watch for a new set of requests | |
if ( fireGlobals && jQuery.active++ === 0 ) { | |
jQuery.event.trigger("ajaxStart"); | |
} | |
// Uppercase the type | |
s.type = s.type.toUpperCase(); | |
// Determine if request has content | |
s.hasContent = !rnoContent.test( s.type ); | |
// Save the URL in case we're toying with the If-Modified-Since | |
// and/or If-None-Match header later on | |
cacheURL = s.url; | |
// More options handling for requests with no content | |
if ( !s.hasContent ) { | |
// If data is available, append data to url | |
if ( s.data ) { | |
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); | |
// #9682: remove data so that it's not used in an eventual retry | |
delete s.data; | |
} | |
// Add anti-cache in url if needed | |
if ( s.cache === false ) { | |
s.url = rts.test( cacheURL ) ? | |
// If there is already a '_' parameter, set its value | |
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : | |
// Otherwise add one to the end | |
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; | |
} | |
} | |
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. | |
if ( s.ifModified ) { | |
if ( jQuery.lastModified[ cacheURL ] ) { | |
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); | |
} | |
if ( jQuery.etag[ cacheURL ] ) { | |
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); | |
} | |
} | |
// Set the correct header, if data is being sent | |
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { | |
jqXHR.setRequestHeader( "Content-Type", s.contentType ); | |
} | |
// Set the Accepts header for the server, depending on the dataType | |
jqXHR.setRequestHeader( | |
"Accept", | |
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? | |
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : | |
s.accepts[ "*" ] | |
); | |
// Check for headers option | |
for ( i in s.headers ) { | |
jqXHR.setRequestHeader( i, s.headers[ i ] ); | |
} | |
// Allow custom headers/mimetypes and early abort | |
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { | |
// Abort if not done already and return | |
return jqXHR.abort(); | |
} | |
// aborting is no longer a cancellation | |
strAbort = "abort"; | |
// Install callbacks on deferreds | |
for ( i in { success: 1, error: 1, complete: 1 } ) { | |
jqXHR[ i ]( s[ i ] ); | |
} | |
// Get transport | |
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); | |
// If no transport, we auto-abort | |
if ( !transport ) { | |
done( -1, "No Transport" ); | |
} else { | |
jqXHR.readyState = 1; | |
// Send global event | |
if ( fireGlobals ) { | |
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); | |
} | |
// Timeout | |
if ( s.async && s.timeout > 0 ) { | |
timeoutTimer = setTimeout(function() { | |
jqXHR.abort("timeout"); | |
}, s.timeout ); | |
} | |
try { | |
state = 1; | |
transport.send( requestHeaders, done ); | |
} catch ( e ) { | |
// Propagate exception as error if not done | |
if ( state < 2 ) { | |
done( -1, e ); | |
// Simply rethrow otherwise | |
} else { | |
throw e; | |
} | |
} | |
} | |
// Callback for when everything is done | |
function done( status, nativeStatusText, responses, headers ) { | |
var isSuccess, success, error, response, modified, | |
statusText = nativeStatusText; | |
// Called once | |
if ( state === 2 ) { | |
return; | |
} | |
// State is "done" now | |
state = 2; | |
// Clear timeout if it exists | |
if ( timeoutTimer ) { | |
clearTimeout( timeoutTimer ); | |
} | |
// Dereference transport for early garbage collection | |
// (no matter how long the jqXHR object will be used) | |
transport = undefined; | |
// Cache response headers | |
responseHeadersString = headers || ""; | |
// Set readyState | |
jqXHR.readyState = status > 0 ? 4 : 0; | |
// Get response data | |
if ( responses ) { | |
response = ajaxHandleResponses( s, jqXHR, responses ); | |
} | |
// If successful, handle type chaining | |
if ( status >= 200 && status < 300 || status === 304 ) { | |
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. | |
if ( s.ifModified ) { | |
modified = jqXHR.getResponseHeader("Last-Modified"); | |
if ( modified ) { | |
jQuery.lastModified[ cacheURL ] = modified; | |
} | |
modified = jqXHR.getResponseHeader("etag"); | |
if ( modified ) { | |
jQuery.etag[ cacheURL ] = modified; | |
} | |
} | |
// if no content | |
if ( status === 204 ) { | |
isSuccess = true; | |
statusText = "nocontent"; | |
// if not modified | |
} else if ( status === 304 ) { | |
isSuccess = true; | |
statusText = "notmodified"; | |
// If we have data, let's convert it | |
} else { | |
isSuccess = ajaxConvert( s, response ); | |
statusText = isSuccess.state; | |
success = isSuccess.data; | |
error = isSuccess.error; | |
isSuccess = !error; | |
} | |
} else { | |
// We extract error from statusText | |
// then normalize statusText and status for non-aborts | |
error = statusText; | |
if ( status || !statusText ) { | |
statusText = "error"; | |
if ( status < 0 ) { | |
status = 0; | |
} | |
} | |
} | |
// Set data for the fake xhr object | |
jqXHR.status = status; | |
jqXHR.statusText = ( nativeStatusText || statusText ) + ""; | |
// Success/Error | |
if ( isSuccess ) { | |
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); | |
} else { | |
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); | |
} | |
// Status-dependent callbacks | |
jqXHR.statusCode( statusCode ); | |
statusCode = undefined; | |
if ( fireGlobals ) { | |
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", | |
[ jqXHR, s, isSuccess ? success : error ] ); | |
} | |
// Complete | |
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); | |
if ( fireGlobals ) { | |
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); | |
// Handle the global AJAX counter | |
if ( !( --jQuery.active ) ) { | |
jQuery.event.trigger("ajaxStop"); | |
} | |
} | |
} | |
return jqXHR; | |
}, | |
getScript: function( url, callback ) { | |
return jQuery.get( url, undefined, callback, "script" ); | |
}, | |
getJSON: function( url, data, callback ) { | |
return jQuery.get( url, data, callback, "json" ); | |
} | |
}); | |
/* Handles responses to an ajax request: | |
* - sets all responseXXX fields accordingly | |
* - finds the right dataType (mediates between content-type and expected dataType) | |
* - returns the corresponding response | |
*/ | |
function ajaxHandleResponses( s, jqXHR, responses ) { | |
var firstDataType, ct, finalDataType, type, | |
contents = s.contents, | |
dataTypes = s.dataTypes, | |
responseFields = s.responseFields; | |
// Fill responseXXX fields | |
for ( type in responseFields ) { | |
if ( type in responses ) { | |
jqXHR[ responseFields[type] ] = responses[ type ]; | |
} | |
} | |
// Remove auto dataType and get content-type in the process | |
while( dataTypes[ 0 ] === "*" ) { | |
dataTypes.shift(); | |
if ( ct === undefined ) { | |
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); | |
} | |
} | |
// Check if we're dealing with a known content-type | |
if ( ct ) { | |
for ( type in contents ) { | |
if ( contents[ type ] && contents[ type ].test( ct ) ) { | |
dataTypes.unshift( type ); | |
break; | |
} | |
} | |
} | |
// Check to see if we have a response for the expected dataType | |
if ( dataTypes[ 0 ] in responses ) { | |
finalDataType = dataTypes[ 0 ]; | |
} else { | |
// Try convertible dataTypes | |
for ( type in responses ) { | |
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { | |
finalDataType = type; | |
break; | |
} | |
if ( !firstDataType ) { | |
firstDataType = type; | |
} | |
} | |
// Or just use first one | |
finalDataType = finalDataType || firstDataType; | |
} | |
// If we found a dataType | |
// We add the dataType to the list if needed | |
// and return the corresponding response | |
if ( finalDataType ) { | |
if ( finalDataType !== dataTypes[ 0 ] ) { | |
dataTypes.unshift( finalDataType ); | |
} | |
return responses[ finalDataType ]; | |
} | |
} | |
// Chain conversions given the request and the original response | |
function ajaxConvert( s, response ) { | |
var conv2, current, conv, tmp, | |
converters = {}, | |
i = 0, | |
// Work with a copy of dataTypes in case we need to modify it for conversion | |
dataTypes = s.dataTypes.slice(), | |
prev = dataTypes[ 0 ]; | |
// Apply the dataFilter if provided | |
if ( s.dataFilter ) { | |
response = s.dataFilter( response, s.dataType ); | |
} | |
// Create converters map with lowercased keys | |
if ( dataTypes[ 1 ] ) { | |
for ( conv in s.converters ) { | |
converters[ conv.toLowerCase() ] = s.converters[ conv ]; | |
} | |
} | |
// Convert to each sequential dataType, tolerating list modification | |
for ( ; (current = dataTypes[++i]); ) { | |
// There's only work to do if current dataType is non-auto | |
if ( current !== "*" ) { | |
// Convert response if prev dataType is non-auto and differs from current | |
if ( prev !== "*" && prev !== current ) { | |
// Seek a direct converter | |
conv = converters[ prev + " " + current ] || converters[ "* " + current ]; | |
// If none found, seek a pair | |
if ( !conv ) { | |
for ( conv2 in converters ) { | |
// If conv2 outputs current | |
tmp = conv2.split(" "); | |
if ( tmp[ 1 ] === current ) { | |
// If prev can be converted to accepted input | |
conv = converters[ prev + " " + tmp[ 0 ] ] || | |
converters[ "* " + tmp[ 0 ] ]; | |
if ( conv ) { | |
// Condense equivalence converters | |
if ( conv === true ) { | |
conv = converters[ conv2 ]; | |
// Otherwise, insert the intermediate dataType | |
} else if ( converters[ conv2 ] !== true ) { | |
current = tmp[ 0 ]; | |
dataTypes.splice( i--, 0, current ); | |
} | |
break; | |
} | |
} | |
} | |
} | |
// Apply converter (if not an equivalence) | |
if ( conv !== true ) { | |
// Unless errors are allowed to bubble, catch and return them | |
if ( conv && s["throws"] ) { | |
response = conv( response ); | |
} else { | |
try { | |
response = conv( response ); | |
} catch ( e ) { | |
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; | |
} | |
} | |
} | |
} | |
// Update prev for next iteration | |
prev = current; | |
} | |
} | |
return { state: "success", data: response }; | |
} | |
// Install script dataType | |
jQuery.ajaxSetup({ | |
accepts: { | |
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" | |
}, | |
contents: { | |
script: /(?:java|ecma)script/ | |
}, | |
converters: { | |
"text script": function( text ) { | |
jQuery.globalEval( text ); | |
return text; | |
} | |
} | |
}); | |
// Handle cache's special case and global | |
jQuery.ajaxPrefilter( "script", function( s ) { | |
if ( s.cache === undefined ) { | |
s.cache = false; | |
} | |
if ( s.crossDomain ) { | |
s.type = "GET"; | |
s.global = false; | |
} | |
}); | |
// Bind script tag hack transport | |
jQuery.ajaxTransport( "script", function(s) { | |
// This transport only deals with cross domain requests | |
if ( s.crossDomain ) { | |
var script, | |
head = document.head || jQuery("head")[0] || document.documentElement; | |
return { | |
send: function( _, callback ) { | |
script = document.createElement("script"); | |
script.async = true; | |
if ( s.scriptCharset ) { | |
script.charset = s.scriptCharset; | |
} | |
script.src = s.url; | |
// Attach handlers for all browsers | |
script.onload = script.onreadystatechange = function( _, isAbort ) { | |
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { | |
// Handle memory leak in IE | |
script.onload = script.onreadystatechange = null; | |
// Remove the script | |
if ( script.parentNode ) { | |
script.parentNode.removeChild( script ); | |
} | |
// Dereference the script | |
script = null; | |
// Callback if not abort | |
if ( !isAbort ) { | |
callback( 200, "success" ); | |
} | |
} | |
}; | |
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending | |
// Use native DOM manipulation to avoid our domManip AJAX trickery | |
head.insertBefore( script, head.firstChild ); | |
}, | |
abort: function() { | |
if ( script ) { | |
script.onload( undefined, true ); | |
} | |
} | |
}; | |
} | |
}); | |
var oldCallbacks = [], | |
rjsonp = /(=)\?(?=&|$)|\?\?/; | |
// Default jsonp settings | |
jQuery.ajaxSetup({ | |
jsonp: "callback", | |
jsonpCallback: function() { | |
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); | |
this[ callback ] = true; | |
return callback; | |
} | |
}); | |
// Detect, normalize options and install callbacks for jsonp requests | |
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { | |
var callbackName, overwritten, responseContainer, | |
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? | |
"url" : | |
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" | |
); | |
// Handle iff the expected data type is "jsonp" or we have a parameter to set | |
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { | |
// Get callback name, remembering preexisting value associated with it | |
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? | |
s.jsonpCallback() : | |
s.jsonpCallback; | |
// Insert callback into url or form data | |
if ( jsonProp ) { | |
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); | |
} else if ( s.jsonp !== false ) { | |
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; | |
} | |
// Use data converter to retrieve json after script execution | |
s.converters["script json"] = function() { | |
if ( !responseContainer ) { | |
jQuery.error( callbackName + " was not called" ); | |
} | |
return responseContainer[ 0 ]; | |
}; | |
// force json dataType | |
s.dataTypes[ 0 ] = "json"; | |
// Install callback | |
overwritten = window[ callbackName ]; | |
window[ callbackName ] = function() { | |
responseContainer = arguments; | |
}; | |
// Clean-up function (fires after converters) | |
jqXHR.always(function() { | |
// Restore preexisting value | |
window[ callbackName ] = overwritten; | |
// Save back as free | |
if ( s[ callbackName ] ) { | |
// make sure that re-using the options doesn't screw things around | |
s.jsonpCallback = originalSettings.jsonpCallback; | |
// save the callback name for future use | |
oldCallbacks.push( callbackName ); | |
} | |
// Call if it was a function and we have a response | |
if ( responseContainer && jQuery.isFunction( overwritten ) ) { | |
overwritten( responseContainer[ 0 ] ); | |
} | |
responseContainer = overwritten = undefined; | |
}); | |
// Delegate to script | |
return "script"; | |
} | |
}); | |
var xhrCallbacks, xhrSupported, | |
xhrId = 0, | |
// #5280: Internet Explorer will keep connections alive if we don't abort on unload | |
xhrOnUnloadAbort = window.ActiveXObject && function() { | |
// Abort all pending requests | |
var key; | |
for ( key in xhrCallbacks ) { | |
xhrCallbacks[ key ]( undefined, true ); | |
} | |
}; | |
// Functions to create xhrs | |
function createStandardXHR() { | |
try { | |
return new window.XMLHttpRequest(); | |
} catch( e ) {} | |
} | |
function createActiveXHR() { | |
try { | |
return new window.ActiveXObject("Microsoft.XMLHTTP"); | |
} catch( e ) {} | |
} | |
// Create the request object | |
// (This is still attached to ajaxSettings for backward compatibility) | |
jQuery.ajaxSettings.xhr = window.ActiveXObject ? | |
/* Microsoft failed to properly | |
* implement the XMLHttpRequest in IE7 (can't request local files), | |
* so we use the ActiveXObject when it is available | |
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so | |
* we need a fallback. | |
*/ | |
function() { | |
return !this.isLocal && createStandardXHR() || createActiveXHR(); | |
} : | |
// For all other browsers, use the standard XMLHttpRequest object | |
createStandardXHR; | |
// Determine support properties | |
xhrSupported = jQuery.ajaxSettings.xhr(); | |
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); | |
xhrSupported = jQuery.support.ajax = !!xhrSupported; | |
// Create transport if the browser can provide an xhr | |
if ( xhrSupported ) { | |
jQuery.ajaxTransport(function( s ) { | |
// Cross domain only allowed if supported through XMLHttpRequest | |
if ( !s.crossDomain || jQuery.support.cors ) { | |
var callback; | |
return { | |
send: function( headers, complete ) { | |
// Get a new xhr | |
var handle, i, | |
xhr = s.xhr(); | |
// Open the socket | |
// Passing null username, generates a login popup on Opera (#2865) | |
if ( s.username ) { | |
xhr.open( s.type, s.url, s.async, s.username, s.password ); | |
} else { | |
xhr.open( s.type, s.url, s.async ); | |
} | |
// Apply custom fields if provided | |
if ( s.xhrFields ) { | |
for ( i in s.xhrFields ) { | |
xhr[ i ] = s.xhrFields[ i ]; | |
} | |
} | |
// Override mime type if needed | |
if ( s.mimeType && xhr.overrideMimeType ) { | |
xhr.overrideMimeType( s.mimeType ); | |
} | |
// X-Requested-With header | |
// For cross-domain requests, seeing as conditions for a preflight are | |
// akin to a jigsaw puzzle, we simply never set it to be sure. | |
// (it can always be set on a per-request basis or even using ajaxSetup) | |
// For same-domain requests, won't change header if already provided. | |
if ( !s.crossDomain && !headers["X-Requested-With"] ) { | |
headers["X-Requested-With"] = "XMLHttpRequest"; | |
} | |
// Need an extra try/catch for cross domain requests in Firefox 3 | |
try { | |
for ( i in headers ) { | |
xhr.setRequestHeader( i, headers[ i ] ); | |
} | |
} catch( err ) {} | |
// Do send the request | |
// This may raise an exception which is actually | |
// handled in jQuery.ajax (so no try/catch here) | |
xhr.send( ( s.hasContent && s.data ) || null ); | |
// Listener | |
callback = function( _, isAbort ) { | |
var status, responseHeaders, statusText, responses; | |
// Firefox throws exceptions when accessing properties | |
// of an xhr when a network error occurred | |
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) | |
try { | |
// Was never called and is aborted or complete | |
if ( callback && ( isAbort || xhr.readyState === 4 ) ) { | |
// Only called once | |
callback = undefined; | |
// Do not keep as active anymore | |
if ( handle ) { | |
xhr.onreadystatechange = jQuery.noop; | |
if ( xhrOnUnloadAbort ) { | |
delete xhrCallbacks[ handle ]; | |
} | |
} | |
// If it's an abort | |
if ( isAbort ) { | |
// Abort it manually if needed | |
if ( xhr.readyState !== 4 ) { | |
xhr.abort(); | |
} | |
} else { | |
responses = {}; | |
status = xhr.status; | |
responseHeaders = xhr.getAllResponseHeaders(); | |
// When requesting binary data, IE6-9 will throw an exception | |
// on any attempt to access responseText (#11426) | |
if ( typeof xhr.responseText === "string" ) { | |
responses.text = xhr.responseText; | |
} | |
// Firefox throws an exception when accessing | |
// statusText for faulty cross-domain requests | |
try { | |
statusText = xhr.statusText; | |
} catch( e ) { | |
// We normalize with Webkit giving an empty statusText | |
statusText = ""; | |
} | |
// Filter status for non standard behaviors | |
// If the request is local and we have data: assume a success | |
// (success with no data won't get notified, that's the best we | |
// can do given current implementations) | |
if ( !status && s.isLocal && !s.crossDomain ) { | |
status = responses.text ? 200 : 404; | |
// IE - #1450: sometimes returns 1223 when it should be 204 | |
} else if ( status === 1223 ) { | |
status = 204; | |
} | |
} | |
} | |
} catch( firefoxAccessException ) { | |
if ( !isAbort ) { | |
complete( -1, firefoxAccessException ); | |
} | |
} | |
// Call complete if needed | |
if ( responses ) { | |
complete( status, statusText, responses, responseHeaders ); | |
} | |
}; | |
if ( !s.async ) { | |
// if we're in sync mode we fire the callback | |
callback(); | |
} else if ( xhr.readyState === 4 ) { | |
// (IE6 & IE7) if it's in cache and has been | |
// retrieved directly we need to fire the callback | |
setTimeout( callback ); | |
} else { | |
handle = ++xhrId; | |
if ( xhrOnUnloadAbort ) { | |
// Create the active xhrs callbacks list if needed | |
// and attach the unload handler | |
if ( !xhrCallbacks ) { | |
xhrCallbacks = {}; | |
jQuery( window ).unload( xhrOnUnloadAbort ); | |
} | |
// Add to list of active xhrs callbacks | |
xhrCallbacks[ handle ] = callback; | |
} | |
xhr.onreadystatechange = callback; | |
} | |
}, | |
abort: function() { | |
if ( callback ) { | |
callback( undefined, true ); | |
} | |
} | |
}; | |
} | |
}); | |
} | |
var fxNow, timerId, | |
rfxtypes = /^(?:toggle|show|hide)$/, | |
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), | |
rrun = /queueHooks$/, | |
animationPrefilters = [ defaultPrefilter ], | |
tweeners = { | |
"*": [function( prop, value ) { | |
var end, unit, | |
tween = this.createTween( prop, value ), | |
parts = rfxnum.exec( value ), | |
target = tween.cur(), | |
start = +target || 0, | |
scale = 1, | |
maxIterations = 20; | |
if ( parts ) { | |
end = +parts[2]; | |
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); | |
// We need to compute starting value | |
if ( unit !== "px" && start ) { | |
// Iteratively approximate from a nonzero starting point | |
// Prefer the current property, because this process will be trivial if it uses the same units | |
// Fallback to end or a simple constant | |
start = jQuery.css( tween.elem, prop, true ) || end || 1; | |
do { | |
// If previous iteration zeroed out, double until we get *something* | |
// Use a string for doubling factor so we don't accidentally see scale as unchanged below | |
scale = scale || ".5"; | |
// Adjust and apply | |
start = start / scale; | |
jQuery.style( tween.elem, prop, start + unit ); | |
// Update scale, tolerating zero or NaN from tween.cur() | |
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough | |
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); | |
} | |
tween.unit = unit; | |
tween.start = start; | |
// If a +=/-= token was provided, we're doing a relative animation | |
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; | |
} | |
return tween; | |
}] | |
}; | |
// Animations created synchronously will run synchronously | |
function createFxNow() { | |
setTimeout(function() { | |
fxNow = undefined; | |
}); | |
return ( fxNow = jQuery.now() ); | |
} | |
function createTweens( animation, props ) { | |
jQuery.each( props, function( prop, value ) { | |
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), | |
index = 0, | |
length = collection.length; | |
for ( ; index < length; index++ ) { | |
if ( collection[ index ].call( animation, prop, value ) ) { | |
// we're done with this property | |
return; | |
} | |
} | |
}); | |
} | |
function Animation( elem, properties, options ) { | |
var result, | |
stopped, | |
index = 0, | |
length = animationPrefilters.length, | |
deferred = jQuery.Deferred().always( function() { | |
// don't match elem in the :animated selector | |
delete tick.elem; | |
}), | |
tick = function() { | |
if ( stopped ) { | |
return false; | |
} | |
var currentTime = fxNow || createFxNow(), | |
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), | |
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) | |
temp = remaining / animation.duration || 0, | |
percent = 1 - temp, | |
index = 0, | |
length = animation.tweens.length; | |
for ( ; index < length ; index++ ) { | |
animation.tweens[ index ].run( percent ); | |
} | |
deferred.notifyWith( elem, [ animation, percent, remaining ]); | |
if ( percent < 1 && length ) { | |
return remaining; | |
} else { | |
deferred.resolveWith( elem, [ animation ] ); | |
return false; | |
} | |
}, | |
animation = deferred.promise({ | |
elem: elem, | |
props: jQuery.extend( {}, properties ), | |
opts: jQuery.extend( true, { specialEasing: {} }, options ), | |
originalProperties: properties, | |
originalOptions: options, | |
startTime: fxNow || createFxNow(), | |
duration: options.duration, | |
tweens: [], | |
createTween: function( prop, end ) { | |
var tween = jQuery.Tween( elem, animation.opts, prop, end, | |
animation.opts.specialEasing[ prop ] || animation.opts.easing ); | |
animation.tweens.push( tween ); | |
return tween; | |
}, | |
stop: function( gotoEnd ) { | |
var index = 0, | |
// if we are going to the end, we want to run all the tweens | |
// otherwise we skip this part | |
length = gotoEnd ? animation.tweens.length : 0; | |
if ( stopped ) { | |
return this; | |
} | |
stopped = true; | |
for ( ; index < length ; index++ ) { | |
animation.tweens[ index ].run( 1 ); | |
} | |
// resolve when we played the last frame | |
// otherwise, reject | |
if ( gotoEnd ) { | |
deferred.resolveWith( elem, [ animation, gotoEnd ] ); | |
} else { | |
deferred.rejectWith( elem, [ animation, gotoEnd ] ); | |
} | |
return this; | |
} | |
}), | |
props = animation.props; | |
propFilter( props, animation.opts.specialEasing ); | |
for ( ; index < length ; index++ ) { | |
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); | |
if ( result ) { | |
return result; | |
} | |
} | |
createTweens( animation, props ); | |
if ( jQuery.isFunction( animation.opts.start ) ) { | |
animation.opts.start.call( elem, animation ); | |
} | |
jQuery.fx.timer( | |
jQuery.extend( tick, { | |
elem: elem, | |
anim: animation, | |
queue: animation.opts.queue | |
}) | |
); | |
// attach callbacks from options | |
return animation.progress( animation.opts.progress ) | |
.done( animation.opts.done, animation.opts.complete ) | |
.fail( animation.opts.fail ) | |
.always( animation.opts.always ); | |
} | |
function propFilter( props, specialEasing ) { | |
var value, name, index, easing, hooks; | |
// camelCase, specialEasing and expand cssHook pass | |
for ( index in props ) { | |
name = jQuery.camelCase( index ); | |
easing = specialEasing[ name ]; | |
value = props[ index ]; | |
if ( jQuery.isArray( value ) ) { | |
easing = value[ 1 ]; | |
value = props[ index ] = value[ 0 ]; | |
} | |
if ( index !== name ) { | |
props[ name ] = value; | |
delete props[ index ]; | |
} | |
hooks = jQuery.cssHooks[ name ]; | |
if ( hooks && "expand" in hooks ) { | |
value = hooks.expand( value ); | |
delete props[ name ]; | |
// not quite $.extend, this wont overwrite keys already present. | |
// also - reusing 'index' from above because we have the correct "name" | |
for ( index in value ) { | |
if ( !( index in props ) ) { | |
props[ index ] = value[ index ]; | |
specialEasing[ index ] = easing; | |
} | |
} | |
} else { | |
specialEasing[ name ] = easing; | |
} | |
} | |
} | |
jQuery.Animation = jQuery.extend( Animation, { | |
tweener: function( props, callback ) { | |
if ( jQuery.isFunction( props ) ) { | |
callback = props; | |
props = [ "*" ]; | |
} else { | |
props = props.split(" "); | |
} | |
var prop, | |
index = 0, | |
length = props.length; | |
for ( ; index < length ; index++ ) { | |
prop = props[ index ]; | |
tweeners[ prop ] = tweeners[ prop ] || []; | |
tweeners[ prop ].unshift( callback ); | |
} | |
}, | |
prefilter: function( callback, prepend ) { | |
if ( prepend ) { | |
animationPrefilters.unshift( callback ); | |
} else { | |
animationPrefilters.push( callback ); | |
} | |
} | |
}); | |
function defaultPrefilter( elem, props, opts ) { | |
/*jshint validthis:true */ | |
var prop, index, length, | |
value, dataShow, toggle, | |
tween, hooks, oldfire, | |
anim = this, | |
style = elem.style, | |
orig = {}, | |
handled = [], | |
hidden = elem.nodeType && isHidden( elem ); | |
// handle queue: false promises | |
if ( !opts.queue ) { | |
hooks = jQuery._queueHooks( elem, "fx" ); | |
if ( hooks.unqueued == null ) { | |
hooks.unqueued = 0; | |
oldfire = hooks.empty.fire; | |
hooks.empty.fire = function() { | |
if ( !hooks.unqueued ) { | |
oldfire(); | |
} | |
}; | |
} | |
hooks.unqueued++; | |
anim.always(function() { | |
// doing this makes sure that the complete handler will be called | |
// before this completes | |
anim.always(function() { | |
hooks.unqueued--; | |
if ( !jQuery.queue( elem, "fx" ).length ) { | |
hooks.empty.fire(); | |
} | |
}); | |
}); | |
} | |
// height/width overflow pass | |
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { | |
// Make sure that nothing sneaks out | |
// Record all 3 overflow attributes because IE does not | |
// change the overflow attribute when overflowX and | |
// overflowY are set to the same value | |
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; | |
// Set display property to inline-block for height/width | |
// animations on inline elements that are having width/height animated | |
if ( jQuery.css( elem, "display" ) === "inline" && | |
jQuery.css( elem, "float" ) === "none" ) { | |
// inline-level elements accept inline-block; | |
// block-level elements need to be inline with layout | |
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { | |
style.display = "inline-block"; | |
} else { | |
style.zoom = 1; | |
} | |
} | |
} | |
if ( opts.overflow ) { | |
style.overflow = "hidden"; | |
if ( !jQuery.support.shrinkWrapBlocks ) { | |
anim.always(function() { | |
style.overflow = opts.overflow[ 0 ]; | |
style.overflowX = opts.overflow[ 1 ]; | |
style.overflowY = opts.overflow[ 2 ]; | |
}); | |
} | |
} | |
// show/hide pass | |
for ( index in props ) { | |
value = props[ index ]; | |
if ( rfxtypes.exec( value ) ) { | |
delete props[ index ]; | |
toggle = toggle || value === "toggle"; | |
if ( value === ( hidden ? "hide" : "show" ) ) { | |
continue; | |
} | |
handled.push( index ); | |
} | |
} | |
length = handled.length; | |
if ( length ) { | |
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); | |
if ( "hidden" in dataShow ) { | |
hidden = dataShow.hidden; | |
} | |
// store state if its toggle - enables .stop().toggle() to "reverse" | |
if ( toggle ) { | |
dataShow.hidden = !hidden; | |
} | |
if ( hidden ) { | |
jQuery( elem ).show(); | |
} else { | |
anim.done(function() { | |
jQuery( elem ).hide(); | |
}); | |
} | |
anim.done(function() { | |
var prop; | |
jQuery._removeData( elem, "fxshow" ); | |
for ( prop in orig ) { | |
jQuery.style( elem, prop, orig[ prop ] ); | |
} | |
}); | |
for ( index = 0 ; index < length ; index++ ) { | |
prop = handled[ index ]; | |
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); | |
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); | |
if ( !( prop in dataShow ) ) { | |
dataShow[ prop ] = tween.start; | |
if ( hidden ) { | |
tween.end = tween.start; | |
tween.start = prop === "width" || prop === "height" ? 1 : 0; | |
} | |
} | |
} | |
} | |
} | |
function Tween( elem, options, prop, end, easing ) { | |
return new Tween.prototype.init( elem, options, prop, end, easing ); | |
} | |
jQuery.Tween = Tween; | |
Tween.prototype = { | |
constructor: Tween, | |
init: function( elem, options, prop, end, easing, unit ) { | |
this.elem = elem; | |
this.prop = prop; | |
this.easing = easing || "swing"; | |
this.options = options; | |
this.start = this.now = this.cur(); | |
this.end = end; | |
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); | |
}, | |
cur: function() { | |
var hooks = Tween.propHooks[ this.prop ]; | |
return hooks && hooks.get ? | |
hooks.get( this ) : | |
Tween.propHooks._default.get( this ); | |
}, | |
run: function( percent ) { | |
var eased, | |
hooks = Tween.propHooks[ this.prop ]; | |
if ( this.options.duration ) { | |
this.pos = eased = jQuery.easing[ this.easing ]( | |
percent, this.options.duration * percent, 0, 1, this.options.duration | |
); | |
} else { | |
this.pos = eased = percent; | |
} | |
this.now = ( this.end - this.start ) * eased + this.start; | |
if ( this.options.step ) { | |
this.options.step.call( this.elem, this.now, this ); | |
} | |
if ( hooks && hooks.set ) { | |
hooks.set( this ); | |
} else { | |
Tween.propHooks._default.set( this ); | |
} | |
return this; | |
} | |
}; | |
Tween.prototype.init.prototype = Tween.prototype; | |
Tween.propHooks = { | |
_default: { | |
get: function( tween ) { | |
var result; | |
if ( tween.elem[ tween.prop ] != null && | |
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { | |
return tween.elem[ tween.prop ]; | |
} | |
// passing an empty string as a 3rd parameter to .css will automatically | |
// attempt a parseFloat and fallback to a string if the parse fails | |
// so, simple values such as "10px" are parsed to Float. | |
// complex values such as "rotate(1rad)" are returned as is. | |
result = jQuery.css( tween.elem, tween.prop, "" ); | |
// Empty strings, null, undefined and "auto" are converted to 0. | |
return !result || result === "auto" ? 0 : result; | |
}, | |
set: function( tween ) { | |
// use step hook for back compat - use cssHook if its there - use .style if its | |
// available and use plain properties where available | |
if ( jQuery.fx.step[ tween.prop ] ) { | |
jQuery.fx.step[ tween.prop ]( tween ); | |
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { | |
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); | |
} else { | |
tween.elem[ tween.prop ] = tween.now; | |
} | |
} | |
} | |
}; | |
// Remove in 2.0 - this supports IE8's panic based approach | |
// to setting things on disconnected nodes | |
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { | |
set: function( tween ) { | |
if ( tween.elem.nodeType && tween.elem.parentNode ) { | |
tween.elem[ tween.prop ] = tween.now; | |
} | |
} | |
}; | |
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { | |
var cssFn = jQuery.fn[ name ]; | |
jQuery.fn[ name ] = function( speed, easing, callback ) { | |
return speed == null || typeof speed === "boolean" ? | |
cssFn.apply( this, arguments ) : | |
this.animate( genFx( name, true ), speed, easing, callback ); | |
}; | |
}); | |
jQuery.fn.extend({ | |
fadeTo: function( speed, to, easing, callback ) { | |
// show any hidden elements after setting opacity to 0 | |
return this.filter( isHidden ).css( "opacity", 0 ).show() | |
// animate to the value specified | |
.end().animate({ opacity: to }, speed, easing, callback ); | |
}, | |
animate: function( prop, speed, easing, callback ) { | |
var empty = jQuery.isEmptyObject( prop ), | |
optall = jQuery.speed( speed, easing, callback ), | |
doAnimation = function() { | |
// Operate on a copy of prop so per-property easing won't be lost | |
var anim = Animation( this, jQuery.extend( {}, prop ), optall ); | |
doAnimation.finish = function() { | |
anim.stop( true ); | |
}; | |
// Empty animations, or finishing resolves immediately | |
if ( empty || jQuery._data( this, "finish" ) ) { | |
anim.stop( true ); | |
} | |
}; | |
doAnimation.finish = doAnimation; | |
return empty || optall.queue === false ? | |
this.each( doAnimation ) : | |
this.queue( optall.queue, doAnimation ); | |
}, | |
stop: function( type, clearQueue, gotoEnd ) { | |
var stopQueue = function( hooks ) { | |
var stop = hooks.stop; | |
delete hooks.stop; | |
stop( gotoEnd ); | |
}; | |
if ( typeof type !== "string" ) { | |
gotoEnd = clearQueue; | |
clearQueue = type; | |
type = undefined; | |
} | |
if ( clearQueue && type !== false ) { | |
this.queue( type || "fx", [] ); | |
} | |
return this.each(function() { | |
var dequeue = true, | |
index = type != null && type + "queueHooks", | |
timers = jQuery.timers, | |
data = jQuery._data( this ); | |
if ( index ) { | |
if ( data[ index ] && data[ index ].stop ) { | |
stopQueue( data[ index ] ); | |
} | |
} else { | |
for ( index in data ) { | |
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { | |
stopQueue( data[ index ] ); | |
} | |
} | |
} | |
for ( index = timers.length; index--; ) { | |
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { | |
timers[ index ].anim.stop( gotoEnd ); | |
dequeue = false; | |
timers.splice( index, 1 ); | |
} | |
} | |
// start the next in the queue if the last step wasn't forced | |
// timers currently will call their complete callbacks, which will dequeue | |
// but only if they were gotoEnd | |
if ( dequeue || !gotoEnd ) { | |
jQuery.dequeue( this, type ); | |
} | |
}); | |
}, | |
finish: function( type ) { | |
if ( type !== false ) { | |
type = type || "fx"; | |
} | |
return this.each(function() { | |
var index, | |
data = jQuery._data( this ), | |
queue = data[ type + "queue" ], | |
hooks = data[ type + "queueHooks" ], | |
timers = jQuery.timers, | |
length = queue ? queue.length : 0; | |
// enable finishing flag on private data | |
data.finish = true; | |
// empty the queue first | |
jQuery.queue( this, type, [] ); | |
if ( hooks && hooks.cur && hooks.cur.finish ) { | |
hooks.cur.finish.call( this ); | |
} | |
// look for any active animations, and finish them | |
for ( index = timers.length; index--; ) { | |
if ( timers[ index ].elem === this && timers[ index ].queue === type ) { | |
timers[ index ].anim.stop( true ); | |
timers.splice( index, 1 ); | |
} | |
} | |
// look for any animations in the old queue and finish them | |
for ( index = 0; index < length; index++ ) { | |
if ( queue[ index ] && queue[ index ].finish ) { | |
queue[ index ].finish.call( this ); | |
} | |
} | |
// turn off finishing flag | |
delete data.finish; | |
}); | |
} | |
}); | |
// Generate parameters to create a standard animation | |
function genFx( type, includeWidth ) { | |
var which, | |
attrs = { height: type }, | |
i = 0; | |
// if we include width, step value is 1 to do all cssExpand values, | |
// if we don't include width, step value is 2 to skip over Left and Right | |
includeWidth = includeWidth? 1 : 0; | |
for( ; i < 4 ; i += 2 - includeWidth ) { | |
which = cssExpand[ i ]; | |
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; | |
} | |
if ( includeWidth ) { | |
attrs.opacity = attrs.width = type; | |
} | |
return attrs; | |
} | |
// Generate shortcuts for custom animations | |
jQuery.each({ | |
slideDown: genFx("show"), | |
slideUp: genFx("hide"), | |
slideToggle: genFx("toggle"), | |
fadeIn: { opacity: "show" }, | |
fadeOut: { opacity: "hide" }, | |
fadeToggle: { opacity: "toggle" } | |
}, function( name, props ) { | |
jQuery.fn[ name ] = function( speed, easing, callback ) { | |
return this.animate( props, speed, easing, callback ); | |
}; | |
}); | |
jQuery.speed = function( speed, easing, fn ) { | |
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { | |
complete: fn || !fn && easing || | |
jQuery.isFunction( speed ) && speed, | |
duration: speed, | |
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing | |
}; | |
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : | |
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; | |
// normalize opt.queue - true/undefined/null -> "fx" | |
if ( opt.queue == null || opt.queue === true ) { | |
opt.queue = "fx"; | |
} | |
// Queueing | |
opt.old = opt.complete; | |
opt.complete = function() { | |
if ( jQuery.isFunction( opt.old ) ) { | |
opt.old.call( this ); | |
} | |
if ( opt.queue ) { | |
jQuery.dequeue( this, opt.queue ); | |
} | |
}; | |
return opt; | |
}; | |
jQuery.easing = { | |
linear: function( p ) { | |
return p; | |
}, | |
swing: function( p ) { | |
return 0.5 - Math.cos( p*Math.PI ) / 2; | |
} | |
}; | |
jQuery.timers = []; | |
jQuery.fx = Tween.prototype.init; | |
jQuery.fx.tick = function() { | |
var timer, | |
timers = jQuery.timers, | |
i = 0; | |
fxNow = jQuery.now(); | |
for ( ; i < timers.length; i++ ) { | |
timer = timers[ i ]; | |
// Checks the timer has not already been removed | |
if ( !timer() && timers[ i ] === timer ) { | |
timers.splice( i--, 1 ); | |
} | |
} | |
if ( !timers.length ) { | |
jQuery.fx.stop(); | |
} | |
fxNow = undefined; | |
}; | |
jQuery.fx.timer = function( timer ) { | |
if ( timer() && jQuery.timers.push( timer ) ) { | |
jQuery.fx.start(); | |
} | |
}; | |
jQuery.fx.interval = 13; | |
jQuery.fx.start = function() { | |
if ( !timerId ) { | |
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); | |
} | |
}; | |
jQuery.fx.stop = function() { | |
clearInterval( timerId ); | |
timerId = null; | |
}; | |
jQuery.fx.speeds = { | |
slow: 600, | |
fast: 200, | |
// Default speed | |
_default: 400 | |
}; | |
// Back Compat <1.8 extension point | |
jQuery.fx.step = {}; | |
if ( jQuery.expr && jQuery.expr.filters ) { | |
jQuery.expr.filters.animated = function( elem ) { | |
return jQuery.grep(jQuery.timers, function( fn ) { | |
return elem === fn.elem; | |
}).length; | |
}; | |
} | |
jQuery.fn.offset = function( options ) { | |
if ( arguments.length ) { | |
return options === undefined ? | |
this : | |
this.each(function( i ) { | |
jQuery.offset.setOffset( this, options, i ); | |
}); | |
} | |
var docElem, win, | |
box = { top: 0, left: 0 }, | |
elem = this[ 0 ], | |
doc = elem && elem.ownerDocument; | |
if ( !doc ) { | |
return; | |
} | |
docElem = doc.documentElement; | |
// Make sure it's not a disconnected DOM node | |
if ( !jQuery.contains( docElem, elem ) ) { | |
return box; | |
} | |
// If we don't have gBCR, just use 0,0 rather than error | |
// BlackBerry 5, iOS 3 (original iPhone) | |
if ( typeof elem.getBoundingClientRect !== core_strundefined ) { | |
box = elem.getBoundingClientRect(); | |
} | |
win = getWindow( doc ); | |
return { | |
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), | |
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) | |
}; | |
}; | |
jQuery.offset = { | |
setOffset: function( elem, options, i ) { | |
var position = jQuery.css( elem, "position" ); | |
// set position first, in-case top/left are set even on static elem | |
if ( position === "static" ) { | |
elem.style.position = "relative"; | |
} | |
var curElem = jQuery( elem ), | |
curOffset = curElem.offset(), | |
curCSSTop = jQuery.css( elem, "top" ), | |
curCSSLeft = jQuery.css( elem, "left" ), | |
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, | |
props = {}, curPosition = {}, curTop, curLeft; | |
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed | |
if ( calculatePosition ) { | |
curPosition = curElem.position(); | |
curTop = curPosition.top; | |
curLeft = curPosition.left; | |
} else { | |
curTop = parseFloat( curCSSTop ) || 0; | |
curLeft = parseFloat( curCSSLeft ) || 0; | |
} | |
if ( jQuery.isFunction( options ) ) { | |
options = options.call( elem, i, curOffset ); | |
} | |
if ( options.top != null ) { | |
props.top = ( options.top - curOffset.top ) + curTop; | |
} | |
if ( options.left != null ) { | |
props.left = ( options.left - curOffset.left ) + curLeft; | |
} | |
if ( "using" in options ) { | |
options.using.call( elem, props ); | |
} else { | |
curElem.css( props ); | |
} | |
} | |
}; | |
jQuery.fn.extend({ | |
position: function() { | |
if ( !this[ 0 ] ) { | |
return; | |
} | |
var offsetParent, offset, | |
parentOffset = { top: 0, left: 0 }, | |
elem = this[ 0 ]; | |
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent | |
if ( jQuery.css( elem, "position" ) === "fixed" ) { | |
// we assume that getBoundingClientRect is available when computed position is fixed | |
offset = elem.getBoundingClientRect(); | |
} else { | |
// Get *real* offsetParent | |
offsetParent = this.offsetParent(); | |
// Get correct offsets | |
offset = this.offset(); | |
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { | |
parentOffset = offsetParent.offset(); | |
} | |
// Add offsetParent borders | |
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); | |
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); | |
} | |
// Subtract parent offsets and element margins | |
// note: when an element has margin: auto the offsetLeft and marginLeft | |
// are the same in Safari causing offset.left to incorrectly be 0 | |
return { | |
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), | |
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) | |
}; | |
}, | |
offsetParent: function() { | |
return this.map(function() { | |
var offsetParent = this.offsetParent || document.documentElement; | |
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { | |
offsetParent = offsetParent.offsetParent; | |
} | |
return offsetParent || document.documentElement; | |
}); | |
} | |
}); | |
// Create scrollLeft and scrollTop methods | |
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { | |
var top = /Y/.test( prop ); | |
jQuery.fn[ method ] = function( val ) { | |
return jQuery.access( this, function( elem, method, val ) { | |
var win = getWindow( elem ); | |
if ( val === undefined ) { | |
return win ? (prop in win) ? win[ prop ] : | |
win.document.documentElement[ method ] : | |
elem[ method ]; | |
} | |
if ( win ) { | |
win.scrollTo( | |
!top ? val : jQuery( win ).scrollLeft(), | |
top ? val : jQuery( win ).scrollTop() | |
); | |
} else { | |
elem[ method ] = val; | |
} | |
}, method, val, arguments.length, null ); | |
}; | |
}); | |
function getWindow( elem ) { | |
return jQuery.isWindow( elem ) ? | |
elem : | |
elem.nodeType === 9 ? | |
elem.defaultView || elem.parentWindow : | |
false; | |
} | |
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods | |
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { | |
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { | |
// margin is only for outerHeight, outerWidth | |
jQuery.fn[ funcName ] = function( margin, value ) { | |
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), | |
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); | |
return jQuery.access( this, function( elem, type, value ) { | |
var doc; | |
if ( jQuery.isWindow( elem ) ) { | |
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there | |
// isn't a whole lot we can do. See pull request at this URL for discussion: | |
// https://github.com/jquery/jquery/pull/764 | |
return elem.document.documentElement[ "client" + name ]; | |
} | |
// Get document width or height | |
if ( elem.nodeType === 9 ) { | |
doc = elem.documentElement; | |
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest | |
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. | |
return Math.max( | |
elem.body[ "scroll" + name ], doc[ "scroll" + name ], | |
elem.body[ "offset" + name ], doc[ "offset" + name ], | |
doc[ "client" + name ] | |
); | |
} | |
return value === undefined ? | |
// Get width or height on the element, requesting but not forcing parseFloat | |
jQuery.css( elem, type, extra ) : | |
// Set width or height on the element | |
jQuery.style( elem, type, value, extra ); | |
}, type, chainable ? margin : undefined, chainable, null ); | |
}; | |
}); | |
}); | |
// Limit scope pollution from any deprecated API | |
// (function() { | |
// })(); | |
// Expose jQuery to the global object | |
window.jQuery = window.$ = jQuery; | |
// Expose jQuery as an AMD module, but only for AMD loaders that | |
// understand the issues with loading multiple versions of jQuery | |
// in a page that all might call define(). The loader will indicate | |
// they have special allowances for multiple jQuery versions by | |
// specifying define.amd.jQuery = true. Register as a named module, | |
// since jQuery can be concatenated with other files that may use define, | |
// but not use a proper concatenation script that understands anonymous | |
// AMD modules. A named AMD is safest and most robust way to register. | |
// Lowercase jquery is used because AMD module names are derived from | |
// file names, and jQuery is normally delivered in a lowercase file name. | |
// Do this after creating the global so that if an AMD module wants to call | |
// noConflict to hide this version of jQuery, it will work. | |
if ( typeof define === "function" && define.amd && define.amd.jQuery ) { | |
define( "jquery", [], function () { return jQuery; } ); | |
} | |
})( window ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************** | |
* HTML CSS | |
*/ | |
.chartWrap { | |
margin: 0; | |
padding: 0; | |
overflow: hidden; | |
} | |
/******************** | |
Box shadow and border radius styling | |
*/ | |
.nvtooltip.with-3d-shadow, .with-3d-shadow .nvtooltip { | |
-moz-box-shadow: 0 5px 10px rgba(0,0,0,.2); | |
-webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2); | |
box-shadow: 0 5px 10px rgba(0,0,0,.2); | |
-webkit-border-radius: 6px; | |
-moz-border-radius: 6px; | |
border-radius: 6px; | |
} | |
/******************** | |
* TOOLTIP CSS | |
*/ | |
.nvtooltip { | |
position: absolute; | |
background-color: rgba(255,255,255,1.0); | |
padding: 1px; | |
border: 1px solid rgba(0,0,0,.2); | |
z-index: 10000; | |
font-family: Arial; | |
font-size: 13px; | |
text-align: left; | |
pointer-events: none; | |
white-space: nowrap; | |
-webkit-touch-callout: none; | |
-webkit-user-select: none; | |
-khtml-user-select: none; | |
-moz-user-select: none; | |
-ms-user-select: none; | |
user-select: none; | |
} | |
/*Give tooltips that old fade in transition by | |
putting a "with-transitions" class on the container div. | |
*/ | |
.nvtooltip.with-transitions, .with-transitions .nvtooltip { | |
transition: opacity 250ms linear; | |
-moz-transition: opacity 250ms linear; | |
-webkit-transition: opacity 250ms linear; | |
transition-delay: 250ms; | |
-moz-transition-delay: 250ms; | |
-webkit-transition-delay: 250ms; | |
} | |
.nvtooltip.x-nvtooltip, | |
.nvtooltip.y-nvtooltip { | |
padding: 8px; | |
} | |
.nvtooltip h3 { | |
margin: 0; | |
padding: 4px 14px; | |
line-height: 18px; | |
font-weight: normal; | |
background-color: rgba(247,247,247,0.75); | |
text-align: center; | |
border-bottom: 1px solid #ebebeb; | |
-webkit-border-radius: 5px 5px 0 0; | |
-moz-border-radius: 5px 5px 0 0; | |
border-radius: 5px 5px 0 0; | |
} | |
.nvtooltip p { | |
margin: 0; | |
padding: 5px 14px; | |
text-align: center; | |
} | |
.nvtooltip span { | |
display: inline-block; | |
margin: 2px 0; | |
} | |
.nvtooltip table { | |
margin: 6px; | |
border-spacing:0; | |
} | |
.nvtooltip table td { | |
padding: 2px 9px 2px 0; | |
vertical-align: middle; | |
} | |
.nvtooltip table td.key { | |
font-weight:normal; | |
} | |
.nvtooltip table td.value { | |
text-align: right; | |
font-weight: bold; | |
} | |
.nvtooltip table tr.highlight td { | |
padding: 1px 9px 1px 0; | |
border-bottom-style: solid; | |
border-bottom-width: 1px; | |
border-top-style: solid; | |
border-top-width: 1px; | |
} | |
.nvtooltip table td.legend-color-guide div { | |
width: 8px; | |
height: 8px; | |
vertical-align: middle; | |
} | |
.nvtooltip .footer { | |
padding: 3px; | |
text-align: center; | |
} | |
.nvtooltip-pending-removal { | |
position: absolute; | |
pointer-events: none; | |
} | |
/******************** | |
* SVG CSS | |
*/ | |
svg { | |
-webkit-touch-callout: none; | |
-webkit-user-select: none; | |
-khtml-user-select: none; | |
-moz-user-select: none; | |
-ms-user-select: none; | |
user-select: none; | |
/* Trying to get SVG to act like a greedy block in all browsers */ | |
display: block; | |
width:100%; | |
height:100%; | |
} | |
svg text { | |
font: normal 12px Arial; | |
} | |
svg .title { | |
font: bold 14px Arial; | |
} | |
.nvd3 .nv-background { | |
fill: white; | |
fill-opacity: 0; | |
/* | |
pointer-events: none; | |
*/ | |
} | |
.nvd3.nv-noData { | |
font-size: 18px; | |
font-weight: bold; | |
} | |
/********** | |
* Brush | |
*/ | |
.nv-brush .extent { | |
fill-opacity: .125; | |
shape-rendering: crispEdges; | |
} | |
/********** | |
* Legend | |
*/ | |
.nvd3 .nv-legend .nv-series { | |
cursor: pointer; | |
} | |
.nvd3 .nv-legend .disabled circle { | |
fill-opacity: 0; | |
} | |
/********** | |
* Axes | |
*/ | |
.nvd3 .nv-axis { | |
pointer-events:none; | |
} | |
.nvd3 .nv-axis path { | |
fill: none; | |
stroke: #000; | |
stroke-opacity: .75; | |
shape-rendering: crispEdges; | |
} | |
.nvd3 .nv-axis path.domain { | |
stroke-opacity: .75; | |
} | |
.nvd3 .nv-axis.nv-x path.domain { | |
stroke-opacity: 0; | |
} | |
.nvd3 .nv-axis line { | |
fill: none; | |
stroke: #e5e5e5; | |
shape-rendering: crispEdges; | |
} | |
.nvd3 .nv-axis .zero line, | |
/*this selector may not be necessary*/ .nvd3 .nv-axis line.zero { | |
stroke-opacity: .75; | |
} | |
.nvd3 .nv-axis .nv-axisMaxMin text { | |
font-weight: bold; | |
} | |
.nvd3 .x .nv-axis .nv-axisMaxMin text, | |
.nvd3 .x2 .nv-axis .nv-axisMaxMin text, | |
.nvd3 .x3 .nv-axis .nv-axisMaxMin text { | |
text-anchor: middle | |
} | |
/********** | |
* Brush | |
*/ | |
.nv-brush .resize path { | |
fill: #eee; | |
stroke: #666; | |
} | |
/********** | |
* Bars | |
*/ | |
.nvd3 .nv-bars .negative rect { | |
zfill: brown; | |
} | |
.nvd3 .nv-bars rect { | |
zfill: steelblue; | |
fill-opacity: .75; | |
transition: fill-opacity 250ms linear; | |
-moz-transition: fill-opacity 250ms linear; | |
-webkit-transition: fill-opacity 250ms linear; | |
} | |
.nvd3 .nv-bars rect.hover { | |
fill-opacity: 1; | |
} | |
.nvd3 .nv-bars .hover rect { | |
fill: lightblue; | |
} | |
.nvd3 .nv-bars text { | |
fill: rgba(0,0,0,0); | |
} | |
.nvd3 .nv-bars .hover text { | |
fill: rgba(0,0,0,1); | |
} | |
/********** | |
* Bars | |
*/ | |
.nvd3 .nv-multibar .nv-groups rect, | |
.nvd3 .nv-multibarHorizontal .nv-groups rect, | |
.nvd3 .nv-discretebar .nv-groups rect { | |
stroke-opacity: 0; | |
transition: fill-opacity 250ms linear; | |
-moz-transition: fill-opacity 250ms linear; | |
-webkit-transition: fill-opacity 250ms linear; | |
} | |
.nvd3 .nv-multibar .nv-groups rect:hover, | |
.nvd3 .nv-multibarHorizontal .nv-groups rect:hover, | |
.nvd3 .nv-discretebar .nv-groups rect:hover { | |
fill-opacity: 1; | |
} | |
.nvd3 .nv-discretebar .nv-groups text, | |
.nvd3 .nv-multibarHorizontal .nv-groups text { | |
font-weight: bold; | |
fill: rgba(0,0,0,1); | |
stroke: rgba(0,0,0,0); | |
} | |
/*********** | |
* Pie Chart | |
*/ | |
.nvd3.nv-pie path { | |
stroke-opacity: 0; | |
transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear; | |
-moz-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear; | |
-webkit-transition: fill-opacity 250ms linear, stroke-width 250ms linear, stroke-opacity 250ms linear; | |
} | |
.nvd3.nv-pie .nv-slice text { | |
stroke: #000; | |
stroke-width: 0; | |
} | |
.nvd3.nv-pie path { | |
stroke: #fff; | |
stroke-width: 1px; | |
stroke-opacity: 1; | |
} | |
.nvd3.nv-pie .hover path { | |
fill-opacity: .7; | |
} | |
.nvd3.nv-pie .nv-label { | |
pointer-events: none; | |
} | |
.nvd3.nv-pie .nv-label rect { | |
fill-opacity: 0; | |
stroke-opacity: 0; | |
} | |
/********** | |
* Lines | |
*/ | |
.nvd3 .nv-groups path.nv-line { | |
fill: none; | |
stroke-width: 1.5px; | |
/* | |
stroke-linecap: round; | |
shape-rendering: geometricPrecision; | |
transition: stroke-width 250ms linear; | |
-moz-transition: stroke-width 250ms linear; | |
-webkit-transition: stroke-width 250ms linear; | |
transition-delay: 250ms | |
-moz-transition-delay: 250ms; | |
-webkit-transition-delay: 250ms; | |
*/ | |
} | |
.nvd3 .nv-groups path.nv-line.nv-thin-line { | |
stroke-width: 1px; | |
} | |
.nvd3 .nv-groups path.nv-area { | |
stroke: none; | |
/* | |
stroke-linecap: round; | |
shape-rendering: geometricPrecision; | |
stroke-width: 2.5px; | |
transition: stroke-width 250ms linear; | |
-moz-transition: stroke-width 250ms linear; | |
-webkit-transition: stroke-width 250ms linear; | |
transition-delay: 250ms | |
-moz-transition-delay: 250ms; | |
-webkit-transition-delay: 250ms; | |
*/ | |
} | |
.nvd3 .nv-line.hover path { | |
stroke-width: 6px; | |
} | |
/* | |
.nvd3.scatter .groups .point { | |
fill-opacity: 0.1; | |
stroke-opacity: 0.1; | |
} | |
*/ | |
.nvd3.nv-line .nvd3.nv-scatter .nv-groups .nv-point { | |
fill-opacity: 0; | |
stroke-opacity: 0; | |
} | |
.nvd3.nv-scatter.nv-single-point .nv-groups .nv-point { | |
fill-opacity: .5 !important; | |
stroke-opacity: .5 !important; | |
} | |
.with-transitions .nvd3 .nv-groups .nv-point { | |
transition: stroke-width 250ms linear, stroke-opacity 250ms linear; | |
-moz-transition: stroke-width 250ms linear, stroke-opacity 250ms linear; | |
-webkit-transition: stroke-width 250ms linear, stroke-opacity 250ms linear; | |
} | |
.nvd3.nv-scatter .nv-groups .nv-point.hover, | |
.nvd3 .nv-groups .nv-point.hover { | |
stroke-width: 7px; | |
fill-opacity: .95 !important; | |
stroke-opacity: .95 !important; | |
} | |
.nvd3 .nv-point-paths path { | |
stroke: #aaa; | |
stroke-opacity: 0; | |
fill: #eee; | |
fill-opacity: 0; | |
} | |
.nvd3 .nv-indexLine { | |
cursor: ew-resize; | |
} | |
/********** | |
* Distribution | |
*/ | |
.nvd3 .nv-distribution { | |
pointer-events: none; | |
} | |
/********** | |
* Scatter | |
*/ | |
/* **Attempting to remove this for useVoronoi(false), need to see if it's required anywhere | |
.nvd3 .nv-groups .nv-point { | |
pointer-events: none; | |
} | |
*/ | |
.nvd3 .nv-groups .nv-point.hover { | |
stroke-width: 20px; | |
stroke-opacity: .5; | |
} | |
.nvd3 .nv-scatter .nv-point.hover { | |
fill-opacity: 1; | |
} | |
/* | |
.nv-group.hover .nv-point { | |
fill-opacity: 1; | |
} | |
*/ | |
/********** | |
* Stacked Area | |
*/ | |
.nvd3.nv-stackedarea path.nv-area { | |
fill-opacity: .7; | |
/* | |
stroke-opacity: .65; | |
fill-opacity: 1; | |
*/ | |
stroke-opacity: 0; | |
transition: fill-opacity 250ms linear, stroke-opacity 250ms linear; | |
-moz-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear; | |
-webkit-transition: fill-opacity 250ms linear, stroke-opacity 250ms linear; | |
/* | |
transition-delay: 500ms; | |
-moz-transition-delay: 500ms; | |
-webkit-transition-delay: 500ms; | |
*/ | |
} | |
.nvd3.nv-stackedarea path.nv-area.hover { | |
fill-opacity: .9; | |
/* | |
stroke-opacity: .85; | |
*/ | |
} | |
/* | |
.d3stackedarea .groups path { | |
stroke-opacity: 0; | |
} | |
*/ | |
.nvd3.nv-stackedarea .nv-groups .nv-point { | |
stroke-opacity: 0; | |
fill-opacity: 0; | |
} | |
/* | |
.nvd3.nv-stackedarea .nv-groups .nv-point.hover { | |
stroke-width: 20px; | |
stroke-opacity: .75; | |
fill-opacity: 1; | |
}*/ | |
/********** | |
* Line Plus Bar | |
*/ | |
.nvd3.nv-linePlusBar .nv-bar rect { | |
fill-opacity: .75; | |
} | |
.nvd3.nv-linePlusBar .nv-bar rect:hover { | |
fill-opacity: 1; | |
} | |
/********** | |
* Bullet | |
*/ | |
.nvd3.nv-bullet { font: 10px sans-serif; } | |
.nvd3.nv-bullet .nv-measure { fill-opacity: .8; } | |
.nvd3.nv-bullet .nv-measure:hover { fill-opacity: 1; } | |
.nvd3.nv-bullet .nv-marker { stroke: #000; stroke-width: 2px; } | |
.nvd3.nv-bullet .nv-markerTriangle { stroke: #000; fill: #fff; stroke-width: 1.5px; } | |
.nvd3.nv-bullet .nv-tick line { stroke: #666; stroke-width: .5px; } | |
.nvd3.nv-bullet .nv-range.nv-s0 { fill: #eee; } | |
.nvd3.nv-bullet .nv-range.nv-s1 { fill: #ddd; } | |
.nvd3.nv-bullet .nv-range.nv-s2 { fill: #ccc; } | |
.nvd3.nv-bullet .nv-title { font-size: 14px; font-weight: bold; } | |
.nvd3.nv-bullet .nv-subtitle { fill: #999; } | |
.nvd3.nv-bullet .nv-range { | |
fill: #bababa; | |
fill-opacity: .4; | |
} | |
.nvd3.nv-bullet .nv-range:hover { | |
fill-opacity: .7; | |
} | |
/********** | |
* Sparkline | |
*/ | |
.nvd3.nv-sparkline path { | |
fill: none; | |
} | |
.nvd3.nv-sparklineplus g.nv-hoverValue { | |
pointer-events: none; | |
} | |
.nvd3.nv-sparklineplus .nv-hoverValue line { | |
stroke: #333; | |
stroke-width: 1.5px; | |
} | |
.nvd3.nv-sparklineplus, | |
.nvd3.nv-sparklineplus g { | |
pointer-events: all; | |
} | |
.nvd3 .nv-hoverArea { | |
fill-opacity: 0; | |
stroke-opacity: 0; | |
} | |
.nvd3.nv-sparklineplus .nv-xValue, | |
.nvd3.nv-sparklineplus .nv-yValue { | |
/* | |
stroke: #666; | |
*/ | |
stroke-width: 0; | |
font-size: .9em; | |
font-weight: normal; | |
} | |
.nvd3.nv-sparklineplus .nv-yValue { | |
stroke: #f66; | |
} | |
.nvd3.nv-sparklineplus .nv-maxValue { | |
stroke: #2ca02c; | |
fill: #2ca02c; | |
} | |
.nvd3.nv-sparklineplus .nv-minValue { | |
stroke: #d62728; | |
fill: #d62728; | |
} | |
.nvd3.nv-sparklineplus .nv-currentValue { | |
/* | |
stroke: #444; | |
fill: #000; | |
*/ | |
font-weight: bold; | |
font-size: 1.1em; | |
} | |
/********** | |
* historical stock | |
*/ | |
.nvd3.nv-ohlcBar .nv-ticks .nv-tick { | |
stroke-width: 2px; | |
} | |
.nvd3.nv-ohlcBar .nv-ticks .nv-tick.hover { | |
stroke-width: 4px; | |
} | |
.nvd3.nv-ohlcBar .nv-ticks .nv-tick.positive { | |
stroke: #2ca02c; | |
} | |
.nvd3.nv-ohlcBar .nv-ticks .nv-tick.negative { | |
stroke: #d62728; | |
} | |
.nvd3.nv-historicalStockChart .nv-axis .nv-axislabel { | |
font-weight: bold; | |
} | |
.nvd3.nv-historicalStockChart .nv-dragTarget { | |
fill-opacity: 0; | |
stroke: none; | |
cursor: move; | |
} | |
.nvd3 .nv-brush .extent { | |
/* | |
cursor: ew-resize !important; | |
*/ | |
fill-opacity: 0 !important; | |
} | |
.nvd3 .nv-brushBackground rect { | |
stroke: #000; | |
stroke-width: .4; | |
fill: #fff; | |
fill-opacity: .7; | |
} | |
/********** | |
* Indented Tree | |
*/ | |
/** | |
* TODO: the following 3 selectors are based on classes used in the example. I should either make them standard and leave them here, or move to a CSS file not included in the library | |
*/ | |
.nvd3.nv-indentedtree .name { | |
margin-left: 5px; | |
} | |
.nvd3.nv-indentedtree .clickable { | |
color: #08C; | |
cursor: pointer; | |
} | |
.nvd3.nv-indentedtree span.clickable:hover { | |
color: #005580; | |
text-decoration: underline; | |
} | |
.nvd3.nv-indentedtree .nv-childrenCount { | |
display: inline-block; | |
margin-left: 5px; | |
} | |
.nvd3.nv-indentedtree .nv-treeicon { | |
cursor: pointer; | |
/* | |
cursor: n-resize; | |
*/ | |
} | |
.nvd3.nv-indentedtree .nv-treeicon.nv-folded { | |
cursor: pointer; | |
/* | |
cursor: s-resize; | |
*/ | |
} | |
/********** | |
* Parallel Coordinates | |
*/ | |
.nvd3 .background path { | |
fill: none; | |
stroke: #ccc; | |
stroke-opacity: .4; | |
shape-rendering: crispEdges; | |
} | |
.nvd3 .foreground path { | |
fill: none; | |
stroke: steelblue; | |
stroke-opacity: .7; | |
} | |
.nvd3 .brush .extent { | |
fill-opacity: .3; | |
stroke: #fff; | |
shape-rendering: crispEdges; | |
} | |
.nvd3 .axis line, .axis path { | |
fill: none; | |
stroke: #000; | |
shape-rendering: crispEdges; | |
} | |
.nvd3 .axis text { | |
text-shadow: 0 1px 0 #fff; | |
} | |
/**** | |
Interactive Layer | |
*/ | |
.nvd3 .nv-interactiveGuideLine { | |
pointer-events:none; | |
} | |
.nvd3 line.nv-guideline { | |
stroke: #ccc; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var nv = window.nv || {}; | |
nv.version = '1.1.15b'; | |
nv.dev = true //set false when in production | |
window.nv = nv; | |
nv.tooltip = nv.tooltip || {}; // For the tooltip system | |
nv.utils = nv.utils || {}; // Utility subsystem | |
nv.models = nv.models || {}; //stores all the possible models/components | |
nv.charts = {}; //stores all the ready to use charts | |
nv.graphs = []; //stores all the graphs currently on the page | |
nv.logs = {}; //stores some statistics and potential error messages | |
nv.dispatch = d3.dispatch('render_start', 'render_end'); | |
// ************************************************************************* | |
// Development render timers - disabled if dev = false | |
if (nv.dev) { | |
nv.dispatch.on('render_start', function(e) { | |
nv.logs.startTime = +new Date(); | |
}); | |
nv.dispatch.on('render_end', function(e) { | |
nv.logs.endTime = +new Date(); | |
nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime; | |
nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times | |
}); | |
} | |
// ******************************************** | |
// Public Core NV functions | |
// Logs all arguments, and returns the last so you can test things in place | |
// Note: in IE8 console.log is an object not a function, and if modernizr is used | |
// then calling Function.prototype.bind with with anything other than a function | |
// causes a TypeError to be thrown. | |
nv.log = function() { | |
if (nv.dev && console.log && console.log.apply) | |
console.log.apply(console, arguments) | |
else if (nv.dev && typeof console.log == "function" && Function.prototype.bind) { | |
var log = Function.prototype.bind.call(console.log, console); | |
log.apply(console, arguments); | |
} | |
return arguments[arguments.length - 1]; | |
}; | |
nv.render = function render(step) { | |
step = step || 1; // number of graphs to generate in each timeout loop | |
nv.render.active = true; | |
nv.dispatch.render_start(); | |
setTimeout(function() { | |
var chart, graph; | |
for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) { | |
chart = graph.generate(); | |
if (typeof graph.callback == typeof(Function)) graph.callback(chart); | |
nv.graphs.push(chart); | |
} | |
nv.render.queue.splice(0, i); | |
if (nv.render.queue.length) setTimeout(arguments.callee, 0); | |
else { | |
nv.dispatch.render_end(); | |
nv.render.active = false; | |
} | |
}, 0); | |
}; | |
nv.render.active = false; | |
nv.render.queue = []; | |
nv.addGraph = function(obj) { | |
if (typeof arguments[0] === typeof(Function)) | |
obj = {generate: arguments[0], callback: arguments[1]}; | |
nv.render.queue.push(obj); | |
if (!nv.render.active) nv.render(); | |
}; | |
nv.identity = function(d) { return d; }; | |
nv.strip = function(s) { return s.replace(/(\s|&)/g,''); }; | |
function daysInMonth(month,year) { | |
return (new Date(year, month+1, 0)).getDate(); | |
} | |
function d3_time_range(floor, step, number) { | |
return function(t0, t1, dt) { | |
var time = floor(t0), times = []; | |
if (time < t0) step(time); | |
if (dt > 1) { | |
while (time < t1) { | |
var date = new Date(+time); | |
if ((number(date) % dt === 0)) times.push(date); | |
step(time); | |
} | |
} else { | |
while (time < t1) { times.push(new Date(+time)); step(time); } | |
} | |
return times; | |
}; | |
} | |
d3.time.monthEnd = function(date) { | |
return new Date(date.getFullYear(), date.getMonth(), 0); | |
}; | |
d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) { | |
date.setUTCDate(date.getUTCDate() + 1); | |
date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear())); | |
}, function(date) { | |
return date.getMonth(); | |
} | |
); | |
/* Utility class to handle creation of an interactive layer. | |
This places a rectangle on top of the chart. When you mouse move over it, it sends a dispatch | |
containing the X-coordinate. It can also render a vertical line where the mouse is located. | |
dispatch.elementMousemove is the important event to latch onto. It is fired whenever the mouse moves over | |
the rectangle. The dispatch is given one object which contains the mouseX/Y location. | |
It also has 'pointXValue', which is the conversion of mouseX to the x-axis scale. | |
*/ | |
nv.interactiveGuideline = function() { | |
"use strict"; | |
var tooltip = nv.models.tooltip(); | |
//Public settings | |
var width = null | |
, height = null | |
//Please pass in the bounding chart's top and left margins | |
//This is important for calculating the correct mouseX/Y positions. | |
, margin = {left: 0, top: 0} | |
, xScale = d3.scale.linear() | |
, yScale = d3.scale.linear() | |
, dispatch = d3.dispatch('elementMousemove', 'elementMouseout','elementDblclick') | |
, showGuideLine = true | |
, svgContainer = null | |
//Must pass in the bounding chart's <svg> container. | |
//The mousemove event is attached to this container. | |
; | |
//Private variables | |
var isMSIE = navigator.userAgent.indexOf("MSIE") !== -1 //Check user-agent for Microsoft Internet Explorer. | |
; | |
function layer(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this); | |
var availableWidth = (width || 960), availableHeight = (height || 400); | |
var wrap = container.selectAll("g.nv-wrap.nv-interactiveLineLayer").data([data]); | |
var wrapEnter = wrap.enter() | |
.append("g").attr("class", " nv-wrap nv-interactiveLineLayer"); | |
wrapEnter.append("g").attr("class","nv-interactiveGuideLine"); | |
if (!svgContainer) { | |
return; | |
} | |
function mouseHandler() { | |
var d3mouse = d3.mouse(this); | |
var mouseX = d3mouse[0]; | |
var mouseY = d3mouse[1]; | |
var subtractMargin = true; | |
var mouseOutAnyReason = false; | |
if (isMSIE) { | |
/* | |
D3.js (or maybe SVG.getScreenCTM) has a nasty bug in Internet Explorer 10. | |
d3.mouse() returns incorrect X,Y mouse coordinates when mouse moving | |
over a rect in IE 10. | |
However, d3.event.offsetX/Y also returns the mouse coordinates | |
relative to the triggering <rect>. So we use offsetX/Y on IE. | |
*/ | |
mouseX = d3.event.offsetX; | |
mouseY = d3.event.offsetY; | |
/* | |
On IE, if you attach a mouse event listener to the <svg> container, | |
it will actually trigger it for all the child elements (like <path>, <circle>, etc). | |
When this happens on IE, the offsetX/Y is set to where ever the child element | |
is located. | |
As a result, we do NOT need to subtract margins to figure out the mouse X/Y | |
position under this scenario. Removing the line below *will* cause | |
the interactive layer to not work right on IE. | |
*/ | |
if(d3.event.target.tagName !== "svg") | |
subtractMargin = false; | |
if (d3.event.target.className.baseVal.match("nv-legend")) | |
mouseOutAnyReason = true; | |
} | |
if(subtractMargin) { | |
mouseX -= margin.left; | |
mouseY -= margin.top; | |
} | |
/* If mouseX/Y is outside of the chart's bounds, | |
trigger a mouseOut event. | |
*/ | |
if (mouseX < 0 || mouseY < 0 | |
|| mouseX > availableWidth || mouseY > availableHeight | |
|| (d3.event.relatedTarget && d3.event.relatedTarget.ownerSVGElement === undefined) | |
|| mouseOutAnyReason | |
) | |
{ | |
if (isMSIE) { | |
if (d3.event.relatedTarget | |
&& d3.event.relatedTarget.ownerSVGElement === undefined | |
&& d3.event.relatedTarget.className.match(tooltip.nvPointerEventsClass)) { | |
return; | |
} | |
} | |
dispatch.elementMouseout({ | |
mouseX: mouseX, | |
mouseY: mouseY | |
}); | |
layer.renderGuideLine(null); //hide the guideline | |
return; | |
} | |
var pointXValue = xScale.invert(mouseX); | |
dispatch.elementMousemove({ | |
mouseX: mouseX, | |
mouseY: mouseY, | |
pointXValue: pointXValue | |
}); | |
//If user double clicks the layer, fire a elementDblclick dispatch. | |
if (d3.event.type === "dblclick") { | |
dispatch.elementDblclick({ | |
mouseX: mouseX, | |
mouseY: mouseY, | |
pointXValue: pointXValue | |
}); | |
} | |
} | |
svgContainer | |
.on("mousemove",mouseHandler, true) | |
.on("mouseout" ,mouseHandler,true) | |
.on("dblclick" ,mouseHandler) | |
; | |
//Draws a vertical guideline at the given X postion. | |
layer.renderGuideLine = function(x) { | |
if (!showGuideLine) return; | |
var line = wrap.select(".nv-interactiveGuideLine") | |
.selectAll("line") | |
.data((x != null) ? [nv.utils.NaNtoZero(x)] : [], String); | |
line.enter() | |
.append("line") | |
.attr("class", "nv-guideline") | |
.attr("x1", function(d) { return d;}) | |
.attr("x2", function(d) { return d;}) | |
.attr("y1", availableHeight) | |
.attr("y2",0) | |
; | |
line.exit().remove(); | |
} | |
}); | |
} | |
layer.dispatch = dispatch; | |
layer.tooltip = tooltip; | |
layer.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return layer; | |
}; | |
layer.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return layer; | |
}; | |
layer.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return layer; | |
}; | |
layer.xScale = function(_) { | |
if (!arguments.length) return xScale; | |
xScale = _; | |
return layer; | |
}; | |
layer.showGuideLine = function(_) { | |
if (!arguments.length) return showGuideLine; | |
showGuideLine = _; | |
return layer; | |
}; | |
layer.svgContainer = function(_) { | |
if (!arguments.length) return svgContainer; | |
svgContainer = _; | |
return layer; | |
}; | |
return layer; | |
}; | |
/* Utility class that uses d3.bisect to find the index in a given array, where a search value can be inserted. | |
This is different from normal bisectLeft; this function finds the nearest index to insert the search value. | |
For instance, lets say your array is [1,2,3,5,10,30], and you search for 28. | |
Normal d3.bisectLeft will return 4, because 28 is inserted after the number 10. But interactiveBisect will return 5 | |
because 28 is closer to 30 than 10. | |
Unit tests can be found in: interactiveBisectTest.html | |
Has the following known issues: | |
* Will not work if the data points move backwards (ie, 10,9,8,7, etc) or if the data points are in random order. | |
* Won't work if there are duplicate x coordinate values. | |
*/ | |
nv.interactiveBisect = function (values, searchVal, xAccessor) { | |
"use strict"; | |
if (! values instanceof Array) return null; | |
if (typeof xAccessor !== 'function') xAccessor = function(d,i) { return d.x;} | |
var bisect = d3.bisector(xAccessor).left; | |
var index = d3.max([0, bisect(values,searchVal) - 1]); | |
var currentValue = xAccessor(values[index], index); | |
if (typeof currentValue === 'undefined') currentValue = index; | |
if (currentValue === searchVal) return index; //found exact match | |
var nextIndex = d3.min([index+1, values.length - 1]); | |
var nextValue = xAccessor(values[nextIndex], nextIndex); | |
if (typeof nextValue === 'undefined') nextValue = nextIndex; | |
if (Math.abs(nextValue - searchVal) >= Math.abs(currentValue - searchVal)) | |
return index; | |
else | |
return nextIndex | |
}; | |
/* | |
Returns the index in the array "values" that is closest to searchVal. | |
Only returns an index if searchVal is within some "threshold". | |
Otherwise, returns null. | |
*/ | |
nv.nearestValueIndex = function (values, searchVal, threshold) { | |
"use strict"; | |
var yDistMax = Infinity, indexToHighlight = null; | |
values.forEach(function(d,i) { | |
var delta = Math.abs(searchVal - d); | |
if ( delta <= yDistMax && delta < threshold) { | |
yDistMax = delta; | |
indexToHighlight = i; | |
} | |
}); | |
return indexToHighlight; | |
};/* Tooltip rendering model for nvd3 charts. | |
window.nv.models.tooltip is the updated,new way to render tooltips. | |
window.nv.tooltip.show is the old tooltip code. | |
window.nv.tooltip.* also has various helper methods. | |
*/ | |
(function() { | |
"use strict"; | |
window.nv.tooltip = {}; | |
/* Model which can be instantiated to handle tooltip rendering. | |
Example usage: | |
var tip = nv.models.tooltip().gravity('w').distance(23) | |
.data(myDataObject); | |
tip(); //just invoke the returned function to render tooltip. | |
*/ | |
window.nv.models.tooltip = function() { | |
var content = null //HTML contents of the tooltip. If null, the content is generated via the data variable. | |
, data = null /* Tooltip data. If data is given in the proper format, a consistent tooltip is generated. | |
Format of data: | |
{ | |
key: "Date", | |
value: "August 2009", | |
series: [ | |
{ | |
key: "Series 1", | |
value: "Value 1", | |
color: "#000" | |
}, | |
{ | |
key: "Series 2", | |
value: "Value 2", | |
color: "#00f" | |
} | |
] | |
} | |
*/ | |
, gravity = 'w' //Can be 'n','s','e','w'. Determines how tooltip is positioned. | |
, distance = 50 //Distance to offset tooltip from the mouse location. | |
, snapDistance = 25 //Tolerance allowed before tooltip is moved from its current position (creates 'snapping' effect) | |
, fixedTop = null //If not null, this fixes the top position of the tooltip. | |
, classes = null //Attaches additional CSS classes to the tooltip DIV that is created. | |
, chartContainer = null //Parent DIV, of the SVG Container that holds the chart. | |
, tooltipElem = null //actual DOM element representing the tooltip. | |
, position = {left: null, top: null} //Relative position of the tooltip inside chartContainer. | |
, enabled = true //True -> tooltips are rendered. False -> don't render tooltips. | |
//Generates a unique id when you create a new tooltip() object | |
, id = "nvtooltip-" + Math.floor(Math.random() * 100000) | |
; | |
//CSS class to specify whether element should not have mouse events. | |
var nvPointerEventsClass = "nv-pointer-events-none"; | |
//Format function for the tooltip values column | |
var valueFormatter = function(d,i) { | |
return d; | |
}; | |
//Format function for the tooltip header value. | |
var headerFormatter = function(d) { | |
return d; | |
}; | |
//By default, the tooltip model renders a beautiful table inside a DIV. | |
//You can override this function if a custom tooltip is desired. | |
var contentGenerator = function(d) { | |
if (content != null) return content; | |
if (d == null) return ''; | |
var table = d3.select(document.createElement("table")); | |
var theadEnter = table.selectAll("thead") | |
.data([d]) | |
.enter().append("thead"); | |
theadEnter.append("tr") | |
.append("td") | |
.attr("colspan",3) | |
.append("strong") | |
.classed("x-value",true) | |
.html(headerFormatter(d.value)); | |
var tbodyEnter = table.selectAll("tbody") | |
.data([d]) | |
.enter().append("tbody"); | |
var trowEnter = tbodyEnter.selectAll("tr") | |
.data(function(p) { return p.series}) | |
.enter() | |
.append("tr") | |
.classed("highlight", function(p) { return p.highlight}) | |
; | |
trowEnter.append("td") | |
.classed("legend-color-guide",true) | |
.append("div") | |
.style("background-color", function(p) { return p.color}); | |
trowEnter.append("td") | |
.classed("key",true) | |
.html(function(p) {return p.key}); | |
trowEnter.append("td") | |
.classed("value",true) | |
.html(function(p,i) { return valueFormatter(p.value,i) }); | |
trowEnter.selectAll("td").each(function(p) { | |
if (p.highlight) { | |
var opacityScale = d3.scale.linear().domain([0,1]).range(["#fff",p.color]); | |
var opacity = 0.6; | |
d3.select(this) | |
.style("border-bottom-color", opacityScale(opacity)) | |
.style("border-top-color", opacityScale(opacity)) | |
; | |
} | |
}); | |
var html = table.node().outerHTML; | |
if (d.footer !== undefined) | |
html += "<div class='footer'>" + d.footer + "</div>"; | |
return html; | |
}; | |
var dataSeriesExists = function(d) { | |
if (d && d.series && d.series.length > 0) return true; | |
return false; | |
}; | |
//In situations where the chart is in a 'viewBox', re-position the tooltip based on how far chart is zoomed. | |
function convertViewBoxRatio() { | |
if (chartContainer) { | |
var svg = d3.select(chartContainer); | |
if (svg.node().tagName !== "svg") { | |
svg = svg.select("svg"); | |
} | |
var viewBox = (svg.node()) ? svg.attr('viewBox') : null; | |
if (viewBox) { | |
viewBox = viewBox.split(' '); | |
var ratio = parseInt(svg.style('width')) / viewBox[2]; | |
position.left = position.left * ratio; | |
position.top = position.top * ratio; | |
} | |
} | |
} | |
//Creates new tooltip container, or uses existing one on DOM. | |
function getTooltipContainer(newContent) { | |
var body; | |
if (chartContainer) | |
body = d3.select(chartContainer); | |
else | |
body = d3.select("body"); | |
var container = body.select(".nvtooltip"); | |
if (container.node() === null) { | |
//Create new tooltip div if it doesn't exist on DOM. | |
container = body.append("div") | |
.attr("class", "nvtooltip " + (classes? classes: "xy-tooltip")) | |
.attr("id",id) | |
; | |
} | |
container.node().innerHTML = newContent; | |
container.style("top",0).style("left",0).style("opacity",0); | |
container.selectAll("div, table, td, tr").classed(nvPointerEventsClass,true) | |
container.classed(nvPointerEventsClass,true); | |
return container.node(); | |
} | |
//Draw the tooltip onto the DOM. | |
function nvtooltip() { | |
if (!enabled) return; | |
if (!dataSeriesExists(data)) return; | |
convertViewBoxRatio(); | |
var left = position.left; | |
var top = (fixedTop != null) ? fixedTop : position.top; | |
var container = getTooltipContainer(contentGenerator(data)); | |
tooltipElem = container; | |
if (chartContainer) { | |
var svgComp = chartContainer.getElementsByTagName("svg")[0]; | |
var boundRect = (svgComp) ? svgComp.getBoundingClientRect() : chartContainer.getBoundingClientRect(); | |
var svgOffset = {left:0,top:0}; | |
if (svgComp) { | |
var svgBound = svgComp.getBoundingClientRect(); | |
var chartBound = chartContainer.getBoundingClientRect(); | |
var svgBoundTop = svgBound.top; | |
//Defensive code. Sometimes, svgBoundTop can be a really negative | |
// number, like -134254. That's a bug. | |
// If such a number is found, use zero instead. FireFox bug only | |
if (svgBoundTop < 0) { | |
var containerBound = chartContainer.getBoundingClientRect(); | |
svgBoundTop = (Math.abs(svgBoundTop) > containerBound.height) ? 0 : svgBoundTop; | |
} | |
svgOffset.top = Math.abs(svgBoundTop - chartBound.top); | |
svgOffset.left = Math.abs(svgBound.left - chartBound.left); | |
} | |
//If the parent container is an overflow <div> with scrollbars, subtract the scroll offsets. | |
//You need to also add any offset between the <svg> element and its containing <div> | |
//Finally, add any offset of the containing <div> on the whole page. | |
left += chartContainer.offsetLeft + svgOffset.left - 2*chartContainer.scrollLeft; | |
top += chartContainer.offsetTop + svgOffset.top - 2*chartContainer.scrollTop; | |
} | |
if (snapDistance && snapDistance > 0) { | |
top = Math.floor(top/snapDistance) * snapDistance; | |
} | |
nv.tooltip.calcTooltipPosition([left,top], gravity, distance, container); | |
return nvtooltip; | |
}; | |
nvtooltip.nvPointerEventsClass = nvPointerEventsClass; | |
nvtooltip.content = function(_) { | |
if (!arguments.length) return content; | |
content = _; | |
return nvtooltip; | |
}; | |
//Returns tooltipElem...not able to set it. | |
nvtooltip.tooltipElem = function() { | |
return tooltipElem; | |
}; | |
nvtooltip.contentGenerator = function(_) { | |
if (!arguments.length) return contentGenerator; | |
if (typeof _ === 'function') { | |
contentGenerator = _; | |
} | |
return nvtooltip; | |
}; | |
nvtooltip.data = function(_) { | |
if (!arguments.length) return data; | |
data = _; | |
return nvtooltip; | |
}; | |
nvtooltip.gravity = function(_) { | |
if (!arguments.length) return gravity; | |
gravity = _; | |
return nvtooltip; | |
}; | |
nvtooltip.distance = function(_) { | |
if (!arguments.length) return distance; | |
distance = _; | |
return nvtooltip; | |
}; | |
nvtooltip.snapDistance = function(_) { | |
if (!arguments.length) return snapDistance; | |
snapDistance = _; | |
return nvtooltip; | |
}; | |
nvtooltip.classes = function(_) { | |
if (!arguments.length) return classes; | |
classes = _; | |
return nvtooltip; | |
}; | |
nvtooltip.chartContainer = function(_) { | |
if (!arguments.length) return chartContainer; | |
chartContainer = _; | |
return nvtooltip; | |
}; | |
nvtooltip.position = function(_) { | |
if (!arguments.length) return position; | |
position.left = (typeof _.left !== 'undefined') ? _.left : position.left; | |
position.top = (typeof _.top !== 'undefined') ? _.top : position.top; | |
return nvtooltip; | |
}; | |
nvtooltip.fixedTop = function(_) { | |
if (!arguments.length) return fixedTop; | |
fixedTop = _; | |
return nvtooltip; | |
}; | |
nvtooltip.enabled = function(_) { | |
if (!arguments.length) return enabled; | |
enabled = _; | |
return nvtooltip; | |
}; | |
nvtooltip.valueFormatter = function(_) { | |
if (!arguments.length) return valueFormatter; | |
if (typeof _ === 'function') { | |
valueFormatter = _; | |
} | |
return nvtooltip; | |
}; | |
nvtooltip.headerFormatter = function(_) { | |
if (!arguments.length) return headerFormatter; | |
if (typeof _ === 'function') { | |
headerFormatter = _; | |
} | |
return nvtooltip; | |
}; | |
//id() is a read-only function. You can't use it to set the id. | |
nvtooltip.id = function() { | |
return id; | |
}; | |
return nvtooltip; | |
}; | |
//Original tooltip.show function. Kept for backward compatibility. | |
// pos = [left,top] | |
nv.tooltip.show = function(pos, content, gravity, dist, parentContainer, classes) { | |
//Create new tooltip div if it doesn't exist on DOM. | |
var container = document.createElement('div'); | |
container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip'); | |
var body = parentContainer; | |
if ( !parentContainer || parentContainer.tagName.match(/g|svg/i)) { | |
//If the parent element is an SVG element, place tooltip in the <body> element. | |
body = document.getElementsByTagName('body')[0]; | |
} | |
container.style.left = 0; | |
container.style.top = 0; | |
container.style.opacity = 0; | |
container.innerHTML = content; | |
body.appendChild(container); | |
//If the parent container is an overflow <div> with scrollbars, subtract the scroll offsets. | |
if (parentContainer) { | |
pos[0] = pos[0] - parentContainer.scrollLeft; | |
pos[1] = pos[1] - parentContainer.scrollTop; | |
} | |
nv.tooltip.calcTooltipPosition(pos, gravity, dist, container); | |
}; | |
//Looks up the ancestry of a DOM element, and returns the first NON-svg node. | |
nv.tooltip.findFirstNonSVGParent = function(Elem) { | |
while(Elem.tagName.match(/^g|svg$/i) !== null) { | |
Elem = Elem.parentNode; | |
} | |
return Elem; | |
}; | |
//Finds the total offsetTop of a given DOM element. | |
//Looks up the entire ancestry of an element, up to the first relatively positioned element. | |
nv.tooltip.findTotalOffsetTop = function ( Elem, initialTop ) { | |
var offsetTop = initialTop; | |
do { | |
if( !isNaN( Elem.offsetTop ) ) { | |
offsetTop += (Elem.offsetTop); | |
} | |
} while( Elem = Elem.offsetParent ); | |
return offsetTop; | |
}; | |
//Finds the total offsetLeft of a given DOM element. | |
//Looks up the entire ancestry of an element, up to the first relatively positioned element. | |
nv.tooltip.findTotalOffsetLeft = function ( Elem, initialLeft) { | |
var offsetLeft = initialLeft; | |
do { | |
if( !isNaN( Elem.offsetLeft ) ) { | |
offsetLeft += (Elem.offsetLeft); | |
} | |
} while( Elem = Elem.offsetParent ); | |
return offsetLeft; | |
}; | |
//Global utility function to render a tooltip on the DOM. | |
//pos = [left,top] coordinates of where to place the tooltip, relative to the SVG chart container. | |
//gravity = how to orient the tooltip | |
//dist = how far away from the mouse to place tooltip | |
//container = tooltip DIV | |
nv.tooltip.calcTooltipPosition = function(pos, gravity, dist, container) { | |
var height = parseInt(container.offsetHeight), | |
width = parseInt(container.offsetWidth), | |
windowWidth = nv.utils.windowSize().width, | |
windowHeight = nv.utils.windowSize().height, | |
scrollTop = window.pageYOffset, | |
scrollLeft = window.pageXOffset, | |
left, top; | |
windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16; | |
windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16; | |
gravity = gravity || 's'; | |
dist = dist || 20; | |
var tooltipTop = function ( Elem ) { | |
return nv.tooltip.findTotalOffsetTop(Elem, top); | |
}; | |
var tooltipLeft = function ( Elem ) { | |
return nv.tooltip.findTotalOffsetLeft(Elem,left); | |
}; | |
switch (gravity) { | |
case 'e': | |
left = pos[0] - width - dist; | |
top = pos[1] - (height / 2); | |
var tLeft = tooltipLeft(container); | |
var tTop = tooltipTop(container); | |
if (tLeft < scrollLeft) left = pos[0] + dist > scrollLeft ? pos[0] + dist : scrollLeft - tLeft + left; | |
if (tTop < scrollTop) top = scrollTop - tTop + top; | |
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height; | |
break; | |
case 'w': | |
left = pos[0] + dist; | |
top = pos[1] - (height / 2); | |
var tLeft = tooltipLeft(container); | |
var tTop = tooltipTop(container); | |
if (tLeft + width > windowWidth) left = pos[0] - width - dist; | |
if (tTop < scrollTop) top = scrollTop + 5; | |
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height; | |
break; | |
case 'n': | |
left = pos[0] - (width / 2) - 5; | |
top = pos[1] + dist; | |
var tLeft = tooltipLeft(container); | |
var tTop = tooltipTop(container); | |
if (tLeft < scrollLeft) left = scrollLeft + 5; | |
if (tLeft + width > windowWidth) left = left - width/2 + 5; | |
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height; | |
break; | |
case 's': | |
left = pos[0] - (width / 2); | |
top = pos[1] - height - dist; | |
var tLeft = tooltipLeft(container); | |
var tTop = tooltipTop(container); | |
if (tLeft < scrollLeft) left = scrollLeft + 5; | |
if (tLeft + width > windowWidth) left = left - width/2 + 5; | |
if (scrollTop > tTop) top = scrollTop; | |
break; | |
case 'none': | |
left = pos[0]; | |
top = pos[1] - dist; | |
var tLeft = tooltipLeft(container); | |
var tTop = tooltipTop(container); | |
break; | |
} | |
container.style.left = left+'px'; | |
container.style.top = top+'px'; | |
container.style.opacity = 1; | |
container.style.position = 'absolute'; | |
return container; | |
}; | |
//Global utility function to remove tooltips from the DOM. | |
nv.tooltip.cleanup = function() { | |
// Find the tooltips, mark them for removal by this class (so others cleanups won't find it) | |
var tooltips = document.getElementsByClassName('nvtooltip'); | |
var purging = []; | |
while(tooltips.length) { | |
purging.push(tooltips[0]); | |
tooltips[0].style.transitionDelay = '0 !important'; | |
tooltips[0].style.opacity = 0; | |
tooltips[0].className = 'nvtooltip-pending-removal'; | |
} | |
setTimeout(function() { | |
while (purging.length) { | |
var removeMe = purging.pop(); | |
removeMe.parentNode.removeChild(removeMe); | |
} | |
}, 500); | |
}; | |
})(); | |
nv.utils.windowSize = function() { | |
// Sane defaults | |
var size = {width: 640, height: 480}; | |
// Earlier IE uses Doc.body | |
if (document.body && document.body.offsetWidth) { | |
size.width = document.body.offsetWidth; | |
size.height = document.body.offsetHeight; | |
} | |
// IE can use depending on mode it is in | |
if (document.compatMode=='CSS1Compat' && | |
document.documentElement && | |
document.documentElement.offsetWidth ) { | |
size.width = document.documentElement.offsetWidth; | |
size.height = document.documentElement.offsetHeight; | |
} | |
// Most recent browsers use | |
if (window.innerWidth && window.innerHeight) { | |
size.width = window.innerWidth; | |
size.height = window.innerHeight; | |
} | |
return (size); | |
}; | |
// Easy way to bind multiple functions to window.onresize | |
// TODO: give a way to remove a function after its bound, other than removing all of them | |
nv.utils.windowResize = function(fun){ | |
if (fun === undefined) return; | |
var oldresize = window.onresize; | |
window.onresize = function(e) { | |
if (typeof oldresize == 'function') oldresize(e); | |
fun(e); | |
} | |
} | |
// Backwards compatible way to implement more d3-like coloring of graphs. | |
// If passed an array, wrap it in a function which implements the old default | |
// behavior | |
nv.utils.getColor = function(color) { | |
if (!arguments.length) return nv.utils.defaultColor(); //if you pass in nothing, get default colors back | |
if( Object.prototype.toString.call( color ) === '[object Array]' ) | |
return function(d, i) { return d.color || color[i % color.length]; }; | |
else | |
return color; | |
//can't really help it if someone passes rubbish as color | |
} | |
// Default color chooser uses the index of an object as before. | |
nv.utils.defaultColor = function() { | |
var colors = d3.scale.category20().range(); | |
return function(d, i) { return d.color || colors[i % colors.length] }; | |
} | |
// Returns a color function that takes the result of 'getKey' for each series and | |
// looks for a corresponding color from the dictionary, | |
nv.utils.customTheme = function(dictionary, getKey, defaultColors) { | |
getKey = getKey || function(series) { return series.key }; // use default series.key if getKey is undefined | |
defaultColors = defaultColors || d3.scale.category20().range(); //default color function | |
var defIndex = defaultColors.length; //current default color (going in reverse) | |
return function(series, index) { | |
var key = getKey(series); | |
if (!defIndex) defIndex = defaultColors.length; //used all the default colors, start over | |
if (typeof dictionary[key] !== "undefined") | |
return (typeof dictionary[key] === "function") ? dictionary[key]() : dictionary[key]; | |
else | |
return defaultColors[--defIndex]; // no match in dictionary, use default color | |
} | |
} | |
// From the PJAX example on d3js.org, while this is not really directly needed | |
// it's a very cool method for doing pjax, I may expand upon it a little bit, | |
// open to suggestions on anything that may be useful | |
nv.utils.pjax = function(links, content) { | |
d3.selectAll(links).on("click", function() { | |
history.pushState(this.href, this.textContent, this.href); | |
load(this.href); | |
d3.event.preventDefault(); | |
}); | |
function load(href) { | |
d3.html(href, function(fragment) { | |
var target = d3.select(content).node(); | |
target.parentNode.replaceChild(d3.select(fragment).select(content).node(), target); | |
nv.utils.pjax(links, content); | |
}); | |
} | |
d3.select(window).on("popstate", function() { | |
if (d3.event.state) load(d3.event.state); | |
}); | |
} | |
/* For situations where we want to approximate the width in pixels for an SVG:text element. | |
Most common instance is when the element is in a display:none; container. | |
Forumla is : text.length * font-size * constant_factor | |
*/ | |
nv.utils.calcApproxTextWidth = function (svgTextElem) { | |
if (typeof svgTextElem.style === 'function' | |
&& typeof svgTextElem.text === 'function') { | |
var fontSize = parseInt(svgTextElem.style("font-size").replace("px","")); | |
var textLength = svgTextElem.text().length; | |
return textLength * fontSize * 0.5; | |
} | |
return 0; | |
}; | |
/* Numbers that are undefined, null or NaN, convert them to zeros. | |
*/ | |
nv.utils.NaNtoZero = function(n) { | |
if (typeof n !== 'number' | |
|| isNaN(n) | |
|| n === null | |
|| n === Infinity) return 0; | |
return n; | |
}; | |
/* | |
Snippet of code you can insert into each nv.models.* to give you the ability to | |
do things like: | |
chart.options({ | |
showXAxis: true, | |
tooltips: true | |
}); | |
To enable in the chart: | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
*/ | |
nv.utils.optionsFunc = function(args) { | |
if (args) { | |
d3.map(args).forEach((function(key,value) { | |
if (typeof this[key] === "function") { | |
this[key](value); | |
} | |
}).bind(this)); | |
} | |
return this; | |
};nv.models.axis = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var axis = d3.svg.axis() | |
; | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 75 //only used for tickLabel currently | |
, height = 60 //only used for tickLabel currently | |
, scale = d3.scale.linear() | |
, axisLabelText = null | |
, showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes | |
, highlightZero = true | |
, rotateLabels = 0 | |
, rotateYLabel = true | |
, staggerLabels = false | |
, isOrdinal = false | |
, ticks = null | |
, axisLabelDistance = 12 //The larger this number is, the closer the axis label is to the axis. | |
; | |
axis | |
.scale(scale) | |
.orient('bottom') | |
.tickFormat(function(d) { return d }) | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var scale0; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g') | |
//------------------------------------------------------------ | |
if (ticks !== null) | |
axis.ticks(ticks); | |
else if (axis.orient() == 'top' || axis.orient() == 'bottom') | |
axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100); | |
//TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component | |
g.transition().call(axis); | |
scale0 = scale0 || axis.scale(); | |
var fmt = axis.tickFormat(); | |
if (fmt == null) { | |
fmt = scale0.tickFormat(); | |
} | |
var axisLabel = g.selectAll('text.nv-axislabel') | |
.data([axisLabelText || null]); | |
axisLabel.exit().remove(); | |
switch (axis.orient()) { | |
case 'top': | |
axisLabel.enter().append('text').attr('class', 'nv-axislabel'); | |
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0])); | |
axisLabel | |
.attr('text-anchor', 'middle') | |
.attr('y', 0) | |
.attr('x', w/2); | |
if (showMaxMin) { | |
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') | |
.data(scale.domain()); | |
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text'); | |
axisMaxMin.exit().remove(); | |
axisMaxMin | |
.attr('transform', function(d,i) { | |
return 'translate(' + scale(d) + ',0)' | |
}) | |
.select('text') | |
.attr('dy', '-0.5em') | |
.attr('y', -axis.tickPadding()) | |
.attr('text-anchor', 'middle') | |
.text(function(d,i) { | |
var v = fmt(d); | |
return ('' + v).match('NaN') ? '' : v; | |
}); | |
axisMaxMin.transition() | |
.attr('transform', function(d,i) { | |
return 'translate(' + scale.range()[i] + ',0)' | |
}); | |
} | |
break; | |
case 'bottom': | |
var xLabelMargin = 36; | |
var maxTextWidth = 30; | |
var xTicks = g.selectAll('g').select("text"); | |
if (rotateLabels%360) { | |
//Calculate the longest xTick width | |
xTicks.each(function(d,i){ | |
var width = this.getBBox().width; | |
if(width > maxTextWidth) maxTextWidth = width; | |
}); | |
//Convert to radians before calculating sin. Add 30 to margin for healthy padding. | |
var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180)); | |
var xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30; | |
//Rotate all xTicks | |
xTicks | |
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' }) | |
.style('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end'); | |
} | |
axisLabel.enter().append('text').attr('class', 'nv-axislabel'); | |
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0])); | |
axisLabel | |
.attr('text-anchor', 'middle') | |
.attr('y', xLabelMargin) | |
.attr('x', w/2); | |
if (showMaxMin) { | |
//if (showMaxMin && !isOrdinal) { | |
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') | |
//.data(scale.domain()) | |
.data([scale.domain()[0], scale.domain()[scale.domain().length - 1]]); | |
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text'); | |
axisMaxMin.exit().remove(); | |
axisMaxMin | |
.attr('transform', function(d,i) { | |
return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)' | |
}) | |
.select('text') | |
.attr('dy', '.71em') | |
.attr('y', axis.tickPadding()) | |
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' }) | |
.style('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle') | |
.text(function(d,i) { | |
var v = fmt(d); | |
return ('' + v).match('NaN') ? '' : v; | |
}); | |
axisMaxMin.transition() | |
.attr('transform', function(d,i) { | |
//return 'translate(' + scale.range()[i] + ',0)' | |
//return 'translate(' + scale(d) + ',0)' | |
return 'translate(' + (scale(d) + (isOrdinal ? scale.rangeBand() / 2 : 0)) + ',0)' | |
}); | |
} | |
if (staggerLabels) | |
xTicks | |
.attr('transform', function(d,i) { return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')' }); | |
break; | |
case 'right': | |
axisLabel.enter().append('text').attr('class', 'nv-axislabel'); | |
axisLabel | |
.style('text-anchor', rotateYLabel ? 'middle' : 'begin') | |
.attr('transform', rotateYLabel ? 'rotate(90)' : '') | |
.attr('y', rotateYLabel ? (-Math.max(margin.right,width) + 12) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart | |
.attr('x', rotateYLabel ? (scale.range()[0] / 2) : axis.tickPadding()); | |
if (showMaxMin) { | |
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') | |
.data(scale.domain()); | |
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text') | |
.style('opacity', 0); | |
axisMaxMin.exit().remove(); | |
axisMaxMin | |
.attr('transform', function(d,i) { | |
return 'translate(0,' + scale(d) + ')' | |
}) | |
.select('text') | |
.attr('dy', '.32em') | |
.attr('y', 0) | |
.attr('x', axis.tickPadding()) | |
.style('text-anchor', 'start') | |
.text(function(d,i) { | |
var v = fmt(d); | |
return ('' + v).match('NaN') ? '' : v; | |
}); | |
axisMaxMin.transition() | |
.attr('transform', function(d,i) { | |
return 'translate(0,' + scale.range()[i] + ')' | |
}) | |
.select('text') | |
.style('opacity', 1); | |
} | |
break; | |
case 'left': | |
/* | |
//For dynamically placing the label. Can be used with dynamically-sized chart axis margins | |
var yTicks = g.selectAll('g').select("text"); | |
yTicks.each(function(d,i){ | |
var labelPadding = this.getBBox().width + axis.tickPadding() + 16; | |
if(labelPadding > width) width = labelPadding; | |
}); | |
*/ | |
axisLabel.enter().append('text').attr('class', 'nv-axislabel'); | |
axisLabel | |
.style('text-anchor', rotateYLabel ? 'middle' : 'end') | |
.attr('transform', rotateYLabel ? 'rotate(-90)' : '') | |
.attr('y', rotateYLabel ? (-Math.max(margin.left,width) + axisLabelDistance) : -10) //TODO: consider calculating this based on largest tick width... OR at least expose this on chart | |
.attr('x', rotateYLabel ? (-scale.range()[0] / 2) : -axis.tickPadding()); | |
if (showMaxMin) { | |
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin') | |
.data(scale.domain()); | |
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text') | |
.style('opacity', 0); | |
axisMaxMin.exit().remove(); | |
axisMaxMin | |
.attr('transform', function(d,i) { | |
return 'translate(0,' + scale0(d) + ')' | |
}) | |
.select('text') | |
.attr('dy', '.32em') | |
.attr('y', 0) | |
.attr('x', -axis.tickPadding()) | |
.attr('text-anchor', 'end') | |
.text(function(d,i) { | |
var v = fmt(d); | |
return ('' + v).match('NaN') ? '' : v; | |
}); | |
axisMaxMin.transition() | |
.attr('transform', function(d,i) { | |
return 'translate(0,' + scale.range()[i] + ')' | |
}) | |
.select('text') | |
.style('opacity', 1); | |
} | |
break; | |
} | |
axisLabel | |
.text(function(d) { return d }); | |
if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) { | |
//check if max and min overlap other values, if so, hide the values that overlap | |
g.selectAll('g') // the g's wrapping each tick | |
.each(function(d,i) { | |
d3.select(this).select('text').attr('opacity', 1); | |
if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it! | |
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL | |
d3.select(this).attr('opacity', 0); | |
d3.select(this).select('text').attr('opacity', 0); // Don't remove the ZERO line!! | |
} | |
}); | |
//if Max and Min = 0 only show min, Issue #281 | |
if (scale.domain()[0] == scale.domain()[1] && scale.domain()[0] == 0) | |
wrap.selectAll('g.nv-axisMaxMin') | |
.style('opacity', function(d,i) { return !i ? 1 : 0 }); | |
} | |
if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) { | |
var maxMinRange = []; | |
wrap.selectAll('g.nv-axisMaxMin') | |
.each(function(d,i) { | |
try { | |
if (i) // i== 1, max position | |
maxMinRange.push(scale(d) - this.getBBox().width - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case) | |
else // i==0, min position | |
maxMinRange.push(scale(d) + this.getBBox().width + 4) | |
}catch (err) { | |
if (i) // i== 1, max position | |
maxMinRange.push(scale(d) - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case) | |
else // i==0, min position | |
maxMinRange.push(scale(d) + 4) | |
} | |
}); | |
g.selectAll('g') // the g's wrapping each tick | |
.each(function(d,i) { | |
if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) { | |
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL | |
d3.select(this).remove(); | |
else | |
d3.select(this).select('text').remove(); // Don't remove the ZERO line!! | |
} | |
}); | |
} | |
//highlight zero line ... Maybe should not be an option and should just be in CSS? | |
if (highlightZero) | |
g.selectAll('.tick') | |
.filter(function(d) { return !parseFloat(Math.round(d.__data__*100000)/1000000) && (d.__data__ !== undefined) }) //this is because sometimes the 0 tick is a very small fraction, TODO: think of cleaner technique | |
.classed('zero', true); | |
//store old scales for use in transitions on update | |
scale0 = scale.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.axis = axis; | |
d3.rebind(chart, axis, 'orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat'); | |
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); //these are also accessible by chart.scale(), but added common ones directly for ease of use | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if(!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
} | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.ticks = function(_) { | |
if (!arguments.length) return ticks; | |
ticks = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.axisLabel = function(_) { | |
if (!arguments.length) return axisLabelText; | |
axisLabelText = _; | |
return chart; | |
} | |
chart.showMaxMin = function(_) { | |
if (!arguments.length) return showMaxMin; | |
showMaxMin = _; | |
return chart; | |
} | |
chart.highlightZero = function(_) { | |
if (!arguments.length) return highlightZero; | |
highlightZero = _; | |
return chart; | |
} | |
chart.scale = function(_) { | |
if (!arguments.length) return scale; | |
scale = _; | |
axis.scale(scale); | |
isOrdinal = typeof scale.rangeBands === 'function'; | |
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); | |
return chart; | |
} | |
chart.rotateYLabel = function(_) { | |
if(!arguments.length) return rotateYLabel; | |
rotateYLabel = _; | |
return chart; | |
} | |
chart.rotateLabels = function(_) { | |
if(!arguments.length) return rotateLabels; | |
rotateLabels = _; | |
return chart; | |
} | |
chart.staggerLabels = function(_) { | |
if (!arguments.length) return staggerLabels; | |
staggerLabels = _; | |
return chart; | |
}; | |
chart.axisLabelDistance = function(_) { | |
if (!arguments.length) return axisLabelDistance; | |
axisLabelDistance = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
//TODO: consider deprecating and using multibar with single series for this | |
nv.models.historicalBar = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one | |
, x = d3.scale.linear() | |
, y = d3.scale.linear() | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, forceX = [] | |
, forceY = [0] | |
, padData = false | |
, clipEdge = true | |
, color = nv.utils.defaultColor() | |
, xDomain | |
, yDomain | |
, xRange | |
, yRange | |
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') | |
, interactive = true | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup Scales | |
x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) )) | |
if (padData) | |
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); | |
else | |
x.range(xRange || [0, availableWidth]); | |
y .domain(yDomain || d3.extent(data[0].values.map(getY).concat(forceY) )) | |
.range(yRange || [availableHeight, 0]); | |
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point | |
if (x.domain()[0] === x.domain()[1]) | |
x.domain()[0] ? | |
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) | |
: x.domain([-1,1]); | |
if (y.domain()[0] === y.domain()[1]) | |
y.domain()[0] ? | |
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) | |
: y.domain([-1,1]); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-historicalBar-' + id).data([data[0].values]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBar-' + id); | |
var defsEnter = wrapEnter.append('defs'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-bars'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
container | |
.on('click', function(d,i) { | |
dispatch.chartClick({ | |
data: d, | |
index: i, | |
pos: d3.event, | |
id: id | |
}); | |
}); | |
defsEnter.append('clipPath') | |
.attr('id', 'nv-chart-clip-path-' + id) | |
.append('rect'); | |
wrap.select('#nv-chart-clip-path-' + id + ' rect') | |
.attr('width', availableWidth) | |
.attr('height', availableHeight); | |
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : ''); | |
var bars = wrap.select('.nv-bars').selectAll('.nv-bar') | |
.data(function(d) { return d }, function(d,i) {return getX(d,i)}); | |
bars.exit().remove(); | |
var barsEnter = bars.enter().append('rect') | |
//.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i }) | |
.attr('x', 0 ) | |
.attr('y', function(d,i) { return nv.utils.NaNtoZero(y(Math.max(0, getY(d,i)))) }) | |
.attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.abs(y(getY(d,i)) - y(0))) }) | |
.attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; }) | |
.on('mouseover', function(d,i) { | |
if (!interactive) return; | |
d3.select(this).classed('hover', true); | |
dispatch.elementMouseover({ | |
point: d, | |
series: data[0], | |
pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: 0, | |
e: d3.event | |
}); | |
}) | |
.on('mouseout', function(d,i) { | |
if (!interactive) return; | |
d3.select(this).classed('hover', false); | |
dispatch.elementMouseout({ | |
point: d, | |
series: data[0], | |
pointIndex: i, | |
seriesIndex: 0, | |
e: d3.event | |
}); | |
}) | |
.on('click', function(d,i) { | |
if (!interactive) return; | |
dispatch.elementClick({ | |
//label: d[label], | |
value: getY(d,i), | |
data: d, | |
index: i, | |
pos: [x(getX(d,i)), y(getY(d,i))], | |
e: d3.event, | |
id: id | |
}); | |
d3.event.stopPropagation(); | |
}) | |
.on('dblclick', function(d,i) { | |
if (!interactive) return; | |
dispatch.elementDblClick({ | |
//label: d[label], | |
value: getY(d,i), | |
data: d, | |
index: i, | |
pos: [x(getX(d,i)), y(getY(d,i))], | |
e: d3.event, | |
id: id | |
}); | |
d3.event.stopPropagation(); | |
}); | |
bars | |
.attr('fill', function(d,i) { return color(d, i); }) | |
.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i }) | |
.transition() | |
.attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - availableWidth / data[0].values.length * .45) + ',0)'; }) | |
//TODO: better width calculations that don't assume always uniform data spacing;w | |
.attr('width', (availableWidth / data[0].values.length) * .9 ); | |
bars.transition() | |
.attr('y', function(d,i) { | |
var rval = getY(d,i) < 0 ? | |
y(0) : | |
y(0) - y(getY(d,i)) < 1 ? | |
y(0) - 1 : | |
y(getY(d,i)); | |
return nv.utils.NaNtoZero(rval); | |
}) | |
.attr('height', function(d,i) { return nv.utils.NaNtoZero(Math.max(Math.abs(y(getY(d,i)) - y(0)),1)) }); | |
}); | |
return chart; | |
} | |
//Create methods to allow outside functions to highlight a specific bar. | |
chart.highlightPoint = function(pointIndex, isHoverOver) { | |
d3.select(".nv-historicalBar-" + id) | |
.select(".nv-bars .nv-bar-0-" + pointIndex) | |
.classed("hover", isHoverOver) | |
; | |
}; | |
chart.clearHighlights = function() { | |
d3.select(".nv-historicalBar-" + id) | |
.select(".nv-bars .nv-bar.hover") | |
.classed("hover", false) | |
; | |
}; | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.xScale = function(_) { | |
if (!arguments.length) return x; | |
x = _; | |
return chart; | |
}; | |
chart.yScale = function(_) { | |
if (!arguments.length) return y; | |
y = _; | |
return chart; | |
}; | |
chart.xDomain = function(_) { | |
if (!arguments.length) return xDomain; | |
xDomain = _; | |
return chart; | |
}; | |
chart.yDomain = function(_) { | |
if (!arguments.length) return yDomain; | |
yDomain = _; | |
return chart; | |
}; | |
chart.xRange = function(_) { | |
if (!arguments.length) return xRange; | |
xRange = _; | |
return chart; | |
}; | |
chart.yRange = function(_) { | |
if (!arguments.length) return yRange; | |
yRange = _; | |
return chart; | |
}; | |
chart.forceX = function(_) { | |
if (!arguments.length) return forceX; | |
forceX = _; | |
return chart; | |
}; | |
chart.forceY = function(_) { | |
if (!arguments.length) return forceY; | |
forceY = _; | |
return chart; | |
}; | |
chart.padData = function(_) { | |
if (!arguments.length) return padData; | |
padData = _; | |
return chart; | |
}; | |
chart.clipEdge = function(_) { | |
if (!arguments.length) return clipEdge; | |
clipEdge = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
chart.interactive = function(_) { | |
if(!arguments.length) return interactive; | |
interactive = false; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
// Chart design based on the recommendations of Stephen Few. Implementation | |
// based on the work of Clint Ivy, Jamie Love, and Jason Davies. | |
// http://projects.instantcognition.com/protovis/bulletchart/ | |
nv.models.bullet = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, orient = 'left' // TODO top & bottom | |
, reverse = false | |
, ranges = function(d) { return d.ranges } | |
, markers = function(d) { return d.markers } | |
, measures = function(d) { return d.measures } | |
, rangeLabels = function(d) { return d.rangeLabels ? d.rangeLabels : [] } | |
, markerLabels = function(d) { return d.markerLabels ? d.markerLabels : [] } | |
, measureLabels = function(d) { return d.measureLabels ? d.measureLabels : [] } | |
, forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.) | |
, width = 380 | |
, height = 30 | |
, tickFormat = null | |
, color = nv.utils.getColor(['#1f77b4']) | |
, dispatch = d3.dispatch('elementMouseover', 'elementMouseout') | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(d, i) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
var rangez = ranges.call(this, d, i).slice().sort(d3.descending), | |
markerz = markers.call(this, d, i).slice().sort(d3.descending), | |
measurez = measures.call(this, d, i).slice().sort(d3.descending), | |
rangeLabelz = rangeLabels.call(this, d, i).slice(), | |
markerLabelz = markerLabels.call(this, d, i).slice(), | |
measureLabelz = measureLabels.call(this, d, i).slice(); | |
//------------------------------------------------------------ | |
// Setup Scales | |
// Compute the new x-scale. | |
var x1 = d3.scale.linear() | |
.domain( d3.extent(d3.merge([forceX, rangez])) ) | |
.range(reverse ? [availableWidth, 0] : [0, availableWidth]); | |
// Retrieve the old x-scale, if this is an update. | |
var x0 = this.__chart__ || d3.scale.linear() | |
.domain([0, Infinity]) | |
.range(x1.range()); | |
// Stash the new scale. | |
this.__chart__ = x1; | |
var rangeMin = d3.min(rangez), //rangez[2] | |
rangeMax = d3.max(rangez), //rangez[0] | |
rangeAvg = rangez[1]; | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-bullet').data([d]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bullet'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('rect').attr('class', 'nv-range nv-rangeMax'); | |
gEnter.append('rect').attr('class', 'nv-range nv-rangeAvg'); | |
gEnter.append('rect').attr('class', 'nv-range nv-rangeMin'); | |
gEnter.append('rect').attr('class', 'nv-measure'); | |
gEnter.append('path').attr('class', 'nv-markerTriangle'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0) | |
w1 = function(d) { return Math.abs(x1(d) - x1(0)) }; | |
var xp0 = function(d) { return d < 0 ? x0(d) : x0(0) }, | |
xp1 = function(d) { return d < 0 ? x1(d) : x1(0) }; | |
g.select('rect.nv-rangeMax') | |
.attr('height', availableHeight) | |
.attr('width', w1(rangeMax > 0 ? rangeMax : rangeMin)) | |
.attr('x', xp1(rangeMax > 0 ? rangeMax : rangeMin)) | |
.datum(rangeMax > 0 ? rangeMax : rangeMin) | |
/* | |
.attr('x', rangeMin < 0 ? | |
rangeMax > 0 ? | |
x1(rangeMin) | |
: x1(rangeMax) | |
: x1(0)) | |
*/ | |
g.select('rect.nv-rangeAvg') | |
.attr('height', availableHeight) | |
.attr('width', w1(rangeAvg)) | |
.attr('x', xp1(rangeAvg)) | |
.datum(rangeAvg) | |
/* | |
.attr('width', rangeMax <= 0 ? | |
x1(rangeMax) - x1(rangeAvg) | |
: x1(rangeAvg) - x1(rangeMin)) | |
.attr('x', rangeMax <= 0 ? | |
x1(rangeAvg) | |
: x1(rangeMin)) | |
*/ | |
g.select('rect.nv-rangeMin') | |
.attr('height', availableHeight) | |
.attr('width', w1(rangeMax)) | |
.attr('x', xp1(rangeMax)) | |
.attr('width', w1(rangeMax > 0 ? rangeMin : rangeMax)) | |
.attr('x', xp1(rangeMax > 0 ? rangeMin : rangeMax)) | |
.datum(rangeMax > 0 ? rangeMin : rangeMax) | |
/* | |
.attr('width', rangeMax <= 0 ? | |
x1(rangeAvg) - x1(rangeMin) | |
: x1(rangeMax) - x1(rangeAvg)) | |
.attr('x', rangeMax <= 0 ? | |
x1(rangeMin) | |
: x1(rangeAvg)) | |
*/ | |
g.select('rect.nv-measure') | |
.style('fill', color) | |
.attr('height', availableHeight / 3) | |
.attr('y', availableHeight / 3) | |
.attr('width', measurez < 0 ? | |
x1(0) - x1(measurez[0]) | |
: x1(measurez[0]) - x1(0)) | |
.attr('x', xp1(measurez)) | |
.on('mouseover', function() { | |
dispatch.elementMouseover({ | |
value: measurez[0], | |
label: measureLabelz[0] || 'Current', | |
pos: [x1(measurez[0]), availableHeight/2] | |
}) | |
}) | |
.on('mouseout', function() { | |
dispatch.elementMouseout({ | |
value: measurez[0], | |
label: measureLabelz[0] || 'Current' | |
}) | |
}) | |
var h3 = availableHeight / 6; | |
if (markerz[0]) { | |
g.selectAll('path.nv-markerTriangle') | |
.attr('transform', function(d) { return 'translate(' + x1(markerz[0]) + ',' + (availableHeight / 2) + ')' }) | |
.attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z') | |
.on('mouseover', function() { | |
dispatch.elementMouseover({ | |
value: markerz[0], | |
label: markerLabelz[0] || 'Previous', | |
pos: [x1(markerz[0]), availableHeight/2] | |
}) | |
}) | |
.on('mouseout', function() { | |
dispatch.elementMouseout({ | |
value: markerz[0], | |
label: markerLabelz[0] || 'Previous' | |
}) | |
}); | |
} else { | |
g.selectAll('path.nv-markerTriangle').remove(); | |
} | |
wrap.selectAll('.nv-range') | |
.on('mouseover', function(d,i) { | |
var label = rangeLabelz[i] || (!i ? "Maximum" : i == 1 ? "Mean" : "Minimum"); | |
dispatch.elementMouseover({ | |
value: d, | |
label: label, | |
pos: [x1(d), availableHeight/2] | |
}) | |
}) | |
.on('mouseout', function(d,i) { | |
var label = rangeLabelz[i] || (!i ? "Maximum" : i == 1 ? "Mean" : "Minimum"); | |
dispatch.elementMouseout({ | |
value: d, | |
label: label | |
}) | |
}) | |
/* // THIS IS THE PREVIOUS BULLET IMPLEMENTATION, WILL REMOVE SHORTLY | |
// Update the range rects. | |
var range = g.selectAll('rect.nv-range') | |
.data(rangez); | |
range.enter().append('rect') | |
.attr('class', function(d, i) { return 'nv-range nv-s' + i; }) | |
.attr('width', w0) | |
.attr('height', availableHeight) | |
.attr('x', reverse ? x0 : 0) | |
.on('mouseover', function(d,i) { | |
dispatch.elementMouseover({ | |
value: d, | |
label: (i <= 0) ? 'Maximum' : (i > 1) ? 'Minimum' : 'Mean', //TODO: make these labels a variable | |
pos: [x1(d), availableHeight/2] | |
}) | |
}) | |
.on('mouseout', function(d,i) { | |
dispatch.elementMouseout({ | |
value: d, | |
label: (i <= 0) ? 'Minimum' : (i >=1) ? 'Maximum' : 'Mean' //TODO: make these labels a variable | |
}) | |
}) | |
d3.transition(range) | |
.attr('x', reverse ? x1 : 0) | |
.attr('width', w1) | |
.attr('height', availableHeight); | |
// Update the measure rects. | |
var measure = g.selectAll('rect.nv-measure') | |
.data(measurez); | |
measure.enter().append('rect') | |
.attr('class', function(d, i) { return 'nv-measure nv-s' + i; }) | |
.style('fill', function(d,i) { return color(d,i ) }) | |
.attr('width', w0) | |
.attr('height', availableHeight / 3) | |
.attr('x', reverse ? x0 : 0) | |
.attr('y', availableHeight / 3) | |
.on('mouseover', function(d) { | |
dispatch.elementMouseover({ | |
value: d, | |
label: 'Current', //TODO: make these labels a variable | |
pos: [x1(d), availableHeight/2] | |
}) | |
}) | |
.on('mouseout', function(d) { | |
dispatch.elementMouseout({ | |
value: d, | |
label: 'Current' //TODO: make these labels a variable | |
}) | |
}) | |
d3.transition(measure) | |
.attr('width', w1) | |
.attr('height', availableHeight / 3) | |
.attr('x', reverse ? x1 : 0) | |
.attr('y', availableHeight / 3); | |
// Update the marker lines. | |
var marker = g.selectAll('path.nv-markerTriangle') | |
.data(markerz); | |
var h3 = availableHeight / 6; | |
marker.enter().append('path') | |
.attr('class', 'nv-markerTriangle') | |
.attr('transform', function(d) { return 'translate(' + x0(d) + ',' + (availableHeight / 2) + ')' }) | |
.attr('d', 'M0,' + h3 + 'L' + h3 + ',' + (-h3) + ' ' + (-h3) + ',' + (-h3) + 'Z') | |
.on('mouseover', function(d,i) { | |
dispatch.elementMouseover({ | |
value: d, | |
label: 'Previous', | |
pos: [x1(d), availableHeight/2] | |
}) | |
}) | |
.on('mouseout', function(d,i) { | |
dispatch.elementMouseout({ | |
value: d, | |
label: 'Previous' | |
}) | |
}); | |
d3.transition(marker) | |
.attr('transform', function(d) { return 'translate(' + (x1(d) - x1(0)) + ',' + (availableHeight / 2) + ')' }); | |
marker.exit().remove(); | |
*/ | |
}); | |
// d3.timer.flush(); // Not needed? | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
// left, right, top, bottom | |
chart.orient = function(_) { | |
if (!arguments.length) return orient; | |
orient = _; | |
reverse = orient == 'right' || orient == 'bottom'; | |
return chart; | |
}; | |
// ranges (bad, satisfactory, good) | |
chart.ranges = function(_) { | |
if (!arguments.length) return ranges; | |
ranges = _; | |
return chart; | |
}; | |
// markers (previous, goal) | |
chart.markers = function(_) { | |
if (!arguments.length) return markers; | |
markers = _; | |
return chart; | |
}; | |
// measures (actual, forecast) | |
chart.measures = function(_) { | |
if (!arguments.length) return measures; | |
measures = _; | |
return chart; | |
}; | |
chart.forceX = function(_) { | |
if (!arguments.length) return forceX; | |
forceX = _; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.tickFormat = function(_) { | |
if (!arguments.length) return tickFormat; | |
tickFormat = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
}; | |
// Chart design based on the recommendations of Stephen Few. Implementation | |
// based on the work of Clint Ivy, Jamie Love, and Jason Davies. | |
// http://projects.instantcognition.com/protovis/bulletchart/ | |
nv.models.bulletChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var bullet = nv.models.bullet() | |
; | |
var orient = 'left' // TODO top & bottom | |
, reverse = false | |
, margin = {top: 5, right: 40, bottom: 20, left: 120} | |
, ranges = function(d) { return d.ranges } | |
, markers = function(d) { return d.markers } | |
, measures = function(d) { return d.measures } | |
, width = null | |
, height = 55 | |
, tickFormat = null | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + x + '</h3>' + | |
'<p>' + y + '</p>' | |
} | |
, noData = 'No Data Available.' | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ) + margin.left, | |
top = e.pos[1] + ( offsetElement.offsetTop || 0) + margin.top, | |
content = tooltip(e.key, e.label, e.value, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(d, i) { | |
var container = d3.select(this); | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
that = this; | |
chart.update = function() { chart(selection) }; | |
chart.container = this; | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!d || !ranges.call(this, d, i)) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', 18 + margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
var rangez = ranges.call(this, d, i).slice().sort(d3.descending), | |
markerz = markers.call(this, d, i).slice().sort(d3.descending), | |
measurez = measures.call(this, d, i).slice().sort(d3.descending); | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-bulletChart').data([d]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bulletChart'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-bulletWrap'); | |
gEnter.append('g').attr('class', 'nv-titles'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
// Compute the new x-scale. | |
var x1 = d3.scale.linear() | |
.domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain | |
.range(reverse ? [availableWidth, 0] : [0, availableWidth]); | |
// Retrieve the old x-scale, if this is an update. | |
var x0 = this.__chart__ || d3.scale.linear() | |
.domain([0, Infinity]) | |
.range(x1.range()); | |
// Stash the new scale. | |
this.__chart__ = x1; | |
/* | |
// Derive width-scales from the x-scales. | |
var w0 = bulletWidth(x0), | |
w1 = bulletWidth(x1); | |
function bulletWidth(x) { | |
var x0 = x(0); | |
return function(d) { | |
return Math.abs(x(d) - x(0)); | |
}; | |
} | |
function bulletTranslate(x) { | |
return function(d) { | |
return 'translate(' + x(d) + ',0)'; | |
}; | |
} | |
*/ | |
var w0 = function(d) { return Math.abs(x0(d) - x0(0)) }, // TODO: could optimize by precalculating x0(0) and x1(0) | |
w1 = function(d) { return Math.abs(x1(d) - x1(0)) }; | |
var title = gEnter.select('.nv-titles').append('g') | |
.attr('text-anchor', 'end') | |
.attr('transform', 'translate(-6,' + (height - margin.top - margin.bottom) / 2 + ')'); | |
title.append('text') | |
.attr('class', 'nv-title') | |
.text(function(d) { return d.title; }); | |
title.append('text') | |
.attr('class', 'nv-subtitle') | |
.attr('dy', '1em') | |
.text(function(d) { return d.subtitle; }); | |
bullet | |
.width(availableWidth) | |
.height(availableHeight) | |
var bulletWrap = g.select('.nv-bulletWrap'); | |
d3.transition(bulletWrap).call(bullet); | |
// Compute the tick format. | |
var format = tickFormat || x1.tickFormat( availableWidth / 100 ); | |
// Update the tick groups. | |
var tick = g.selectAll('g.nv-tick') | |
.data(x1.ticks( availableWidth / 50 ), function(d) { | |
return this.textContent || format(d); | |
}); | |
// Initialize the ticks with the old scale, x0. | |
var tickEnter = tick.enter().append('g') | |
.attr('class', 'nv-tick') | |
.attr('transform', function(d) { return 'translate(' + x0(d) + ',0)' }) | |
.style('opacity', 1e-6); | |
tickEnter.append('line') | |
.attr('y1', availableHeight) | |
.attr('y2', availableHeight * 7 / 6); | |
tickEnter.append('text') | |
.attr('text-anchor', 'middle') | |
.attr('dy', '1em') | |
.attr('y', availableHeight * 7 / 6) | |
.text(format); | |
// Transition the updating ticks to the new scale, x1. | |
var tickUpdate = d3.transition(tick) | |
.attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) | |
.style('opacity', 1); | |
tickUpdate.select('line') | |
.attr('y1', availableHeight) | |
.attr('y2', availableHeight * 7 / 6); | |
tickUpdate.select('text') | |
.attr('y', availableHeight * 7 / 6); | |
// Transition the exiting ticks to the new scale, x1. | |
d3.transition(tick.exit()) | |
.attr('transform', function(d) { return 'translate(' + x1(d) + ',0)' }) | |
.style('opacity', 1e-6) | |
.remove(); | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
dispatch.on('tooltipShow', function(e) { | |
e.key = d.title; | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
//============================================================ | |
}); | |
d3.timer.flush(); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
bullet.dispatch.on('elementMouseover.tooltip', function(e) { | |
dispatch.tooltipShow(e); | |
}); | |
bullet.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.bullet = bullet; | |
d3.rebind(chart, bullet, 'color'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
// left, right, top, bottom | |
chart.orient = function(x) { | |
if (!arguments.length) return orient; | |
orient = x; | |
reverse = orient == 'right' || orient == 'bottom'; | |
return chart; | |
}; | |
// ranges (bad, satisfactory, good) | |
chart.ranges = function(x) { | |
if (!arguments.length) return ranges; | |
ranges = x; | |
return chart; | |
}; | |
// markers (previous, goal) | |
chart.markers = function(x) { | |
if (!arguments.length) return markers; | |
markers = x; | |
return chart; | |
}; | |
// measures (actual, forecast) | |
chart.measures = function(x) { | |
if (!arguments.length) return measures; | |
measures = x; | |
return chart; | |
}; | |
chart.width = function(x) { | |
if (!arguments.length) return width; | |
width = x; | |
return chart; | |
}; | |
chart.height = function(x) { | |
if (!arguments.length) return height; | |
height = x; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.tickFormat = function(x) { | |
if (!arguments.length) return tickFormat; | |
tickFormat = x; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
}; | |
nv.models.cumulativeLineChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var lines = nv.models.line() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend() | |
, controls = nv.models.legend() | |
, interactiveLayer = nv.interactiveGuideline() | |
; | |
var margin = {top: 30, right: 30, bottom: 50, left: 60} | |
, color = nv.utils.defaultColor() | |
, width = null | |
, height = null | |
, showLegend = true | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, tooltips = true | |
, showControls = true | |
, useInteractiveGuideline = false | |
, rescaleY = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' at ' + x + '</p>' | |
} | |
, x //can be accessed via chart.xScale() | |
, y //can be accessed via chart.yScale() | |
, id = lines.id() | |
, state = { index: 0, rescaleY: rescaleY } | |
, defaultState = null | |
, noData = 'No Data Available.' | |
, average = function(d) { return d.average } | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, transitionDuration = 250 | |
, noErrorCheck = false //if set to TRUE, will bypass an error check in the indexify function. | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(7) | |
; | |
yAxis | |
.orient((rightAlignYAxis) ? 'right' : 'left') | |
; | |
//============================================================ | |
controls.updateState(false); | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var dx = d3.scale.linear() | |
, index = {i: 0, x: 0} | |
; | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, null, null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this).classed('nv-chart-' + id, true), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart) }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
var indexDrag = d3.behavior.drag() | |
.on('dragstart', dragStart) | |
.on('drag', dragMove) | |
.on('dragend', dragEnd); | |
function dragStart(d,i) { | |
d3.select(chart.container) | |
.style('cursor', 'ew-resize'); | |
} | |
function dragMove(d,i) { | |
index.x = d3.event.x; | |
index.i = Math.round(dx.invert(index.x)); | |
updateZero(); | |
} | |
function dragEnd(d,i) { | |
d3.select(chart.container) | |
.style('cursor', 'auto'); | |
// update state and send stateChange with new index | |
state.index = index.i; | |
dispatch.stateChange(state); | |
} | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = lines.xScale(); | |
y = lines.yScale(); | |
if (!rescaleY) { | |
var seriesDomains = data | |
.filter(function(series) { return !series.disabled }) | |
.map(function(series,i) { | |
var initialDomain = d3.extent(series.values, lines.y()); | |
//account for series being disabled when losing 95% or more | |
if (initialDomain[0] < -.95) initialDomain[0] = -.95; | |
return [ | |
(initialDomain[0] - initialDomain[1]) / (1 + initialDomain[1]), | |
(initialDomain[1] - initialDomain[0]) / (1 + initialDomain[0]) | |
]; | |
}); | |
var completeDomain = [ | |
d3.min(seriesDomains, function(d) { return d[0] }), | |
d3.max(seriesDomains, function(d) { return d[1] }) | |
] | |
lines.yDomain(completeDomain); | |
} else { | |
lines.yDomain(null); | |
} | |
dx .domain([0, data[0].values.length - 1]) //Assumes all series have same length | |
.range([0, availableWidth]) | |
.clamp(true); | |
//------------------------------------------------------------ | |
var data = indexify(index.i, data); | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var interactivePointerEvents = (useInteractiveGuideline) ? "none" : "all"; | |
var wrap = container.selectAll('g.nv-wrap.nv-cumulativeLine').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-cumulativeLine').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-interactive'); | |
gEnter.append('g').attr('class', 'nv-x nv-axis').style("pointer-events","none"); | |
gEnter.append('g').attr('class', 'nv-y nv-axis'); | |
gEnter.append('g').attr('class', 'nv-background'); | |
gEnter.append('g').attr('class', 'nv-linesWrap').style("pointer-events",interactivePointerEvents); | |
gEnter.append('g').attr('class', 'nv-avgLinesWrap').style("pointer-events","none"); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
gEnter.append('g').attr('class', 'nv-controlsWrap'); | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width(availableWidth); | |
g.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
g.select('.nv-legendWrap') | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Controls | |
if (showControls) { | |
var controlsData = [ | |
{ key: 'Re-scale y-axis', disabled: !rescaleY } | |
]; | |
controls | |
.width(140) | |
.color(['#444', '#444', '#444']) | |
.rightAlign(false) | |
.margin({top: 5, right: 0, bottom: 5, left: 20}) | |
; | |
g.select('.nv-controlsWrap') | |
.datum(controlsData) | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
.call(controls); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
// Show error if series goes below 100% | |
var tempDisabled = data.filter(function(d) { return d.tempDisabled }); | |
wrap.select('.tempDisabled').remove(); //clean-up and prevent duplicates | |
if (tempDisabled.length) { | |
wrap.append('text').attr('class', 'tempDisabled') | |
.attr('x', availableWidth / 2) | |
.attr('y', '-.71em') | |
.style('text-anchor', 'end') | |
.text(tempDisabled.map(function(d) { return d.key }).join(', ') + ' values cannot be calculated for this time period.'); | |
} | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
//------------------------------------------------------------ | |
//Set up interactive layer | |
if (useInteractiveGuideline) { | |
interactiveLayer | |
.width(availableWidth) | |
.height(availableHeight) | |
.margin({left:margin.left,top:margin.top}) | |
.svgContainer(container) | |
.xScale(x); | |
wrap.select(".nv-interactive").call(interactiveLayer); | |
} | |
gEnter.select('.nv-background') | |
.append('rect'); | |
g.select('.nv-background rect') | |
.attr('width', availableWidth) | |
.attr('height', availableHeight); | |
lines | |
//.x(function(d) { return d.x }) | |
.y(function(d) { return d.display.y }) | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled && !data[i].tempDisabled; })); | |
var linesWrap = g.select('.nv-linesWrap') | |
.datum(data.filter(function(d) { return !d.disabled && !d.tempDisabled })); | |
//d3.transition(linesWrap).call(lines); | |
linesWrap.call(lines); | |
/*Handle average lines [AN-612] ----------------------------*/ | |
//Store a series index number in the data array. | |
data.forEach(function(d,i) { | |
d.seriesIndex = i; | |
}); | |
var avgLineData = data.filter(function(d) { | |
return !d.disabled && !!average(d); | |
}); | |
var avgLines = g.select(".nv-avgLinesWrap").selectAll("line") | |
.data(avgLineData, function(d) { return d.key; }); | |
var getAvgLineY = function(d) { | |
//If average lines go off the svg element, clamp them to the svg bounds. | |
var yVal = y(average(d)); | |
if (yVal < 0) return 0; | |
if (yVal > availableHeight) return availableHeight; | |
return yVal; | |
}; | |
avgLines.enter() | |
.append('line') | |
.style('stroke-width',2) | |
.style('stroke-dasharray','10,10') | |
.style('stroke',function (d,i) { | |
return lines.color()(d,d.seriesIndex); | |
}) | |
.attr('x1',0) | |
.attr('x2',availableWidth) | |
.attr('y1', getAvgLineY) | |
.attr('y2', getAvgLineY); | |
avgLines | |
.style('stroke-opacity',function(d){ | |
//If average lines go offscreen, make them transparent | |
var yVal = y(average(d)); | |
if (yVal < 0 || yVal > availableHeight) return 0; | |
return 1; | |
}) | |
.attr('x1',0) | |
.attr('x2',availableWidth) | |
.attr('y1', getAvgLineY) | |
.attr('y2', getAvgLineY); | |
avgLines.exit().remove(); | |
//Create index line ----------------------------------------- | |
var indexLine = linesWrap.selectAll('.nv-indexLine') | |
.data([index]); | |
indexLine.enter().append('rect').attr('class', 'nv-indexLine') | |
.attr('width', 3) | |
.attr('x', -2) | |
.attr('fill', 'red') | |
.attr('fill-opacity', .5) | |
.style("pointer-events","all") | |
.call(indexDrag) | |
indexLine | |
.attr('transform', function(d) { return 'translate(' + dx(d.i) + ',0)' }) | |
.attr('height', availableHeight) | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
//Suggest how many ticks based on the chart width and D3 should listen (70 is the optimal number for MM/DD/YY dates) | |
.ticks( Math.min(data[0].values.length,availableWidth/70) ) | |
.tickSize(-availableHeight, 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')'); | |
d3.transition(g.select('.nv-x.nv-axis')) | |
.call(xAxis); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
d3.transition(g.select('.nv-y.nv-axis')) | |
.call(yAxis); | |
} | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
function updateZero() { | |
indexLine | |
.data([index]); | |
//When dragging the index line, turn off line transitions. | |
// Then turn them back on when done dragging. | |
var oldDuration = chart.transitionDuration(); | |
chart.transitionDuration(0); | |
chart.update(); | |
chart.transitionDuration(oldDuration); | |
} | |
g.select('.nv-background rect') | |
.on('click', function() { | |
index.x = d3.mouse(this)[0]; | |
index.i = Math.round(dx.invert(index.x)); | |
// update state and send stateChange with new index | |
state.index = index.i; | |
dispatch.stateChange(state); | |
updateZero(); | |
}); | |
lines.dispatch.on('elementClick', function(e) { | |
index.i = e.pointIndex; | |
index.x = dx(index.i); | |
// update state and send stateChange with new index | |
state.index = index.i; | |
dispatch.stateChange(state); | |
updateZero(); | |
}); | |
controls.dispatch.on('legendClick', function(d,i) { | |
d.disabled = !d.disabled; | |
rescaleY = !d.disabled; | |
state.rescaleY = rescaleY; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
legend.dispatch.on('stateChange', function(newState) { | |
state.disabled = newState.disabled; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
interactiveLayer.dispatch.on('elementMousemove', function(e) { | |
lines.clearHighlights(); | |
var singlePoint, pointIndex, pointXLocation, allData = []; | |
data | |
.filter(function(series, i) { | |
series.seriesIndex = i; | |
return !series.disabled; | |
}) | |
.forEach(function(series,i) { | |
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x()); | |
lines.highlightPoint(i, pointIndex, true); | |
var point = series.values[pointIndex]; | |
if (typeof point === 'undefined') return; | |
if (typeof singlePoint === 'undefined') singlePoint = point; | |
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex)); | |
allData.push({ | |
key: series.key, | |
value: chart.y()(point, pointIndex), | |
color: color(series,series.seriesIndex) | |
}); | |
}); | |
//Highlight the tooltip entry based on which point the mouse is closest to. | |
if (allData.length > 2) { | |
var yValue = chart.yScale().invert(e.mouseY); | |
var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]); | |
var threshold = 0.03 * domainExtent; | |
var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold); | |
if (indexToHighlight !== null) | |
allData[indexToHighlight].highlight = true; | |
} | |
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex), pointIndex); | |
interactiveLayer.tooltip | |
.position({left: pointXLocation + margin.left, top: e.mouseY + margin.top}) | |
.chartContainer(that.parentNode) | |
.enabled(tooltips) | |
.valueFormatter(function(d,i) { | |
return yAxis.tickFormat()(d); | |
}) | |
.data( | |
{ | |
value: xValue, | |
series: allData | |
} | |
)(); | |
interactiveLayer.renderGuideLine(pointXLocation); | |
}); | |
interactiveLayer.dispatch.on("elementMouseout",function(e) { | |
dispatch.tooltipHide(); | |
lines.clearHighlights(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
if (typeof e.index !== 'undefined') { | |
index.i = e.index; | |
index.x = dx(index.i); | |
state.index = e.index; | |
indexLine | |
.data([index]); | |
} | |
if (typeof e.rescaleY !== 'undefined') { | |
rescaleY = e.rescaleY; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
lines.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.lines = lines; | |
chart.legend = legend; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
chart.interactiveLayer = interactiveLayer; | |
d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'xScale','yScale', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi','useVoronoi', 'id'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.rescaleY = function(_) { | |
if (!arguments.length) return rescaleY; | |
rescaleY = _; | |
return chart; | |
}; | |
chart.showControls = function(_) { | |
if (!arguments.length) return showControls; | |
showControls = _; | |
return chart; | |
}; | |
chart.useInteractiveGuideline = function(_) { | |
if(!arguments.length) return useInteractiveGuideline; | |
useInteractiveGuideline = _; | |
if (_ === true) { | |
chart.interactive(false); | |
chart.useVoronoi(false); | |
} | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.average = function(_) { | |
if(!arguments.length) return average; | |
average = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
chart.noErrorCheck = function(_) { | |
if (!arguments.length) return noErrorCheck; | |
noErrorCheck = _; | |
return chart; | |
}; | |
//============================================================ | |
//============================================================ | |
// Functions | |
//------------------------------------------------------------ | |
/* Normalize the data according to an index point. */ | |
function indexify(idx, data) { | |
return data.map(function(line, i) { | |
if (!line.values) { | |
return line; | |
} | |
var indexValue = line.values[idx]; | |
if (indexValue == null) { | |
return line; | |
} | |
var v = lines.y()(indexValue, idx); | |
//TODO: implement check below, and disable series if series loses 100% or more cause divide by 0 issue | |
if (v < -.95 && !noErrorCheck) { | |
//if a series loses more than 100%, calculations fail.. anything close can cause major distortion (but is mathematically correct till it hits 100) | |
line.tempDisabled = true; | |
return line; | |
} | |
line.tempDisabled = false; | |
line.values = line.values.map(function(point, pointIndex) { | |
point.display = {'y': (lines.y()(point, pointIndex) - v) / (1 + v) }; | |
return point; | |
}) | |
return line; | |
}) | |
} | |
//============================================================ | |
return chart; | |
} | |
//TODO: consider deprecating by adding necessary features to multiBar model | |
nv.models.discreteBar = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one | |
, x = d3.scale.ordinal() | |
, y = d3.scale.linear() | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove | |
, color = nv.utils.defaultColor() | |
, showValues = false | |
, valueFormat = d3.format(',.2f') | |
, xDomain | |
, yDomain | |
, xRange | |
, yRange | |
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') | |
, rectClass = 'discreteBar' | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x0, y0; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
//add series index to each data point for reference | |
data.forEach(function(series, i) { | |
series.values.forEach(function(point) { | |
point.series = i; | |
}); | |
}); | |
//------------------------------------------------------------ | |
// Setup Scales | |
// remap and flatten the data for use in calculating the scales' domains | |
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate | |
data.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: getX(d,i), y: getY(d,i), y0: d.y0 } | |
}) | |
}); | |
x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x })) | |
.rangeBands(xRange || [0, availableWidth], .1); | |
y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y }).concat(forceY))); | |
// If showValues, pad the Y axis range to account for label height | |
if (showValues) y.range(yRange || [availableHeight - (y.domain()[0] < 0 ? 12 : 0), y.domain()[1] > 0 ? 12 : 0]); | |
else y.range(yRange || [availableHeight, 0]); | |
//store old scales if they exist | |
x0 = x0 || x; | |
y0 = y0 || y.copy().range([y(0),y(0)]); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-discretebar').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discretebar'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-groups'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
//TODO: by definition, the discrete bar should not have multiple groups, will modify/remove later | |
var groups = wrap.select('.nv-groups').selectAll('.nv-group') | |
.data(function(d) { return d }, function(d) { return d.key }); | |
groups.enter().append('g') | |
.style('stroke-opacity', 1e-6) | |
.style('fill-opacity', 1e-6); | |
groups.exit() | |
.transition() | |
.style('stroke-opacity', 1e-6) | |
.style('fill-opacity', 1e-6) | |
.remove(); | |
groups | |
.attr('class', function(d,i) { return 'nv-group nv-series-' + i }) | |
.classed('hover', function(d) { return d.hover }); | |
groups | |
.transition() | |
.style('stroke-opacity', 1) | |
.style('fill-opacity', .75); | |
var bars = groups.selectAll('g.nv-bar') | |
.data(function(d) { return d.values }); | |
bars.exit().remove(); | |
var barsEnter = bars.enter().append('g') | |
.attr('transform', function(d,i,j) { | |
return 'translate(' + (x(getX(d,i)) + x.rangeBand() * .05 ) + ', ' + y(0) + ')' | |
}) | |
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here | |
d3.select(this).classed('hover', true); | |
dispatch.elementMouseover({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
}) | |
.on('mouseout', function(d,i) { | |
d3.select(this).classed('hover', false); | |
dispatch.elementMouseout({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
}) | |
.on('click', function(d,i) { | |
dispatch.elementClick({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
d3.event.stopPropagation(); | |
}) | |
.on('dblclick', function(d,i) { | |
dispatch.elementDblClick({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (d.series + .5) / data.length), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
d3.event.stopPropagation(); | |
}); | |
barsEnter.append('rect') | |
.attr('height', 0) | |
.attr('width', x.rangeBand() * .9 / data.length ) | |
if (showValues) { | |
barsEnter.append('text') | |
.attr('text-anchor', 'middle') | |
; | |
bars.select('text') | |
.text(function(d,i) { return valueFormat(getY(d,i)) }) | |
.transition() | |
.attr('x', x.rangeBand() * .9 / 2) | |
.attr('y', function(d,i) { return getY(d,i) < 0 ? y(getY(d,i)) - y(0) + 12 : -4 }) | |
; | |
} else { | |
bars.selectAll('text').remove(); | |
} | |
bars | |
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive' }) | |
.style('fill', function(d,i) { return d.color || color(d,i) }) | |
.style('stroke', function(d,i) { return d.color || color(d,i) }) | |
.select('rect') | |
.attr('class', rectClass) | |
.transition() | |
.attr('width', x.rangeBand() * .9 / data.length); | |
bars.transition() | |
//.delay(function(d,i) { return i * 1200 / data[0].values.length }) | |
.attr('transform', function(d,i) { | |
var left = x(getX(d,i)) + x.rangeBand() * .05, | |
top = getY(d,i) < 0 ? | |
y(0) : | |
y(0) - y(getY(d,i)) < 1 ? | |
y(0) - 1 : //make 1 px positive bars show up above y=0 | |
y(getY(d,i)); | |
return 'translate(' + left + ', ' + top + ')' | |
}) | |
.select('rect') | |
.attr('height', function(d,i) { | |
return Math.max(Math.abs(y(getY(d,i)) - y((yDomain && yDomain[0]) || 0)) || 1) | |
}); | |
//store old scales for use in transitions on update | |
x0 = x.copy(); | |
y0 = y.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.xScale = function(_) { | |
if (!arguments.length) return x; | |
x = _; | |
return chart; | |
}; | |
chart.yScale = function(_) { | |
if (!arguments.length) return y; | |
y = _; | |
return chart; | |
}; | |
chart.xDomain = function(_) { | |
if (!arguments.length) return xDomain; | |
xDomain = _; | |
return chart; | |
}; | |
chart.yDomain = function(_) { | |
if (!arguments.length) return yDomain; | |
yDomain = _; | |
return chart; | |
}; | |
chart.xRange = function(_) { | |
if (!arguments.length) return xRange; | |
xRange = _; | |
return chart; | |
}; | |
chart.yRange = function(_) { | |
if (!arguments.length) return yRange; | |
yRange = _; | |
return chart; | |
}; | |
chart.forceY = function(_) { | |
if (!arguments.length) return forceY; | |
forceY = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
chart.showValues = function(_) { | |
if (!arguments.length) return showValues; | |
showValues = _; | |
return chart; | |
}; | |
chart.valueFormat= function(_) { | |
if (!arguments.length) return valueFormat; | |
valueFormat = _; | |
return chart; | |
}; | |
chart.rectClass= function(_) { | |
if (!arguments.length) return rectClass; | |
rectClass = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.discreteBarChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var discretebar = nv.models.discreteBar() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
; | |
var margin = {top: 15, right: 10, bottom: 50, left: 60} | |
, width = null | |
, height = null | |
, color = nv.utils.getColor() | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, staggerLabels = false | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + x + '</h3>' + | |
'<p>' + y + '</p>' | |
} | |
, x | |
, y | |
, noData = "No Data Available." | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'beforeUpdate') | |
, transitionDuration = 250 | |
; | |
xAxis | |
.orient('bottom') | |
.highlightZero(false) | |
.showMaxMin(false) | |
.tickFormat(function(d) { return d }) | |
; | |
yAxis | |
.orient((rightAlignYAxis) ? 'right' : 'left') | |
.tickFormat(d3.format(',.1f')) | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(discretebar.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(discretebar.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { | |
dispatch.beforeUpdate(); | |
container.transition().duration(transitionDuration).call(chart); | |
}; | |
chart.container = this; | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = discretebar.xScale(); | |
y = discretebar.yScale().clamp(true); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-discreteBarWithAxes').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-discreteBarWithAxes').append('g'); | |
var defsEnter = gEnter.append('defs'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis') | |
.append('g').attr('class', 'nv-zeroLine') | |
.append('line'); | |
gEnter.append('g').attr('class', 'nv-barsWrap'); | |
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
discretebar | |
.width(availableWidth) | |
.height(availableHeight); | |
var barsWrap = g.select('.nv-barsWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
barsWrap.transition().call(discretebar); | |
//------------------------------------------------------------ | |
defsEnter.append('clipPath') | |
.attr('id', 'nv-x-label-clip-' + discretebar.id()) | |
.append('rect'); | |
g.select('#nv-x-label-clip-' + discretebar.id() + ' rect') | |
.attr('width', x.rangeBand() * (staggerLabels ? 2 : 1)) | |
.attr('height', 16) | |
.attr('x', -x.rangeBand() / (staggerLabels ? 1 : 2 )); | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight, 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + (y.range()[0] + ((discretebar.showValues() && y.domain()[0] < 0) ? 16 : 0)) + ')'); | |
//d3.transition(g.select('.nv-x.nv-axis')) | |
g.select('.nv-x.nv-axis').transition() | |
.call(xAxis); | |
var xTicks = g.select('.nv-x.nv-axis').selectAll('g'); | |
if (staggerLabels) { | |
xTicks | |
.selectAll('text') | |
.attr('transform', function(d,i,j) { return 'translate(0,' + (j % 2 == 0 ? '5' : '17') + ')' }) | |
} | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-y.nv-axis').transition() | |
.call(yAxis); | |
} | |
// Zero line | |
g.select(".nv-zeroLine line") | |
.attr("x1",0) | |
.attr("x2",availableWidth) | |
.attr("y1", y(0)) | |
.attr("y2", y(0)) | |
; | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
discretebar.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
discretebar.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.discretebar = discretebar; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
d3.rebind(chart, discretebar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'id', 'showValues', 'valueFormat'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
discretebar.color(color); | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.staggerLabels = function(_) { | |
if (!arguments.length) return staggerLabels; | |
staggerLabels = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.distribution = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 400 //technically width or height depending on x or y.... | |
, size = 8 | |
, axis = 'x' // 'x' or 'y'... horizontal or vertical | |
, getData = function(d) { return d[axis] } // defaults d.x or d.y | |
, color = nv.utils.defaultColor() | |
, scale = d3.scale.linear() | |
, domain | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var scale0; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableLength = width - (axis === 'x' ? margin.left + margin.right : margin.top + margin.bottom), | |
naxis = axis == 'x' ? 'y' : 'x', | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup Scales | |
scale0 = scale0 || scale; | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-distribution').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-distribution'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') | |
//------------------------------------------------------------ | |
var distWrap = g.selectAll('g.nv-dist') | |
.data(function(d) { return d }, function(d) { return d.key }); | |
distWrap.enter().append('g'); | |
distWrap | |
.attr('class', function(d,i) { return 'nv-dist nv-series-' + i }) | |
.style('stroke', function(d,i) { return color(d, i) }); | |
var dist = distWrap.selectAll('line.nv-dist' + axis) | |
.data(function(d) { return d.values }) | |
dist.enter().append('line') | |
.attr(axis + '1', function(d,i) { return scale0(getData(d,i)) }) | |
.attr(axis + '2', function(d,i) { return scale0(getData(d,i)) }) | |
distWrap.exit().selectAll('line.nv-dist' + axis) | |
.transition() | |
.attr(axis + '1', function(d,i) { return scale(getData(d,i)) }) | |
.attr(axis + '2', function(d,i) { return scale(getData(d,i)) }) | |
.style('stroke-opacity', 0) | |
.remove(); | |
dist | |
.attr('class', function(d,i) { return 'nv-dist' + axis + ' nv-dist' + axis + '-' + i }) | |
.attr(naxis + '1', 0) | |
.attr(naxis + '2', size); | |
dist | |
.transition() | |
.attr(axis + '1', function(d,i) { return scale(getData(d,i)) }) | |
.attr(axis + '2', function(d,i) { return scale(getData(d,i)) }) | |
scale0 = scale.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.axis = function(_) { | |
if (!arguments.length) return axis; | |
axis = _; | |
return chart; | |
}; | |
chart.size = function(_) { | |
if (!arguments.length) return size; | |
size = _; | |
return chart; | |
}; | |
chart.getData = function(_) { | |
if (!arguments.length) return getData; | |
getData = d3.functor(_); | |
return chart; | |
}; | |
chart.scale = function(_) { | |
if (!arguments.length) return scale; | |
scale = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.historicalBarChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var bars = nv.models.historicalBar() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend() | |
; | |
var margin = {top: 30, right: 90, bottom: 50, left: 90} | |
, color = nv.utils.defaultColor() | |
, width = null | |
, height = null | |
, showLegend = false | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' at ' + x + '</p>' | |
} | |
, x | |
, y | |
, state = {} | |
, defaultState = null | |
, noData = 'No Data Available.' | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, transitionDuration = 250 | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(7) | |
; | |
yAxis | |
.orient( (rightAlignYAxis) ? 'right' : 'left') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
// New addition to calculate position if SVG is scaled with viewBox, may move TODO: consider implementing everywhere else | |
if (offsetElement) { | |
var svg = d3.select(offsetElement).select('svg'); | |
var viewBox = (svg.node()) ? svg.attr('viewBox') : null; | |
if (viewBox) { | |
viewBox = viewBox.split(' '); | |
var ratio = parseInt(svg.style('width')) / viewBox[2]; | |
e.pos[0] = e.pos[0] * ratio; | |
e.pos[1] = e.pos[1] * ratio; | |
} | |
} | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(bars.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(bars.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, null, null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart) }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display noData message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = bars.xScale(); | |
y = bars.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-historicalBarChart').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-historicalBarChart').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis'); | |
gEnter.append('g').attr('class', 'nv-barsWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width(availableWidth); | |
g.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
wrap.select('.nv-legendWrap') | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
bars | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })); | |
var barsWrap = g.select('.nv-barsWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
barsWrap.transition().call(bars); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.tickSize(-availableHeight, 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')'); | |
g.select('.nv-x.nv-axis') | |
.transition() | |
.call(xAxis); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-y.nv-axis') | |
.transition() | |
.call(yAxis); | |
} | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('legendClick', function(d,i) { | |
d.disabled = !d.disabled; | |
if (!data.filter(function(d) { return !d.disabled }).length) { | |
data.map(function(d) { | |
d.disabled = false; | |
wrap.selectAll('.nv-series').classed('disabled', false); | |
return d; | |
}); | |
} | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
dispatch.stateChange(state); | |
selection.transition().call(chart); | |
}); | |
legend.dispatch.on('legendDblclick', function(d) { | |
//Double clicking should always enable current series, and disabled all others. | |
data.forEach(function(d) { | |
d.disabled = true; | |
}); | |
d.disabled = false; | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
bars.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
bars.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.bars = bars; | |
chart.legend = legend; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
d3.rebind(chart, bars, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', | |
'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id', 'interpolate','highlightPoint','clearHighlights', 'interactive'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.indentedTree = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} //TODO: implement, maybe as margin on the containing div | |
, width = 960 | |
, height = 500 | |
, color = nv.utils.defaultColor() | |
, id = Math.floor(Math.random() * 10000) | |
, header = true | |
, filterZero = false | |
, noData = "No Data Available." | |
, childIndent = 20 | |
, columns = [{key:'key', label: 'Name', type:'text'}] //TODO: consider functions like chart.addColumn, chart.removeColumn, instead of a block like this | |
, tableClass = null | |
, iconOpen = 'images/grey-plus.png' //TODO: consider removing this and replacing with a '+' or '-' unless user defines images | |
, iconClose = 'images/grey-minus.png' | |
, dispatch = d3.dispatch('elementClick', 'elementDblclick', 'elementMouseover', 'elementMouseout') | |
, getUrl = function(d) { return d.url } | |
; | |
//============================================================ | |
var idx = 0; | |
function chart(selection) { | |
selection.each(function(data) { | |
var depth = 1, | |
container = d3.select(this); | |
var tree = d3.layout.tree() | |
.children(function(d) { return d.values }) | |
.size([height, childIndent]); //Not sure if this is needed now that the result is HTML | |
chart.update = function() { container.transition().duration(600).call(chart) }; | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data[0]) data[0] = {key: noData}; | |
//------------------------------------------------------------ | |
var nodes = tree.nodes(data[0]); | |
// nodes.map(function(d) { | |
// d.id = i++; | |
// }) | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = d3.select(this).selectAll('div').data([[nodes]]); | |
var wrapEnter = wrap.enter().append('div').attr('class', 'nvd3 nv-wrap nv-indentedtree'); | |
var tableEnter = wrapEnter.append('table'); | |
var table = wrap.select('table').attr('width', '100%').attr('class', tableClass); | |
//------------------------------------------------------------ | |
if (header) { | |
var thead = tableEnter.append('thead'); | |
var theadRow1 = thead.append('tr'); | |
columns.forEach(function(column) { | |
theadRow1 | |
.append('th') | |
.attr('width', column.width ? column.width : '10%') | |
.style('text-align', column.type == 'numeric' ? 'right' : 'left') | |
.append('span') | |
.text(column.label); | |
}); | |
} | |
var tbody = table.selectAll('tbody') | |
.data(function(d) { return d }); | |
tbody.enter().append('tbody'); | |
//compute max generations | |
depth = d3.max(nodes, function(node) { return node.depth }); | |
tree.size([height, depth * childIndent]); //TODO: see if this is necessary at all | |
// Update the nodes… | |
var node = tbody.selectAll('tr') | |
// .data(function(d) { return d; }, function(d) { return d.id || (d.id == ++i)}); | |
.data(function(d) { return d.filter(function(d) { return (filterZero && !d.children) ? filterZero(d) : true; } )}, function(d,i) { return d.id || (d.id || ++idx)}); | |
//.style('display', 'table-row'); //TODO: see if this does anything | |
node.exit().remove(); | |
node.select('img.nv-treeicon') | |
.attr('src', icon) | |
.classed('folded', folded); | |
var nodeEnter = node.enter().append('tr'); | |
columns.forEach(function(column, index) { | |
var nodeName = nodeEnter.append('td') | |
.style('padding-left', function(d) { return (index ? 0 : d.depth * childIndent + 12 + (icon(d) ? 0 : 16)) + 'px' }, 'important') //TODO: check why I did the ternary here | |
.style('text-align', column.type == 'numeric' ? 'right' : 'left'); | |
if (index == 0) { | |
nodeName.append('img') | |
.classed('nv-treeicon', true) | |
.classed('nv-folded', folded) | |
.attr('src', icon) | |
.style('width', '14px') | |
.style('height', '14px') | |
.style('padding', '0 1px') | |
.style('display', function(d) { return icon(d) ? 'inline-block' : 'none'; }) | |
.on('click', click); | |
} | |
nodeName.each(function(d) { | |
if (!index && getUrl(d)) | |
d3.select(this) | |
.append('a') | |
.attr('href',getUrl) | |
.attr('class', d3.functor(column.classes)) | |
.append('span') | |
else | |
d3.select(this) | |
.append('span') | |
d3.select(this).select('span') | |
.attr('class', d3.functor(column.classes) ) | |
.text(function(d) { return column.format ? column.format(d) : | |
(d[column.key] || '-') }); | |
}); | |
if (column.showCount) { | |
nodeName.append('span') | |
.attr('class', 'nv-childrenCount'); | |
node.selectAll('span.nv-childrenCount').text(function(d) { | |
return ((d.values && d.values.length) || (d._values && d._values.length)) ? //If this is a parent | |
'(' + ((d.values && (d.values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length)) //If children are in values check its children and filter | |
|| (d._values && d._values.filter(function(d) { return filterZero ? filterZero(d) : true; }).length) //Otherwise, do the same, but with the other name, _values... | |
|| 0) + ')' //This is the catch-all in case there are no children after a filter | |
: '' //If this is not a parent, just give an empty string | |
}); | |
} | |
// if (column.click) | |
// nodeName.select('span').on('click', column.click); | |
}); | |
node | |
.order() | |
.on('click', function(d) { | |
dispatch.elementClick({ | |
row: this, //TODO: decide whether or not this should be consistent with scatter/line events or should be an html link (a href) | |
data: d, | |
pos: [d.x, d.y] | |
}); | |
}) | |
.on('dblclick', function(d) { | |
dispatch.elementDblclick({ | |
row: this, | |
data: d, | |
pos: [d.x, d.y] | |
}); | |
}) | |
.on('mouseover', function(d) { | |
dispatch.elementMouseover({ | |
row: this, | |
data: d, | |
pos: [d.x, d.y] | |
}); | |
}) | |
.on('mouseout', function(d) { | |
dispatch.elementMouseout({ | |
row: this, | |
data: d, | |
pos: [d.x, d.y] | |
}); | |
}); | |
// Toggle children on click. | |
function click(d, _, unshift) { | |
d3.event.stopPropagation(); | |
if(d3.event.shiftKey && !unshift) { | |
//If you shift-click, it'll toggle fold all the children, instead of itself | |
d3.event.shiftKey = false; | |
d.values && d.values.forEach(function(node){ | |
if (node.values || node._values) { | |
click(node, 0, true); | |
} | |
}); | |
return true; | |
} | |
if(!hasChildren(d)) { | |
//download file | |
//window.location.href = d.url; | |
return true; | |
} | |
if (d.values) { | |
d._values = d.values; | |
d.values = null; | |
} else { | |
d.values = d._values; | |
d._values = null; | |
} | |
chart.update(); | |
} | |
function icon(d) { | |
return (d._values && d._values.length) ? iconOpen : (d.values && d.values.length) ? iconClose : ''; | |
} | |
function folded(d) { | |
return (d._values && d._values.length); | |
} | |
function hasChildren(d) { | |
var values = d.values || d._values; | |
return (values && values.length); | |
} | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
scatter.color(color); | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
chart.header = function(_) { | |
if (!arguments.length) return header; | |
header = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.filterZero = function(_) { | |
if (!arguments.length) return filterZero; | |
filterZero = _; | |
return chart; | |
}; | |
chart.columns = function(_) { | |
if (!arguments.length) return columns; | |
columns = _; | |
return chart; | |
}; | |
chart.tableClass = function(_) { | |
if (!arguments.length) return tableClass; | |
tableClass = _; | |
return chart; | |
}; | |
chart.iconOpen = function(_){ | |
if (!arguments.length) return iconOpen; | |
iconOpen = _; | |
return chart; | |
} | |
chart.iconClose = function(_){ | |
if (!arguments.length) return iconClose; | |
iconClose = _; | |
return chart; | |
} | |
chart.getUrl = function(_){ | |
if (!arguments.length) return getUrl; | |
getUrl = _; | |
return chart; | |
} | |
//============================================================ | |
return chart; | |
};nv.models.legend = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 5, right: 0, bottom: 5, left: 0} | |
, width = 400 | |
, height = 20 | |
, getKey = function(d) { return d.key } | |
, color = nv.utils.defaultColor() | |
, align = true | |
, rightAlign = true | |
, updateState = true //If true, legend will update data.disabled and trigger a 'stateChange' dispatch. | |
, radioButtonMode = false //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time) | |
, dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange') | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-legend').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g'); | |
var g = wrap.select('g'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
var series = g.selectAll('.nv-series') | |
.data(function(d) { return d }); | |
var seriesEnter = series.enter().append('g').attr('class', 'nv-series') | |
.on('mouseover', function(d,i) { | |
dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects | |
}) | |
.on('mouseout', function(d,i) { | |
dispatch.legendMouseout(d,i); | |
}) | |
.on('click', function(d,i) { | |
dispatch.legendClick(d,i); | |
if (updateState) { | |
if (radioButtonMode) { | |
//Radio button mode: set every series to disabled, | |
// and enable the clicked series. | |
data.forEach(function(series) { series.disabled = true}); | |
d.disabled = false; | |
} | |
else { | |
d.disabled = !d.disabled; | |
if (data.every(function(series) { return series.disabled})) { | |
//the default behavior of NVD3 legends is, if every single series | |
// is disabled, turn all series' back on. | |
data.forEach(function(series) { series.disabled = false}); | |
} | |
} | |
dispatch.stateChange({ | |
disabled: data.map(function(d) { return !!d.disabled }) | |
}); | |
} | |
}) | |
.on('dblclick', function(d,i) { | |
dispatch.legendDblclick(d,i); | |
if (updateState) { | |
//the default behavior of NVD3 legends, when double clicking one, | |
// is to set all other series' to false, and make the double clicked series enabled. | |
data.forEach(function(series) { | |
series.disabled = true; | |
}); | |
d.disabled = false; | |
dispatch.stateChange({ | |
disabled: data.map(function(d) { return !!d.disabled }) | |
}); | |
} | |
}); | |
seriesEnter.append('circle') | |
.style('stroke-width', 2) | |
.attr('class','nv-legend-symbol') | |
.attr('r', 5); | |
seriesEnter.append('text') | |
.attr('text-anchor', 'start') | |
.attr('class','nv-legend-text') | |
.attr('dy', '.32em') | |
.attr('dx', '8'); | |
series.classed('disabled', function(d) { return d.disabled }); | |
series.exit().remove(); | |
series.select('circle') | |
.style('fill', function(d,i) { return d.color || color(d,i)}) | |
.style('stroke', function(d,i) { return d.color || color(d, i) }); | |
series.select('text').text(getKey); | |
//TODO: implement fixed-width and max-width options (max-width is especially useful with the align option) | |
// NEW ALIGNING CODE, TODO: clean up | |
if (align) { | |
var seriesWidths = []; | |
series.each(function(d,i) { | |
var legendText = d3.select(this).select('text'); | |
var nodeTextLength; | |
try { | |
nodeTextLength = legendText.getComputedTextLength(); | |
// If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead | |
if(nodeTextLength <= 0) throw Error(); | |
} | |
catch(e) { | |
nodeTextLength = nv.utils.calcApproxTextWidth(legendText); | |
} | |
seriesWidths.push(nodeTextLength + 28); // 28 is ~ the width of the circle plus some padding | |
}); | |
var seriesPerRow = 0; | |
var legendWidth = 0; | |
var columnWidths = []; | |
while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) { | |
columnWidths[seriesPerRow] = seriesWidths[seriesPerRow]; | |
legendWidth += seriesWidths[seriesPerRow++]; | |
} | |
if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row | |
while ( legendWidth > availableWidth && seriesPerRow > 1 ) { | |
columnWidths = []; | |
seriesPerRow--; | |
for (var k = 0; k < seriesWidths.length; k++) { | |
if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) ) | |
columnWidths[k % seriesPerRow] = seriesWidths[k]; | |
} | |
legendWidth = columnWidths.reduce(function(prev, cur, index, array) { | |
return prev + cur; | |
}); | |
} | |
var xPositions = []; | |
for (var i = 0, curX = 0; i < seriesPerRow; i++) { | |
xPositions[i] = curX; | |
curX += columnWidths[i]; | |
} | |
series | |
.attr('transform', function(d, i) { | |
return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * 20) + ')'; | |
}); | |
//position legend as far right as possible within the total width | |
if (rightAlign) { | |
g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')'); | |
} | |
else { | |
g.attr('transform', 'translate(0' + ',' + margin.top + ')'); | |
} | |
height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * 20); | |
} else { | |
var ypos = 5, | |
newxpos = 5, | |
maxwidth = 0, | |
xpos; | |
series | |
.attr('transform', function(d, i) { | |
var length = d3.select(this).select('text').node().getComputedTextLength() + 28; | |
xpos = newxpos; | |
if (width < margin.left + margin.right + xpos + length) { | |
newxpos = xpos = 5; | |
ypos += 20; | |
} | |
newxpos += length; | |
if (newxpos > maxwidth) maxwidth = newxpos; | |
return 'translate(' + xpos + ',' + ypos + ')'; | |
}); | |
//position legend as far right as possible within the total width | |
g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')'); | |
height = margin.top + margin.bottom + ypos + 15; | |
} | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.key = function(_) { | |
if (!arguments.length) return getKey; | |
getKey = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.align = function(_) { | |
if (!arguments.length) return align; | |
align = _; | |
return chart; | |
}; | |
chart.rightAlign = function(_) { | |
if (!arguments.length) return rightAlign; | |
rightAlign = _; | |
return chart; | |
}; | |
chart.updateState = function(_) { | |
if (!arguments.length) return updateState; | |
updateState = _; | |
return chart; | |
}; | |
chart.radioButtonMode = function(_) { | |
if (!arguments.length) return radioButtonMode; | |
radioButtonMode = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.line = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var scatter = nv.models.scatter() | |
; | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, color = nv.utils.defaultColor() // a function that returns a color | |
, getX = function(d) { return d.x } // accessor to get the x value from a data point | |
, getY = function(d) { return d.y } // accessor to get the y value from a data point | |
, defined = function(d,i) { return !isNaN(getY(d,i)) && getY(d,i) !== null } // allows a line to be not continuous when it is not defined | |
, isArea = function(d) { return d.area } // decides if a line is an area or just a line | |
, clipEdge = false // if true, masks lines within x and y scale | |
, x //can be accessed via chart.xScale() | |
, y //can be accessed via chart.yScale() | |
, interpolate = "linear" // controls the line interpolation | |
; | |
scatter | |
.size(16) // default size | |
.sizeDomain([16,256]) //set to speed up calculation, needs to be unset if there is a custom size accessor | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x0, y0 //used to store previous scales | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = scatter.xScale(); | |
y = scatter.yScale(); | |
x0 = x0 || x; | |
y0 = y0 || y; | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-line').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-line'); | |
var defsEnter = wrapEnter.append('defs'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g') | |
gEnter.append('g').attr('class', 'nv-groups'); | |
gEnter.append('g').attr('class', 'nv-scatterWrap'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
scatter | |
.width(availableWidth) | |
.height(availableHeight) | |
var scatterWrap = wrap.select('.nv-scatterWrap'); | |
//.datum(data); // Data automatically trickles down from the wrap | |
scatterWrap.transition().call(scatter); | |
defsEnter.append('clipPath') | |
.attr('id', 'nv-edge-clip-' + scatter.id()) | |
.append('rect'); | |
wrap.select('#nv-edge-clip-' + scatter.id() + ' rect') | |
.attr('width', availableWidth) | |
.attr('height', (availableHeight > 0) ? availableHeight : 0); | |
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : ''); | |
scatterWrap | |
.attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + scatter.id() + ')' : ''); | |
var groups = wrap.select('.nv-groups').selectAll('.nv-group') | |
.data(function(d) { return d }, function(d) { return d.key }); | |
groups.enter().append('g') | |
.style('stroke-opacity', 1e-6) | |
.style('fill-opacity', 1e-6); | |
groups.exit().remove(); | |
groups | |
.attr('class', function(d,i) { return 'nv-group nv-series-' + i }) | |
.classed('hover', function(d) { return d.hover }) | |
.style('fill', function(d,i){ return color(d, i) }) | |
.style('stroke', function(d,i){ return color(d, i)}); | |
groups | |
.transition() | |
.style('stroke-opacity', 1) | |
.style('fill-opacity', .5); | |
var areaPaths = groups.selectAll('path.nv-area') | |
.data(function(d) { return isArea(d) ? [d] : [] }); // this is done differently than lines because I need to check if series is an area | |
areaPaths.enter().append('path') | |
.attr('class', 'nv-area') | |
.attr('d', function(d) { | |
return d3.svg.area() | |
.interpolate(interpolate) | |
.defined(defined) | |
.x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) }) | |
.y0(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) }) | |
.y1(function(d,i) { return y0( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) | |
//.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this | |
.apply(this, [d.values]) | |
}); | |
groups.exit().selectAll('path.nv-area') | |
.remove(); | |
areaPaths | |
.transition() | |
.attr('d', function(d) { | |
return d3.svg.area() | |
.interpolate(interpolate) | |
.defined(defined) | |
.x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) }) | |
.y0(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) }) | |
.y1(function(d,i) { return y( y.domain()[0] <= 0 ? y.domain()[1] >= 0 ? 0 : y.domain()[1] : y.domain()[0] ) }) | |
//.y1(function(d,i) { return y0(0) }) //assuming 0 is within y domain.. may need to tweak this | |
.apply(this, [d.values]) | |
}); | |
var linePaths = groups.selectAll('path.nv-line') | |
.data(function(d) { return [d.values] }); | |
linePaths.enter().append('path') | |
.attr('class', 'nv-line') | |
.attr('d', | |
d3.svg.line() | |
.interpolate(interpolate) | |
.defined(defined) | |
.x(function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) }) | |
.y(function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) }) | |
); | |
linePaths | |
.transition() | |
.attr('d', | |
d3.svg.line() | |
.interpolate(interpolate) | |
.defined(defined) | |
.x(function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) }) | |
.y(function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) }) | |
); | |
//store old scales for use in transitions on update | |
x0 = x.copy(); | |
y0 = y.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = scatter.dispatch; | |
chart.scatter = scatter; | |
d3.rebind(chart, scatter, 'id', 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange', | |
'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'useVoronoi', 'clipRadius', 'padData','highlightPoint','clearHighlights'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
scatter.x(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
scatter.y(_); | |
return chart; | |
}; | |
chart.clipEdge = function(_) { | |
if (!arguments.length) return clipEdge; | |
clipEdge = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
scatter.color(color); | |
return chart; | |
}; | |
chart.interpolate = function(_) { | |
if (!arguments.length) return interpolate; | |
interpolate = _; | |
return chart; | |
}; | |
chart.defined = function(_) { | |
if (!arguments.length) return defined; | |
defined = _; | |
return chart; | |
}; | |
chart.isArea = function(_) { | |
if (!arguments.length) return isArea; | |
isArea = d3.functor(_); | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.lineChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var lines = nv.models.line() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend() | |
, interactiveLayer = nv.interactiveGuideline() | |
; | |
var margin = {top: 30, right: 20, bottom: 50, left: 60} | |
, color = nv.utils.defaultColor() | |
, width = null | |
, height = null | |
, showLegend = true | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, useInteractiveGuideline = false | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' at ' + x + '</p>' | |
} | |
, x | |
, y | |
, state = {} | |
, defaultState = null | |
, noData = 'No Data Available.' | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, transitionDuration = 250 | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(7) | |
; | |
yAxis | |
.orient((rightAlignYAxis) ? 'right' : 'left') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, null, null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart) }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display noData message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = lines.xScale(); | |
y = lines.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-lineChart').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineChart').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append("rect").style("opacity",0); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis'); | |
gEnter.append('g').attr('class', 'nv-linesWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
gEnter.append('g').attr('class', 'nv-interactive'); | |
g.select("rect") | |
.attr("width",availableWidth) | |
.attr("height",(availableHeight > 0) ? availableHeight : 0); | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width(availableWidth); | |
g.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
wrap.select('.nv-legendWrap') | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
//------------------------------------------------------------ | |
//Set up interactive layer | |
if (useInteractiveGuideline) { | |
interactiveLayer | |
.width(availableWidth) | |
.height(availableHeight) | |
.margin({left:margin.left, top:margin.top}) | |
.svgContainer(container) | |
.xScale(x); | |
wrap.select(".nv-interactive").call(interactiveLayer); | |
} | |
lines | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })); | |
var linesWrap = g.select('.nv-linesWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
linesWrap.transition().call(lines); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight, 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')'); | |
g.select('.nv-x.nv-axis') | |
.transition() | |
.call(xAxis); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-y.nv-axis') | |
.transition() | |
.call(yAxis); | |
} | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('stateChange', function(newState) { | |
state = newState; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
interactiveLayer.dispatch.on('elementMousemove', function(e) { | |
lines.clearHighlights(); | |
var singlePoint, pointIndex, pointXLocation, allData = []; | |
data | |
.filter(function(series, i) { | |
series.seriesIndex = i; | |
return !series.disabled; | |
}) | |
.forEach(function(series,i) { | |
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x()); | |
lines.highlightPoint(i, pointIndex, true); | |
var point = series.values[pointIndex]; | |
if (typeof point === 'undefined') return; | |
if (typeof singlePoint === 'undefined') singlePoint = point; | |
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex)); | |
allData.push({ | |
key: series.key, | |
value: chart.y()(point, pointIndex), | |
color: color(series,series.seriesIndex) | |
}); | |
}); | |
//Highlight the tooltip entry based on which point the mouse is closest to. | |
if (allData.length > 2) { | |
var yValue = chart.yScale().invert(e.mouseY); | |
var domainExtent = Math.abs(chart.yScale().domain()[0] - chart.yScale().domain()[1]); | |
var threshold = 0.03 * domainExtent; | |
var indexToHighlight = nv.nearestValueIndex(allData.map(function(d){return d.value}),yValue,threshold); | |
if (indexToHighlight !== null) | |
allData[indexToHighlight].highlight = true; | |
} | |
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex)); | |
interactiveLayer.tooltip | |
.position({left: pointXLocation + margin.left, top: e.mouseY + margin.top}) | |
.chartContainer(that.parentNode) | |
.enabled(tooltips) | |
.valueFormatter(function(d,i) { | |
return yAxis.tickFormat()(d); | |
}) | |
.data( | |
{ | |
value: xValue, | |
series: allData | |
} | |
)(); | |
interactiveLayer.renderGuideLine(pointXLocation); | |
}); | |
interactiveLayer.dispatch.on("elementMouseout",function(e) { | |
dispatch.tooltipHide(); | |
lines.clearHighlights(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
lines.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.lines = lines; | |
chart.legend = legend; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
chart.interactiveLayer = interactiveLayer; | |
d3.rebind(chart, lines, 'defined', 'isArea', 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'xRange', 'yRange' | |
, 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'useVoronoi','id', 'interpolate'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.useInteractiveGuideline = function(_) { | |
if(!arguments.length) return useInteractiveGuideline; | |
useInteractiveGuideline = _; | |
if (_ === true) { | |
chart.interactive(false); | |
chart.useVoronoi(false); | |
} | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.linePlusBarChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var lines = nv.models.line() | |
, bars = nv.models.historicalBar() | |
, xAxis = nv.models.axis() | |
, y1Axis = nv.models.axis() | |
, y2Axis = nv.models.axis() | |
, legend = nv.models.legend() | |
; | |
var margin = {top: 30, right: 60, bottom: 50, left: 60} | |
, width = null | |
, height = null | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, color = nv.utils.defaultColor() | |
, showLegend = true | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' at ' + x + '</p>'; | |
} | |
, x | |
, y1 | |
, y2 | |
, state = {} | |
, defaultState = null | |
, noData = "No Data Available." | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
; | |
bars | |
.padData(true) | |
; | |
lines | |
.clipEdge(false) | |
.padData(true) | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(7) | |
.highlightZero(false) | |
; | |
y1Axis | |
.orient('left') | |
; | |
y2Axis | |
.orient('right') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), | |
y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); | |
} | |
; | |
//------------------------------------------------------------ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().call(chart); }; | |
// chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
var dataBars = data.filter(function(d) { return !d.disabled && d.bar }); | |
var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240 | |
//x = xAxis.scale(); | |
x = dataLines.filter(function(d) { return !d.disabled; }).length && dataLines.filter(function(d) { return !d.disabled; })[0].values.length ? lines.xScale() : bars.xScale(); | |
//x = dataLines.filter(function(d) { return !d.disabled; }).length ? lines.xScale() : bars.xScale(); //old code before change above | |
y1 = bars.yScale(); | |
y2 = lines.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-linePlusBar').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y1 nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y2 nv-axis'); | |
gEnter.append('g').attr('class', 'nv-barsWrap'); | |
gEnter.append('g').attr('class', 'nv-linesWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width( availableWidth / 2 ); | |
g.select('.nv-legendWrap') | |
.datum(data.map(function(series) { | |
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; | |
series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)'); | |
return series; | |
})) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
g.select('.nv-legendWrap') | |
.attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
lines | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled && !data[i].bar })) | |
bars | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled && data[i].bar })) | |
var barsWrap = g.select('.nv-barsWrap') | |
.datum(dataBars.length ? dataBars : [{values:[]}]) | |
var linesWrap = g.select('.nv-linesWrap') | |
.datum(dataLines[0] && !dataLines[0].disabled ? dataLines : [{values:[]}] ); | |
//.datum(!dataLines[0].disabled ? dataLines : [{values:dataLines[0].values.map(function(d) { return [d[0], null] }) }] ); | |
d3.transition(barsWrap).call(bars); | |
d3.transition(linesWrap).call(lines); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
xAxis | |
.scale(x) | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight, 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y1.range()[0] + ')'); | |
d3.transition(g.select('.nv-x.nv-axis')) | |
.call(xAxis); | |
y1Axis | |
.scale(y1) | |
.ticks( availableHeight / 36 ) | |
.tickSize(-availableWidth, 0); | |
d3.transition(g.select('.nv-y1.nv-axis')) | |
.style('opacity', dataBars.length ? 1 : 0) | |
.call(y1Axis); | |
y2Axis | |
.scale(y2) | |
.ticks( availableHeight / 36 ) | |
.tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none | |
g.select('.nv-y2.nv-axis') | |
.style('opacity', dataLines.length ? 1 : 0) | |
.attr('transform', 'translate(' + availableWidth + ',0)'); | |
//.attr('transform', 'translate(' + x.range()[1] + ',0)'); | |
d3.transition(g.select('.nv-y2.nv-axis')) | |
.call(y2Axis); | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('stateChange', function(newState) { | |
state = newState; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
lines.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
bars.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
bars.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.legend = legend; | |
chart.lines = lines; | |
chart.bars = bars; | |
chart.xAxis = xAxis; | |
chart.y1Axis = y1Axis; | |
chart.y2Axis = y2Axis; | |
d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate'); | |
//TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc. | |
//d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
lines.x(_); | |
bars.x(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
lines.y(_); | |
bars.y(_); | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.lineWithFocusChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var lines = nv.models.line() | |
, lines2 = nv.models.line() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, x2Axis = nv.models.axis() | |
, y2Axis = nv.models.axis() | |
, legend = nv.models.legend() | |
, brush = d3.svg.brush() | |
; | |
var margin = {top: 30, right: 30, bottom: 30, left: 60} | |
, margin2 = {top: 0, right: 30, bottom: 20, left: 60} | |
, color = nv.utils.defaultColor() | |
, width = null | |
, height = null | |
, height2 = 100 | |
, x | |
, y | |
, x2 | |
, y2 | |
, showLegend = true | |
, brushExtent = null | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' at ' + x + '</p>' | |
} | |
, noData = "No Data Available." | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush') | |
, transitionDuration = 250 | |
; | |
lines | |
.clipEdge(true) | |
; | |
lines2 | |
.interactive(false) | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(5) | |
; | |
yAxis | |
.orient('left') | |
; | |
x2Axis | |
.orient('bottom') | |
.tickPadding(5) | |
; | |
y2Axis | |
.orient('left') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(lines.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, null, null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight1 = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom - height2, | |
availableHeight2 = height2 - margin2.top - margin2.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart) }; | |
chart.container = this; | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight1 / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = lines.xScale(); | |
y = lines.yScale(); | |
x2 = lines2.xScale(); | |
y2 = lines2.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-lineWithFocusChart').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-lineWithFocusChart').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
var focusEnter = gEnter.append('g').attr('class', 'nv-focus'); | |
focusEnter.append('g').attr('class', 'nv-x nv-axis'); | |
focusEnter.append('g').attr('class', 'nv-y nv-axis'); | |
focusEnter.append('g').attr('class', 'nv-linesWrap'); | |
var contextEnter = gEnter.append('g').attr('class', 'nv-context'); | |
contextEnter.append('g').attr('class', 'nv-x nv-axis'); | |
contextEnter.append('g').attr('class', 'nv-y nv-axis'); | |
contextEnter.append('g').attr('class', 'nv-linesWrap'); | |
contextEnter.append('g').attr('class', 'nv-brushBackground'); | |
contextEnter.append('g').attr('class', 'nv-x nv-brush'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width(availableWidth); | |
g.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight1 = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom - height2; | |
} | |
g.select('.nv-legendWrap') | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
lines | |
.width(availableWidth) | |
.height(availableHeight1) | |
.color( | |
data | |
.map(function(d,i) { | |
return d.color || color(d, i); | |
}) | |
.filter(function(d,i) { | |
return !data[i].disabled; | |
}) | |
); | |
lines2 | |
.defined(lines.defined()) | |
.width(availableWidth) | |
.height(availableHeight2) | |
.color( | |
data | |
.map(function(d,i) { | |
return d.color || color(d, i); | |
}) | |
.filter(function(d,i) { | |
return !data[i].disabled; | |
}) | |
); | |
g.select('.nv-context') | |
.attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')') | |
var contextLinesWrap = g.select('.nv-context .nv-linesWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
d3.transition(contextLinesWrap).call(lines2); | |
//------------------------------------------------------------ | |
/* | |
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
d3.transition(focusLinesWrap).call(lines); | |
*/ | |
//------------------------------------------------------------ | |
// Setup Main (Focus) Axes | |
xAxis | |
.scale(x) | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight1, 0); | |
yAxis | |
.scale(y) | |
.ticks( availableHeight1 / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-focus .nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + availableHeight1 + ')'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Brush | |
brush | |
.x(x2) | |
.on('brush', function() { | |
//When brushing, turn off transitions because chart needs to change immediately. | |
var oldTransition = chart.transitionDuration(); | |
chart.transitionDuration(0); | |
onBrush(); | |
chart.transitionDuration(oldTransition); | |
}); | |
if (brushExtent) brush.extent(brushExtent); | |
var brushBG = g.select('.nv-brushBackground').selectAll('g') | |
.data([brushExtent || brush.extent()]) | |
var brushBGenter = brushBG.enter() | |
.append('g'); | |
brushBGenter.append('rect') | |
.attr('class', 'left') | |
.attr('x', 0) | |
.attr('y', 0) | |
.attr('height', availableHeight2); | |
brushBGenter.append('rect') | |
.attr('class', 'right') | |
.attr('x', 0) | |
.attr('y', 0) | |
.attr('height', availableHeight2); | |
var gBrush = g.select('.nv-x.nv-brush') | |
.call(brush); | |
gBrush.selectAll('rect') | |
//.attr('y', -5) | |
.attr('height', availableHeight2); | |
gBrush.selectAll('.resize').append('path').attr('d', resizePath); | |
onBrush(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Secondary (Context) Axes | |
x2Axis | |
.scale(x2) | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight2, 0); | |
g.select('.nv-context .nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y2.range()[0] + ')'); | |
d3.transition(g.select('.nv-context .nv-x.nv-axis')) | |
.call(x2Axis); | |
y2Axis | |
.scale(y2) | |
.ticks( availableHeight2 / 36 ) | |
.tickSize( -availableWidth, 0); | |
d3.transition(g.select('.nv-context .nv-y.nv-axis')) | |
.call(y2Axis); | |
g.select('.nv-context .nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y2.range()[0] + ')'); | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('stateChange', function(newState) { | |
chart.update(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
//============================================================ | |
//============================================================ | |
// Functions | |
//------------------------------------------------------------ | |
// Taken from crossfilter (http://square.github.com/crossfilter/) | |
function resizePath(d) { | |
var e = +(d == 'e'), | |
x = e ? 1 : -1, | |
y = availableHeight2 / 3; | |
return 'M' + (.5 * x) + ',' + y | |
+ 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) | |
+ 'V' + (2 * y - 6) | |
+ 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y) | |
+ 'Z' | |
+ 'M' + (2.5 * x) + ',' + (y + 8) | |
+ 'V' + (2 * y - 8) | |
+ 'M' + (4.5 * x) + ',' + (y + 8) | |
+ 'V' + (2 * y - 8); | |
} | |
function updateBrushBG() { | |
if (!brush.empty()) brush.extent(brushExtent); | |
brushBG | |
.data([brush.empty() ? x2.domain() : brushExtent]) | |
.each(function(d,i) { | |
var leftWidth = x2(d[0]) - x.range()[0], | |
rightWidth = x.range()[1] - x2(d[1]); | |
d3.select(this).select('.left') | |
.attr('width', leftWidth < 0 ? 0 : leftWidth); | |
d3.select(this).select('.right') | |
.attr('x', x2(d[1])) | |
.attr('width', rightWidth < 0 ? 0 : rightWidth); | |
}); | |
} | |
function onBrush() { | |
brushExtent = brush.empty() ? null : brush.extent(); | |
var extent = brush.empty() ? x2.domain() : brush.extent(); | |
//The brush extent cannot be less than one. If it is, don't update the line chart. | |
if (Math.abs(extent[0] - extent[1]) <= 1) { | |
return; | |
} | |
dispatch.brush({extent: extent, brush: brush}); | |
updateBrushBG(); | |
// Update Main (Focus) | |
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') | |
.datum( | |
data | |
.filter(function(d) { return !d.disabled }) | |
.map(function(d,i) { | |
return { | |
key: d.key, | |
values: d.values.filter(function(d,i) { | |
return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1]; | |
}) | |
} | |
}) | |
); | |
focusLinesWrap.transition().duration(transitionDuration).call(lines); | |
// Update Main (Focus) Axes | |
g.select('.nv-focus .nv-x.nv-axis').transition().duration(transitionDuration) | |
.call(xAxis); | |
g.select('.nv-focus .nv-y.nv-axis').transition().duration(transitionDuration) | |
.call(yAxis); | |
} | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
lines.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.legend = legend; | |
chart.lines = lines; | |
chart.lines2 = lines2; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
chart.x2Axis = x2Axis; | |
chart.y2Axis = y2Axis; | |
d3.rebind(chart, lines, 'defined', 'isArea', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return lines.x; | |
lines.x(_); | |
lines2.x(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return lines.y; | |
lines.y(_); | |
lines2.y(_); | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.margin2 = function(_) { | |
if (!arguments.length) return margin2; | |
margin2 = _; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.height2 = function(_) { | |
if (!arguments.length) return height2; | |
height2 = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color =nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.interpolate = function(_) { | |
if (!arguments.length) return lines.interpolate(); | |
lines.interpolate(_); | |
lines2.interpolate(_); | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
// Chart has multiple similar Axes, to prevent code duplication, probably need to link all axis functions manually like below | |
chart.xTickFormat = function(_) { | |
if (!arguments.length) return xAxis.tickFormat(); | |
xAxis.tickFormat(_); | |
x2Axis.tickFormat(_); | |
return chart; | |
}; | |
chart.yTickFormat = function(_) { | |
if (!arguments.length) return yAxis.tickFormat(); | |
yAxis.tickFormat(_); | |
y2Axis.tickFormat(_); | |
return chart; | |
}; | |
chart.brushExtent = function(_) { | |
if (!arguments.length) return brushExtent; | |
brushExtent = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.linePlusBarWithFocusChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var lines = nv.models.line() | |
, lines2 = nv.models.line() | |
, bars = nv.models.historicalBar() | |
, bars2 = nv.models.historicalBar() | |
, xAxis = nv.models.axis() | |
, x2Axis = nv.models.axis() | |
, y1Axis = nv.models.axis() | |
, y2Axis = nv.models.axis() | |
, y3Axis = nv.models.axis() | |
, y4Axis = nv.models.axis() | |
, legend = nv.models.legend() | |
, brush = d3.svg.brush() | |
; | |
var margin = {top: 30, right: 30, bottom: 30, left: 60} | |
, margin2 = {top: 0, right: 30, bottom: 20, left: 60} | |
, width = null | |
, height = null | |
, height2 = 100 | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, color = nv.utils.defaultColor() | |
, showLegend = true | |
, extent | |
, brushExtent = null | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' at ' + x + '</p>'; | |
} | |
, x | |
, x2 | |
, y1 | |
, y2 | |
, y3 | |
, y4 | |
, noData = "No Data Available." | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'brush') | |
, transitionDuration = 0 | |
; | |
lines | |
.clipEdge(true) | |
; | |
lines2 | |
.interactive(false) | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(5) | |
; | |
y1Axis | |
.orient('left') | |
; | |
y2Axis | |
.orient('right') | |
; | |
x2Axis | |
.orient('bottom') | |
.tickPadding(5) | |
; | |
y3Axis | |
.orient('left') | |
; | |
y4Axis | |
.orient('right') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
if (extent) { | |
e.pointIndex += Math.ceil(extent[0]); | |
} | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(lines.x()(e.point, e.pointIndex)), | |
y = (e.series.bar ? y1Axis : y2Axis).tickFormat()(lines.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); | |
}; | |
//------------------------------------------------------------ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight1 = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom - height2, | |
availableHeight2 = height2 - margin2.top - margin2.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart); }; | |
chart.container = this; | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight1 / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
var dataBars = data.filter(function(d) { return !d.disabled && d.bar }); | |
var dataLines = data.filter(function(d) { return !d.bar }); // removed the !d.disabled clause here to fix Issue #240 | |
x = bars.xScale(); | |
x2 = x2Axis.scale(); | |
y1 = bars.yScale(); | |
y2 = lines.yScale(); | |
y3 = bars2.yScale(); | |
y4 = lines2.yScale(); | |
var series1 = data | |
.filter(function(d) { return !d.disabled && d.bar }) | |
.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: getX(d,i), y: getY(d,i) } | |
}) | |
}); | |
var series2 = data | |
.filter(function(d) { return !d.disabled && !d.bar }) | |
.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: getX(d,i), y: getY(d,i) } | |
}) | |
}); | |
x .range([0, availableWidth]); | |
x2 .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } )) | |
.range([0, availableWidth]); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-linePlusBar').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-linePlusBar').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
var focusEnter = gEnter.append('g').attr('class', 'nv-focus'); | |
focusEnter.append('g').attr('class', 'nv-x nv-axis'); | |
focusEnter.append('g').attr('class', 'nv-y1 nv-axis'); | |
focusEnter.append('g').attr('class', 'nv-y2 nv-axis'); | |
focusEnter.append('g').attr('class', 'nv-barsWrap'); | |
focusEnter.append('g').attr('class', 'nv-linesWrap'); | |
var contextEnter = gEnter.append('g').attr('class', 'nv-context'); | |
contextEnter.append('g').attr('class', 'nv-x nv-axis'); | |
contextEnter.append('g').attr('class', 'nv-y1 nv-axis'); | |
contextEnter.append('g').attr('class', 'nv-y2 nv-axis'); | |
contextEnter.append('g').attr('class', 'nv-barsWrap'); | |
contextEnter.append('g').attr('class', 'nv-linesWrap'); | |
contextEnter.append('g').attr('class', 'nv-brushBackground'); | |
contextEnter.append('g').attr('class', 'nv-x nv-brush'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width( availableWidth / 2 ); | |
g.select('.nv-legendWrap') | |
.datum(data.map(function(series) { | |
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; | |
series.key = series.originalKey + (series.bar ? ' (left axis)' : ' (right axis)'); | |
return series; | |
})) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight1 = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom - height2; | |
} | |
g.select('.nv-legendWrap') | |
.attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
// Context Components | |
bars2 | |
.width(availableWidth) | |
.height(availableHeight2) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled && data[i].bar })); | |
lines2 | |
.width(availableWidth) | |
.height(availableHeight2) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled && !data[i].bar })); | |
var bars2Wrap = g.select('.nv-context .nv-barsWrap') | |
.datum(dataBars.length ? dataBars : [{values:[]}]); | |
var lines2Wrap = g.select('.nv-context .nv-linesWrap') | |
.datum(!dataLines[0].disabled ? dataLines : [{values:[]}]); | |
g.select('.nv-context') | |
.attr('transform', 'translate(0,' + ( availableHeight1 + margin.bottom + margin2.top) + ')') | |
bars2Wrap.transition().call(bars2); | |
lines2Wrap.transition().call(lines2); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Brush | |
brush | |
.x(x2) | |
.on('brush', onBrush); | |
if (brushExtent) brush.extent(brushExtent); | |
var brushBG = g.select('.nv-brushBackground').selectAll('g') | |
.data([brushExtent || brush.extent()]) | |
var brushBGenter = brushBG.enter() | |
.append('g'); | |
brushBGenter.append('rect') | |
.attr('class', 'left') | |
.attr('x', 0) | |
.attr('y', 0) | |
.attr('height', availableHeight2); | |
brushBGenter.append('rect') | |
.attr('class', 'right') | |
.attr('x', 0) | |
.attr('y', 0) | |
.attr('height', availableHeight2); | |
var gBrush = g.select('.nv-x.nv-brush') | |
.call(brush); | |
gBrush.selectAll('rect') | |
//.attr('y', -5) | |
.attr('height', availableHeight2); | |
gBrush.selectAll('.resize').append('path').attr('d', resizePath); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Secondary (Context) Axes | |
x2Axis | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight2, 0); | |
g.select('.nv-context .nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y3.range()[0] + ')'); | |
g.select('.nv-context .nv-x.nv-axis').transition() | |
.call(x2Axis); | |
y3Axis | |
.scale(y3) | |
.ticks( availableHeight2 / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-context .nv-y1.nv-axis') | |
.style('opacity', dataBars.length ? 1 : 0) | |
.attr('transform', 'translate(0,' + x2.range()[0] + ')'); | |
g.select('.nv-context .nv-y1.nv-axis').transition() | |
.call(y3Axis); | |
y4Axis | |
.scale(y4) | |
.ticks( availableHeight2 / 36 ) | |
.tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none | |
g.select('.nv-context .nv-y2.nv-axis') | |
.style('opacity', dataLines.length ? 1 : 0) | |
.attr('transform', 'translate(' + x2.range()[1] + ',0)'); | |
g.select('.nv-context .nv-y2.nv-axis').transition() | |
.call(y4Axis); | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('stateChange', function(newState) { | |
chart.update(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
//============================================================ | |
//============================================================ | |
// Functions | |
//------------------------------------------------------------ | |
// Taken from crossfilter (http://square.github.com/crossfilter/) | |
function resizePath(d) { | |
var e = +(d == 'e'), | |
x = e ? 1 : -1, | |
y = availableHeight2 / 3; | |
return 'M' + (.5 * x) + ',' + y | |
+ 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) | |
+ 'V' + (2 * y - 6) | |
+ 'A6,6 0 0 ' + e + ' ' + (.5 * x) + ',' + (2 * y) | |
+ 'Z' | |
+ 'M' + (2.5 * x) + ',' + (y + 8) | |
+ 'V' + (2 * y - 8) | |
+ 'M' + (4.5 * x) + ',' + (y + 8) | |
+ 'V' + (2 * y - 8); | |
} | |
function updateBrushBG() { | |
if (!brush.empty()) brush.extent(brushExtent); | |
brushBG | |
.data([brush.empty() ? x2.domain() : brushExtent]) | |
.each(function(d,i) { | |
var leftWidth = x2(d[0]) - x2.range()[0], | |
rightWidth = x2.range()[1] - x2(d[1]); | |
d3.select(this).select('.left') | |
.attr('width', leftWidth < 0 ? 0 : leftWidth); | |
d3.select(this).select('.right') | |
.attr('x', x2(d[1])) | |
.attr('width', rightWidth < 0 ? 0 : rightWidth); | |
}); | |
} | |
function onBrush() { | |
brushExtent = brush.empty() ? null : brush.extent(); | |
extent = brush.empty() ? x2.domain() : brush.extent(); | |
dispatch.brush({extent: extent, brush: brush}); | |
updateBrushBG(); | |
//------------------------------------------------------------ | |
// Prepare Main (Focus) Bars and Lines | |
bars | |
.width(availableWidth) | |
.height(availableHeight1) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled && data[i].bar })); | |
lines | |
.width(availableWidth) | |
.height(availableHeight1) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled && !data[i].bar })); | |
var focusBarsWrap = g.select('.nv-focus .nv-barsWrap') | |
.datum(!dataBars.length ? [{values:[]}] : | |
dataBars | |
.map(function(d,i) { | |
return { | |
key: d.key, | |
values: d.values.filter(function(d,i) { | |
return bars.x()(d,i) >= extent[0] && bars.x()(d,i) <= extent[1]; | |
}) | |
} | |
}) | |
); | |
var focusLinesWrap = g.select('.nv-focus .nv-linesWrap') | |
.datum(dataLines[0].disabled ? [{values:[]}] : | |
dataLines | |
.map(function(d,i) { | |
return { | |
key: d.key, | |
values: d.values.filter(function(d,i) { | |
return lines.x()(d,i) >= extent[0] && lines.x()(d,i) <= extent[1]; | |
}) | |
} | |
}) | |
); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Update Main (Focus) X Axis | |
if (dataBars.length) { | |
x = bars.xScale(); | |
} else { | |
x = lines.xScale(); | |
} | |
xAxis | |
.scale(x) | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight1, 0); | |
xAxis.domain([Math.ceil(extent[0]), Math.floor(extent[1])]); | |
g.select('.nv-x.nv-axis').transition().duration(transitionDuration) | |
.call(xAxis); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Update Main (Focus) Bars and Lines | |
focusBarsWrap.transition().duration(transitionDuration).call(bars); | |
focusLinesWrap.transition().duration(transitionDuration).call(lines); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup and Update Main (Focus) Y Axes | |
g.select('.nv-focus .nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y1.range()[0] + ')'); | |
y1Axis | |
.scale(y1) | |
.ticks( availableHeight1 / 36 ) | |
.tickSize(-availableWidth, 0); | |
g.select('.nv-focus .nv-y1.nv-axis') | |
.style('opacity', dataBars.length ? 1 : 0); | |
y2Axis | |
.scale(y2) | |
.ticks( availableHeight1 / 36 ) | |
.tickSize(dataBars.length ? 0 : -availableWidth, 0); // Show the y2 rules only if y1 has none | |
g.select('.nv-focus .nv-y2.nv-axis') | |
.style('opacity', dataLines.length ? 1 : 0) | |
.attr('transform', 'translate(' + x.range()[1] + ',0)'); | |
g.select('.nv-focus .nv-y1.nv-axis').transition().duration(transitionDuration) | |
.call(y1Axis); | |
g.select('.nv-focus .nv-y2.nv-axis').transition().duration(transitionDuration) | |
.call(y2Axis); | |
} | |
//============================================================ | |
onBrush(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
lines.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
bars.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
bars.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.legend = legend; | |
chart.lines = lines; | |
chart.lines2 = lines2; | |
chart.bars = bars; | |
chart.bars2 = bars2; | |
chart.xAxis = xAxis; | |
chart.x2Axis = x2Axis; | |
chart.y1Axis = y1Axis; | |
chart.y2Axis = y2Axis; | |
chart.y3Axis = y3Axis; | |
chart.y4Axis = y4Axis; | |
d3.rebind(chart, lines, 'defined', 'size', 'clipVoronoi', 'interpolate'); | |
//TODO: consider rebinding x, y and some other stuff, and simply do soemthign lile bars.x(lines.x()), etc. | |
//d3.rebind(chart, lines, 'x', 'y', 'size', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'interactive', 'clipEdge', 'clipVoronoi', 'id'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
lines.x(_); | |
bars.x(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
lines.y(_); | |
bars.y(_); | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.brushExtent = function(_) { | |
if (!arguments.length) return brushExtent; | |
brushExtent = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.multiBar = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, x = d3.scale.ordinal() | |
, y = d3.scale.linear() | |
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove | |
, clipEdge = true | |
, stacked = false | |
, stackOffset = 'zero' // options include 'silhouette', 'wiggle', 'expand', 'zero', or a custom function | |
, color = nv.utils.defaultColor() | |
, hideable = false | |
, barColor = null // adding the ability to set the color for each rather than the whole group | |
, disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled | |
, delay = 1200 | |
, xDomain | |
, yDomain | |
, xRange | |
, yRange | |
, groupSpacing = 0.1 | |
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x0, y0 //used to store previous scales | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
if(hideable && data.length) hideable = [{ | |
values: data[0].values.map(function(d) { | |
return { | |
x: d.x, | |
y: 0, | |
series: d.series, | |
size: 0.01 | |
};} | |
)}]; | |
if (stacked) | |
data = d3.layout.stack() | |
.offset(stackOffset) | |
.values(function(d){ return d.values }) | |
.y(getY) | |
(!data.length && hideable ? hideable : data); | |
//add series index to each data point for reference | |
data.forEach(function(series, i) { | |
series.values.forEach(function(point) { | |
point.series = i; | |
}); | |
}); | |
//------------------------------------------------------------ | |
// HACK for negative value stacking | |
if (stacked) | |
data[0].values.map(function(d,i) { | |
var posBase = 0, negBase = 0; | |
data.map(function(d) { | |
var f = d.values[i] | |
f.size = Math.abs(f.y); | |
if (f.y<0) { | |
f.y1 = negBase; | |
negBase = negBase - f.size; | |
} else | |
{ | |
f.y1 = f.size + posBase; | |
posBase = posBase + f.size; | |
} | |
}); | |
}); | |
//------------------------------------------------------------ | |
// Setup Scales | |
// remap and flatten the data for use in calculating the scales' domains | |
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate | |
data.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 } | |
}) | |
}); | |
x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x })) | |
.rangeBands(xRange || [0, availableWidth], groupSpacing); | |
//y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y1 : 0) }).concat(forceY))) | |
y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 : d.y1 + d.y ) : d.y }).concat(forceY))) | |
.range(yRange || [availableHeight, 0]); | |
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point | |
if (x.domain()[0] === x.domain()[1]) | |
x.domain()[0] ? | |
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) | |
: x.domain([-1,1]); | |
if (y.domain()[0] === y.domain()[1]) | |
y.domain()[0] ? | |
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) | |
: y.domain([-1,1]); | |
x0 = x0 || x; | |
y0 = y0 || y; | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-multibar').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibar'); | |
var defsEnter = wrapEnter.append('defs'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g') | |
gEnter.append('g').attr('class', 'nv-groups'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
defsEnter.append('clipPath') | |
.attr('id', 'nv-edge-clip-' + id) | |
.append('rect'); | |
wrap.select('#nv-edge-clip-' + id + ' rect') | |
.attr('width', availableWidth) | |
.attr('height', availableHeight); | |
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); | |
var groups = wrap.select('.nv-groups').selectAll('.nv-group') | |
.data(function(d) { return d }, function(d,i) { return i }); | |
groups.enter().append('g') | |
.style('stroke-opacity', 1e-6) | |
.style('fill-opacity', 1e-6); | |
groups.exit() | |
.transition() | |
.selectAll('rect.nv-bar') | |
.delay(function(d,i) { | |
return i * delay/ data[0].values.length; | |
}) | |
.attr('y', function(d) { return stacked ? y0(d.y0) : y0(0) }) | |
.attr('height', 0) | |
.remove(); | |
groups | |
.attr('class', function(d,i) { return 'nv-group nv-series-' + i }) | |
.classed('hover', function(d) { return d.hover }) | |
.style('fill', function(d,i){ return color(d, i) }) | |
.style('stroke', function(d,i){ return color(d, i) }); | |
groups | |
.transition() | |
.style('stroke-opacity', 1) | |
.style('fill-opacity', .75); | |
var bars = groups.selectAll('rect.nv-bar') | |
.data(function(d) { return (hideable && !data.length) ? hideable.values : d.values }); | |
bars.exit().remove(); | |
var barsEnter = bars.enter().append('rect') | |
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) | |
.attr('x', function(d,i,j) { | |
return stacked ? 0 : (j * x.rangeBand() / data.length ) | |
}) | |
.attr('y', function(d) { return y0(stacked ? d.y0 : 0) }) | |
.attr('height', 0) | |
.attr('width', x.rangeBand() / (stacked ? 1 : data.length) ) | |
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; }) | |
; | |
bars | |
.style('fill', function(d,i,j){ return color(d, j, i); }) | |
.style('stroke', function(d,i,j){ return color(d, j, i); }) | |
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here | |
d3.select(this).classed('hover', true); | |
dispatch.elementMouseover({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
}) | |
.on('mouseout', function(d,i) { | |
d3.select(this).classed('hover', false); | |
dispatch.elementMouseout({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
}) | |
.on('click', function(d,i) { | |
dispatch.elementClick({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
d3.event.stopPropagation(); | |
}) | |
.on('dblclick', function(d,i) { | |
dispatch.elementDblClick({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
d3.event.stopPropagation(); | |
}); | |
bars | |
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) | |
.transition() | |
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',0)'; }) | |
if (barColor) { | |
if (!disabled) disabled = data.map(function() { return true }); | |
bars | |
.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }) | |
.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }); | |
} | |
if (stacked) | |
bars.transition() | |
.delay(function(d,i) { | |
return i * delay / data[0].values.length; | |
}) | |
.attr('y', function(d,i) { | |
return y((stacked ? d.y1 : 0)); | |
}) | |
.attr('height', function(d,i) { | |
return Math.max(Math.abs(y(d.y + (stacked ? d.y0 : 0)) - y((stacked ? d.y0 : 0))),1); | |
}) | |
.attr('x', function(d,i) { | |
return stacked ? 0 : (d.series * x.rangeBand() / data.length ) | |
}) | |
.attr('width', x.rangeBand() / (stacked ? 1 : data.length) ); | |
else | |
bars.transition() | |
.delay(function(d,i) { | |
return i * delay/ data[0].values.length; | |
}) | |
.attr('x', function(d,i) { | |
return d.series * x.rangeBand() / data.length | |
}) | |
.attr('width', x.rangeBand() / data.length) | |
.attr('y', function(d,i) { | |
return getY(d,i) < 0 ? | |
y(0) : | |
y(0) - y(getY(d,i)) < 1 ? | |
y(0) - 1 : | |
y(getY(d,i)) || 0; | |
}) | |
.attr('height', function(d,i) { | |
return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) || 0; | |
}); | |
//store old scales for use in transitions on update | |
x0 = x.copy(); | |
y0 = y.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.xScale = function(_) { | |
if (!arguments.length) return x; | |
x = _; | |
return chart; | |
}; | |
chart.yScale = function(_) { | |
if (!arguments.length) return y; | |
y = _; | |
return chart; | |
}; | |
chart.xDomain = function(_) { | |
if (!arguments.length) return xDomain; | |
xDomain = _; | |
return chart; | |
}; | |
chart.yDomain = function(_) { | |
if (!arguments.length) return yDomain; | |
yDomain = _; | |
return chart; | |
}; | |
chart.xRange = function(_) { | |
if (!arguments.length) return xRange; | |
xRange = _; | |
return chart; | |
}; | |
chart.yRange = function(_) { | |
if (!arguments.length) return yRange; | |
yRange = _; | |
return chart; | |
}; | |
chart.forceY = function(_) { | |
if (!arguments.length) return forceY; | |
forceY = _; | |
return chart; | |
}; | |
chart.stacked = function(_) { | |
if (!arguments.length) return stacked; | |
stacked = _; | |
return chart; | |
}; | |
chart.stackOffset = function(_) { | |
if (!arguments.length) return stackOffset; | |
stackOffset = _; | |
return chart; | |
}; | |
chart.clipEdge = function(_) { | |
if (!arguments.length) return clipEdge; | |
clipEdge = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.barColor = function(_) { | |
if (!arguments.length) return barColor; | |
barColor = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.disabled = function(_) { | |
if (!arguments.length) return disabled; | |
disabled = _; | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
chart.hideable = function(_) { | |
if (!arguments.length) return hideable; | |
hideable = _; | |
return chart; | |
}; | |
chart.delay = function(_) { | |
if (!arguments.length) return delay; | |
delay = _; | |
return chart; | |
}; | |
chart.groupSpacing = function(_) { | |
if (!arguments.length) return groupSpacing; | |
groupSpacing = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.multiBarChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var multibar = nv.models.multiBar() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend() | |
, controls = nv.models.legend() | |
; | |
var margin = {top: 30, right: 20, bottom: 50, left: 60} | |
, width = null | |
, height = null | |
, color = nv.utils.defaultColor() | |
, showControls = true | |
, showLegend = true | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, reduceXTicks = true // if false a tick will show for every data point | |
, staggerLabels = false | |
, rotateLabels = 0 | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' on ' + x + '</p>' | |
} | |
, x //can be accessed via chart.xScale() | |
, y //can be accessed via chart.yScale() | |
, state = { stacked: false } | |
, defaultState = null | |
, noData = "No Data Available." | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, controlWidth = function() { return showControls ? 180 : 0 } | |
, transitionDuration = 250 | |
; | |
multibar | |
.stacked(false) | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(7) | |
.highlightZero(true) | |
.showMaxMin(false) | |
.tickFormat(function(d) { return d }) | |
; | |
yAxis | |
.orient((rightAlignYAxis) ? 'right' : 'left') | |
.tickFormat(d3.format(',.1f')) | |
; | |
controls.updateState(false); | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart) }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display noData message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = multibar.xScale(); | |
y = multibar.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-multiBarWithLegend').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarWithLegend').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis'); | |
gEnter.append('g').attr('class', 'nv-barsWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
gEnter.append('g').attr('class', 'nv-controlsWrap'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width(availableWidth - controlWidth()); | |
if (multibar.barColor()) | |
data.forEach(function(series,i) { | |
series.color = d3.rgb('#ccc').darker(i * 1.5).toString(); | |
}) | |
g.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
g.select('.nv-legendWrap') | |
.attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Controls | |
if (showControls) { | |
var controlsData = [ | |
{ key: 'Grouped', disabled: multibar.stacked() }, | |
{ key: 'Stacked', disabled: !multibar.stacked() } | |
]; | |
controls.width(controlWidth()).color(['#444', '#444', '#444']); | |
g.select('.nv-controlsWrap') | |
.datum(controlsData) | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
.call(controls); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
multibar | |
.disabled(data.map(function(series) { return series.disabled })) | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })) | |
var barsWrap = g.select('.nv-barsWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
barsWrap.transition().call(multibar); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight, 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')'); | |
g.select('.nv-x.nv-axis').transition() | |
.call(xAxis); | |
var xTicks = g.select('.nv-x.nv-axis > g').selectAll('g'); | |
xTicks | |
.selectAll('line, text') | |
.style('opacity', 1) | |
if (staggerLabels) { | |
var getTranslate = function(x,y) { | |
return "translate(" + x + "," + y + ")"; | |
}; | |
var staggerUp = 5, staggerDown = 17; //pixels to stagger by | |
// Issue #140 | |
xTicks | |
.selectAll("text") | |
.attr('transform', function(d,i,j) { | |
return getTranslate(0, (j % 2 == 0 ? staggerUp : staggerDown)); | |
}); | |
var totalInBetweenTicks = d3.selectAll(".nv-x.nv-axis .nv-wrap g g text")[0].length; | |
g.selectAll(".nv-x.nv-axis .nv-axisMaxMin text") | |
.attr("transform", function(d,i) { | |
return getTranslate(0, (i === 0 || totalInBetweenTicks % 2 !== 0) ? staggerDown : staggerUp); | |
}); | |
} | |
if (reduceXTicks) | |
xTicks | |
.filter(function(d,i) { | |
return i % Math.ceil(data[0].values.length / (availableWidth / 100)) !== 0; | |
}) | |
.selectAll('text, line') | |
.style('opacity', 0); | |
if(rotateLabels) | |
xTicks | |
.selectAll('.tick text') | |
.attr('transform', 'rotate(' + rotateLabels + ' 0,0)') | |
.style('text-anchor', rotateLabels > 0 ? 'start' : 'end'); | |
g.select('.nv-x.nv-axis').selectAll('g.nv-axisMaxMin text') | |
.style('opacity', 1); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-y.nv-axis').transition() | |
.call(yAxis); | |
} | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('stateChange', function(newState) { | |
state = newState; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
controls.dispatch.on('legendClick', function(d,i) { | |
if (!d.disabled) return; | |
controlsData = controlsData.map(function(s) { | |
s.disabled = true; | |
return s; | |
}); | |
d.disabled = false; | |
switch (d.key) { | |
case 'Grouped': | |
multibar.stacked(false); | |
break; | |
case 'Stacked': | |
multibar.stacked(true); | |
break; | |
} | |
state.stacked = multibar.stacked(); | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode) | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
if (typeof e.stacked !== 'undefined') { | |
multibar.stacked(e.stacked); | |
state.stacked = e.stacked; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
multibar.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
multibar.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.multibar = multibar; | |
chart.legend = legend; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', 'clipEdge', | |
'id', 'stacked', 'stackOffset', 'delay', 'barColor','groupSpacing'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.showControls = function(_) { | |
if (!arguments.length) return showControls; | |
showControls = _; | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.reduceXTicks= function(_) { | |
if (!arguments.length) return reduceXTicks; | |
reduceXTicks = _; | |
return chart; | |
}; | |
chart.rotateLabels = function(_) { | |
if (!arguments.length) return rotateLabels; | |
rotateLabels = _; | |
return chart; | |
} | |
chart.staggerLabels = function(_) { | |
if (!arguments.length) return staggerLabels; | |
staggerLabels = _; | |
return chart; | |
}; | |
chart.tooltip = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.multiBarHorizontal = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one | |
, x = d3.scale.ordinal() | |
, y = d3.scale.linear() | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, forceY = [0] // 0 is forced by default.. this makes sense for the majority of bar graphs... user can always do chart.forceY([]) to remove | |
, color = nv.utils.defaultColor() | |
, barColor = null // adding the ability to set the color for each rather than the whole group | |
, disabled // used in conjunction with barColor to communicate from multiBarHorizontalChart what series are disabled | |
, stacked = false | |
, showValues = false | |
, showBarLabels = false | |
, valuePadding = 60 | |
, valueFormat = d3.format(',.2f') | |
, delay = 1200 | |
, xDomain | |
, yDomain | |
, xRange | |
, yRange | |
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x0, y0 //used to store previous scales | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
if (stacked) | |
data = d3.layout.stack() | |
.offset('zero') | |
.values(function(d){ return d.values }) | |
.y(getY) | |
(data); | |
//add series index to each data point for reference | |
data.forEach(function(series, i) { | |
series.values.forEach(function(point) { | |
point.series = i; | |
}); | |
}); | |
//------------------------------------------------------------ | |
// HACK for negative value stacking | |
if (stacked) | |
data[0].values.map(function(d,i) { | |
var posBase = 0, negBase = 0; | |
data.map(function(d) { | |
var f = d.values[i] | |
f.size = Math.abs(f.y); | |
if (f.y<0) { | |
f.y1 = negBase - f.size; | |
negBase = negBase - f.size; | |
} else | |
{ | |
f.y1 = posBase; | |
posBase = posBase + f.size; | |
} | |
}); | |
}); | |
//------------------------------------------------------------ | |
// Setup Scales | |
// remap and flatten the data for use in calculating the scales' domains | |
var seriesData = (xDomain && yDomain) ? [] : // if we know xDomain and yDomain, no need to calculate | |
data.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: getX(d,i), y: getY(d,i), y0: d.y0, y1: d.y1 } | |
}) | |
}); | |
x .domain(xDomain || d3.merge(seriesData).map(function(d) { return d.x })) | |
.rangeBands(xRange || [0, availableHeight], .1); | |
//y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return d.y + (stacked ? d.y0 : 0) }).concat(forceY))) | |
y .domain(yDomain || d3.extent(d3.merge(seriesData).map(function(d) { return stacked ? (d.y > 0 ? d.y1 + d.y : d.y1 ) : d.y }).concat(forceY))) | |
if (showValues && !stacked) | |
y.range(yRange || [(y.domain()[0] < 0 ? valuePadding : 0), availableWidth - (y.domain()[1] > 0 ? valuePadding : 0) ]); | |
else | |
y.range(yRange || [0, availableWidth]); | |
x0 = x0 || x; | |
y0 = y0 || d3.scale.linear().domain(y.domain()).range([y(0),y(0)]); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-multibarHorizontal').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multibarHorizontal'); | |
var defsEnter = wrapEnter.append('defs'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-groups'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
var groups = wrap.select('.nv-groups').selectAll('.nv-group') | |
.data(function(d) { return d }, function(d,i) { return i }); | |
groups.enter().append('g') | |
.style('stroke-opacity', 1e-6) | |
.style('fill-opacity', 1e-6); | |
groups.exit().transition() | |
.style('stroke-opacity', 1e-6) | |
.style('fill-opacity', 1e-6) | |
.remove(); | |
groups | |
.attr('class', function(d,i) { return 'nv-group nv-series-' + i }) | |
.classed('hover', function(d) { return d.hover }) | |
.style('fill', function(d,i){ return color(d, i) }) | |
.style('stroke', function(d,i){ return color(d, i) }); | |
groups.transition() | |
.style('stroke-opacity', 1) | |
.style('fill-opacity', .75); | |
var bars = groups.selectAll('g.nv-bar') | |
.data(function(d) { return d.values }); | |
bars.exit().remove(); | |
var barsEnter = bars.enter().append('g') | |
.attr('transform', function(d,i,j) { | |
return 'translate(' + y0(stacked ? d.y0 : 0) + ',' + (stacked ? 0 : (j * x.rangeBand() / data.length ) + x(getX(d,i))) + ')' | |
}); | |
barsEnter.append('rect') | |
.attr('width', 0) | |
.attr('height', x.rangeBand() / (stacked ? 1 : data.length) ) | |
bars | |
.on('mouseover', function(d,i) { //TODO: figure out why j works above, but not here | |
d3.select(this).classed('hover', true); | |
dispatch.elementMouseover({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [ y(getY(d,i) + (stacked ? d.y0 : 0)), x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length) ], | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
}) | |
.on('mouseout', function(d,i) { | |
d3.select(this).classed('hover', false); | |
dispatch.elementMouseout({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
}) | |
.on('click', function(d,i) { | |
dispatch.elementClick({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
d3.event.stopPropagation(); | |
}) | |
.on('dblclick', function(d,i) { | |
dispatch.elementDblClick({ | |
value: getY(d,i), | |
point: d, | |
series: data[d.series], | |
pos: [x(getX(d,i)) + (x.rangeBand() * (stacked ? data.length / 2 : d.series + .5) / data.length), y(getY(d,i) + (stacked ? d.y0 : 0))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: d.series, | |
e: d3.event | |
}); | |
d3.event.stopPropagation(); | |
}); | |
barsEnter.append('text'); | |
if (showValues && !stacked) { | |
bars.select('text') | |
.attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'end' : 'start' }) | |
.attr('y', x.rangeBand() / (data.length * 2)) | |
.attr('dy', '.32em') | |
.text(function(d,i) { return valueFormat(getY(d,i)) }) | |
bars.transition() | |
.select('text') | |
.attr('x', function(d,i) { return getY(d,i) < 0 ? -4 : y(getY(d,i)) - y(0) + 4 }) | |
} else { | |
bars.selectAll('text').text(''); | |
} | |
if (showBarLabels && !stacked) { | |
barsEnter.append('text').classed('nv-bar-label',true); | |
bars.select('text.nv-bar-label') | |
.attr('text-anchor', function(d,i) { return getY(d,i) < 0 ? 'start' : 'end' }) | |
.attr('y', x.rangeBand() / (data.length * 2)) | |
.attr('dy', '.32em') | |
.text(function(d,i) { return getX(d,i) }); | |
bars.transition() | |
.select('text.nv-bar-label') | |
.attr('x', function(d,i) { return getY(d,i) < 0 ? y(0) - y(getY(d,i)) + 4 : -4 }); | |
} | |
else { | |
bars.selectAll('text.nv-bar-label').text(''); | |
} | |
bars | |
.attr('class', function(d,i) { return getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive'}) | |
if (barColor) { | |
if (!disabled) disabled = data.map(function() { return true }); | |
bars | |
.style('fill', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }) | |
.style('stroke', function(d,i,j) { return d3.rgb(barColor(d,i)).darker( disabled.map(function(d,i) { return i }).filter(function(d,i){ return !disabled[i] })[j] ).toString(); }); | |
} | |
if (stacked) | |
bars.transition() | |
.attr('transform', function(d,i) { | |
return 'translate(' + y(d.y1) + ',' + x(getX(d,i)) + ')' | |
}) | |
.select('rect') | |
.attr('width', function(d,i) { | |
return Math.abs(y(getY(d,i) + d.y0) - y(d.y0)) | |
}) | |
.attr('height', x.rangeBand() ); | |
else | |
bars.transition() | |
.attr('transform', function(d,i) { | |
//TODO: stacked must be all positive or all negative, not both? | |
return 'translate(' + | |
(getY(d,i) < 0 ? y(getY(d,i)) : y(0)) | |
+ ',' + | |
(d.series * x.rangeBand() / data.length | |
+ | |
x(getX(d,i)) ) | |
+ ')' | |
}) | |
.select('rect') | |
.attr('height', x.rangeBand() / data.length ) | |
.attr('width', function(d,i) { | |
return Math.max(Math.abs(y(getY(d,i)) - y(0)),1) | |
}); | |
//store old scales for use in transitions on update | |
x0 = x.copy(); | |
y0 = y.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.xScale = function(_) { | |
if (!arguments.length) return x; | |
x = _; | |
return chart; | |
}; | |
chart.yScale = function(_) { | |
if (!arguments.length) return y; | |
y = _; | |
return chart; | |
}; | |
chart.xDomain = function(_) { | |
if (!arguments.length) return xDomain; | |
xDomain = _; | |
return chart; | |
}; | |
chart.yDomain = function(_) { | |
if (!arguments.length) return yDomain; | |
yDomain = _; | |
return chart; | |
}; | |
chart.xRange = function(_) { | |
if (!arguments.length) return xRange; | |
xRange = _; | |
return chart; | |
}; | |
chart.yRange = function(_) { | |
if (!arguments.length) return yRange; | |
yRange = _; | |
return chart; | |
}; | |
chart.forceY = function(_) { | |
if (!arguments.length) return forceY; | |
forceY = _; | |
return chart; | |
}; | |
chart.stacked = function(_) { | |
if (!arguments.length) return stacked; | |
stacked = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.barColor = function(_) { | |
if (!arguments.length) return barColor; | |
barColor = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.disabled = function(_) { | |
if (!arguments.length) return disabled; | |
disabled = _; | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
chart.delay = function(_) { | |
if (!arguments.length) return delay; | |
delay = _; | |
return chart; | |
}; | |
chart.showValues = function(_) { | |
if (!arguments.length) return showValues; | |
showValues = _; | |
return chart; | |
}; | |
chart.showBarLabels = function(_) { | |
if (!arguments.length) return showBarLabels; | |
showBarLabels = _; | |
return chart; | |
}; | |
chart.valueFormat= function(_) { | |
if (!arguments.length) return valueFormat; | |
valueFormat = _; | |
return chart; | |
}; | |
chart.valuePadding = function(_) { | |
if (!arguments.length) return valuePadding; | |
valuePadding = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.multiBarHorizontalChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var multibar = nv.models.multiBarHorizontal() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend().height(30) | |
, controls = nv.models.legend().height(30) | |
; | |
var margin = {top: 30, right: 20, bottom: 50, left: 60} | |
, width = null | |
, height = null | |
, color = nv.utils.defaultColor() | |
, showControls = true | |
, showLegend = true | |
, showXAxis = true | |
, showYAxis = true | |
, stacked = false | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + ' - ' + x + '</h3>' + | |
'<p>' + y + '</p>' | |
} | |
, x //can be accessed via chart.xScale() | |
, y //can be accessed via chart.yScale() | |
, state = { stacked: stacked } | |
, defaultState = null | |
, noData = 'No Data Available.' | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, controlWidth = function() { return showControls ? 180 : 0 } | |
, transitionDuration = 250 | |
; | |
multibar | |
.stacked(stacked) | |
; | |
xAxis | |
.orient('left') | |
.tickPadding(5) | |
.highlightZero(false) | |
.showMaxMin(false) | |
.tickFormat(function(d) { return d }) | |
; | |
yAxis | |
.orient('bottom') | |
.tickFormat(d3.format(',.1f')) | |
; | |
controls.updateState(false); | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(multibar.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(multibar.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'e' : 'w', null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart) }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = multibar.xScale(); | |
y = multibar.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-multiBarHorizontalChart').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-multiBarHorizontalChart').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis') | |
.append('g').attr('class', 'nv-zeroLine') | |
.append('line'); | |
gEnter.append('g').attr('class', 'nv-barsWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
gEnter.append('g').attr('class', 'nv-controlsWrap'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width(availableWidth - controlWidth()); | |
if (multibar.barColor()) | |
data.forEach(function(series,i) { | |
series.color = d3.rgb('#ccc').darker(i * 1.5).toString(); | |
}) | |
g.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
g.select('.nv-legendWrap') | |
.attr('transform', 'translate(' + controlWidth() + ',' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Controls | |
if (showControls) { | |
var controlsData = [ | |
{ key: 'Grouped', disabled: multibar.stacked() }, | |
{ key: 'Stacked', disabled: !multibar.stacked() } | |
]; | |
controls.width(controlWidth()).color(['#444', '#444', '#444']); | |
g.select('.nv-controlsWrap') | |
.datum(controlsData) | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
.call(controls); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
multibar | |
.disabled(data.map(function(series) { return series.disabled })) | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })) | |
var barsWrap = g.select('.nv-barsWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
barsWrap.transition().call(multibar); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.ticks( availableHeight / 24 ) | |
.tickSize(-availableWidth, 0); | |
g.select('.nv-x.nv-axis').transition() | |
.call(xAxis); | |
var xTicks = g.select('.nv-x.nv-axis').selectAll('g'); | |
xTicks | |
.selectAll('line, text'); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( availableWidth / 100 ) | |
.tickSize( -availableHeight, 0); | |
g.select('.nv-y.nv-axis') | |
.attr('transform', 'translate(0,' + availableHeight + ')'); | |
g.select('.nv-y.nv-axis').transition() | |
.call(yAxis); | |
} | |
// Zero line | |
g.select(".nv-zeroLine line") | |
.attr("x1", y(0)) | |
.attr("x2", y(0)) | |
.attr("y1", 0) | |
.attr("y2", -availableHeight) | |
; | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('stateChange', function(newState) { | |
state = newState; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
controls.dispatch.on('legendClick', function(d,i) { | |
if (!d.disabled) return; | |
controlsData = controlsData.map(function(s) { | |
s.disabled = true; | |
return s; | |
}); | |
d.disabled = false; | |
switch (d.key) { | |
case 'Grouped': | |
multibar.stacked(false); | |
break; | |
case 'Stacked': | |
multibar.stacked(true); | |
break; | |
} | |
state.stacked = multibar.stacked(); | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
if (typeof e.stacked !== 'undefined') { | |
multibar.stacked(e.stacked); | |
state.stacked = e.stacked; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
multibar.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
multibar.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.multibar = multibar; | |
chart.legend = legend; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
d3.rebind(chart, multibar, 'x', 'y', 'xDomain', 'yDomain', 'xRange', 'yRange', 'forceX', 'forceY', | |
'clipEdge', 'id', 'delay', 'showValues','showBarLabels', 'valueFormat', 'stacked', 'barColor'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
return chart; | |
}; | |
chart.showControls = function(_) { | |
if (!arguments.length) return showControls; | |
showControls = _; | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.tooltip = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.multiChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 30, right: 20, bottom: 50, left: 60}, | |
color = d3.scale.category20().range(), | |
width = null, | |
height = null, | |
showLegend = true, | |
tooltips = true, | |
tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' at ' + x + '</p>' | |
}, | |
x, | |
y, | |
yDomain1, | |
yDomain2 | |
; //can be accessed via chart.lines.[x/y]Scale() | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x = d3.scale.linear(), | |
yScale1 = d3.scale.linear(), | |
yScale2 = d3.scale.linear(), | |
lines1 = nv.models.line().yScale(yScale1), | |
lines2 = nv.models.line().yScale(yScale2), | |
bars1 = nv.models.multiBar().stacked(false).yScale(yScale1), | |
bars2 = nv.models.multiBar().stacked(false).yScale(yScale2), | |
stack1 = nv.models.stackedArea().yScale(yScale1), | |
stack2 = nv.models.stackedArea().yScale(yScale2), | |
xAxis = nv.models.axis().scale(x).orient('bottom').tickPadding(5), | |
yAxis1 = nv.models.axis().scale(yScale1).orient('left'), | |
yAxis2 = nv.models.axis().scale(yScale2).orient('right'), | |
legend = nv.models.legend().height(30), | |
dispatch = d3.dispatch('tooltipShow', 'tooltipHide'); | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(lines1.x()(e.point, e.pointIndex)), | |
y = ((e.series.yAxis == 2) ? yAxis2 : yAxis1).tickFormat()(lines1.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, undefined, undefined, offsetElement.offsetParent); | |
}; | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
chart.update = function() { container.transition().call(chart); }; | |
chart.container = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
var dataLines1 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 1}) | |
var dataLines2 = data.filter(function(d) {return !d.disabled && d.type == 'line' && d.yAxis == 2}) | |
var dataBars1 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 1}) | |
var dataBars2 = data.filter(function(d) {return !d.disabled && d.type == 'bar' && d.yAxis == 2}) | |
var dataStack1 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 1}) | |
var dataStack2 = data.filter(function(d) {return !d.disabled && d.type == 'area' && d.yAxis == 2}) | |
var series1 = data.filter(function(d) {return !d.disabled && d.yAxis == 1}) | |
.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: d.x, y: d.y } | |
}) | |
}) | |
var series2 = data.filter(function(d) {return !d.disabled && d.yAxis == 2}) | |
.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: d.x, y: d.y } | |
}) | |
}) | |
x .domain(d3.extent(d3.merge(series1.concat(series2)), function(d) { return d.x } )) | |
.range([0, availableWidth]); | |
var wrap = container.selectAll('g.wrap.multiChart').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'wrap nvd3 multiChart').append('g'); | |
gEnter.append('g').attr('class', 'x axis'); | |
gEnter.append('g').attr('class', 'y1 axis'); | |
gEnter.append('g').attr('class', 'y2 axis'); | |
gEnter.append('g').attr('class', 'lines1Wrap'); | |
gEnter.append('g').attr('class', 'lines2Wrap'); | |
gEnter.append('g').attr('class', 'bars1Wrap'); | |
gEnter.append('g').attr('class', 'bars2Wrap'); | |
gEnter.append('g').attr('class', 'stack1Wrap'); | |
gEnter.append('g').attr('class', 'stack2Wrap'); | |
gEnter.append('g').attr('class', 'legendWrap'); | |
var g = wrap.select('g'); | |
if (showLegend) { | |
legend.width( availableWidth / 2 ); | |
g.select('.legendWrap') | |
.datum(data.map(function(series) { | |
series.originalKey = series.originalKey === undefined ? series.key : series.originalKey; | |
series.key = series.originalKey + (series.yAxis == 1 ? '' : ' (right axis)'); | |
return series; | |
})) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
g.select('.legendWrap') | |
.attr('transform', 'translate(' + ( availableWidth / 2 ) + ',' + (-margin.top) +')'); | |
} | |
lines1 | |
.width(availableWidth) | |
.height(availableHeight) | |
.interpolate("monotone") | |
.color(data.map(function(d,i) { | |
return d.color || color[i % color.length]; | |
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'line'})); | |
lines2 | |
.width(availableWidth) | |
.height(availableHeight) | |
.interpolate("monotone") | |
.color(data.map(function(d,i) { | |
return d.color || color[i % color.length]; | |
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'line'})); | |
bars1 | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color[i % color.length]; | |
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'bar'})); | |
bars2 | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color[i % color.length]; | |
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'bar'})); | |
stack1 | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color[i % color.length]; | |
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 1 && data[i].type == 'area'})); | |
stack2 | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color[i % color.length]; | |
}).filter(function(d,i) { return !data[i].disabled && data[i].yAxis == 2 && data[i].type == 'area'})); | |
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
var lines1Wrap = g.select('.lines1Wrap') | |
.datum(dataLines1) | |
var bars1Wrap = g.select('.bars1Wrap') | |
.datum(dataBars1) | |
var stack1Wrap = g.select('.stack1Wrap') | |
.datum(dataStack1) | |
var lines2Wrap = g.select('.lines2Wrap') | |
.datum(dataLines2) | |
var bars2Wrap = g.select('.bars2Wrap') | |
.datum(dataBars2) | |
var stack2Wrap = g.select('.stack2Wrap') | |
.datum(dataStack2) | |
var extraValue1 = dataStack1.length ? dataStack1.map(function(a){return a.values}).reduce(function(a,b){ | |
return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}}) | |
}).concat([{x:0, y:0}]) : [] | |
var extraValue2 = dataStack2.length ? dataStack2.map(function(a){return a.values}).reduce(function(a,b){ | |
return a.map(function(aVal,i){return {x: aVal.x, y: aVal.y + b[i].y}}) | |
}).concat([{x:0, y:0}]) : [] | |
yScale1 .domain(yDomain1 || d3.extent(d3.merge(series1).concat(extraValue1), function(d) { return d.y } )) | |
.range([0, availableHeight]) | |
yScale2 .domain(yDomain2 || d3.extent(d3.merge(series2).concat(extraValue2), function(d) { return d.y } )) | |
.range([0, availableHeight]) | |
lines1.yDomain(yScale1.domain()) | |
bars1.yDomain(yScale1.domain()) | |
stack1.yDomain(yScale1.domain()) | |
lines2.yDomain(yScale2.domain()) | |
bars2.yDomain(yScale2.domain()) | |
stack2.yDomain(yScale2.domain()) | |
if(dataStack1.length){d3.transition(stack1Wrap).call(stack1);} | |
if(dataStack2.length){d3.transition(stack2Wrap).call(stack2);} | |
if(dataBars1.length){d3.transition(bars1Wrap).call(bars1);} | |
if(dataBars2.length){d3.transition(bars2Wrap).call(bars2);} | |
if(dataLines1.length){d3.transition(lines1Wrap).call(lines1);} | |
if(dataLines2.length){d3.transition(lines2Wrap).call(lines2);} | |
xAxis | |
.ticks( availableWidth / 100 ) | |
.tickSize(-availableHeight, 0); | |
g.select('.x.axis') | |
.attr('transform', 'translate(0,' + availableHeight + ')'); | |
d3.transition(g.select('.x.axis')) | |
.call(xAxis); | |
yAxis1 | |
.ticks( availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
d3.transition(g.select('.y1.axis')) | |
.call(yAxis1); | |
yAxis2 | |
.ticks( availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
d3.transition(g.select('.y2.axis')) | |
.call(yAxis2); | |
g.select('.y2.axis') | |
.style('opacity', series2.length ? 1 : 0) | |
.attr('transform', 'translate(' + x.range()[1] + ',0)'); | |
legend.dispatch.on('stateChange', function(newState) { | |
chart.update(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
lines1.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines1.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
lines2.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines2.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
bars1.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
bars1.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
bars2.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
bars2.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
stack1.dispatch.on('tooltipShow', function(e) { | |
//disable tooltips when value ~= 0 | |
//// TODO: consider removing points from voronoi that have 0 value instead of this hack | |
if (!Math.round(stack1.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range | |
setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); | |
return false; | |
} | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], | |
dispatch.tooltipShow(e); | |
}); | |
stack1.dispatch.on('tooltipHide', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
stack2.dispatch.on('tooltipShow', function(e) { | |
//disable tooltips when value ~= 0 | |
//// TODO: consider removing points from voronoi that have 0 value instead of this hack | |
if (!Math.round(stack2.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range | |
setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); | |
return false; | |
} | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], | |
dispatch.tooltipShow(e); | |
}); | |
stack2.dispatch.on('tooltipHide', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
lines1.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines1.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
lines2.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
lines2.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
// Global getters and setters | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.lines1 = lines1; | |
chart.lines2 = lines2; | |
chart.bars1 = bars1; | |
chart.bars2 = bars2; | |
chart.stack1 = stack1; | |
chart.stack2 = stack2; | |
chart.xAxis = xAxis; | |
chart.yAxis1 = yAxis1; | |
chart.yAxis2 = yAxis2; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
lines1.x(_); | |
bars1.x(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
lines1.y(_); | |
bars1.y(_); | |
return chart; | |
}; | |
chart.yDomain1 = function(_) { | |
if (!arguments.length) return yDomain1; | |
yDomain1 = _; | |
return chart; | |
}; | |
chart.yDomain2 = function(_) { | |
if (!arguments.length) return yDomain2; | |
yDomain2 = _; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin = _; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = _; | |
legend.color(_); | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
return chart; | |
} | |
nv.models.ohlcBar = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one | |
, x = d3.scale.linear() | |
, y = d3.scale.linear() | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, getOpen = function(d) { return d.open } | |
, getClose = function(d) { return d.close } | |
, getHigh = function(d) { return d.high } | |
, getLow = function(d) { return d.low } | |
, forceX = [] | |
, forceY = [] | |
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart | |
, clipEdge = true | |
, color = nv.utils.defaultColor() | |
, xDomain | |
, yDomain | |
, xRange | |
, yRange | |
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
//TODO: store old scales for transitions | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup Scales | |
x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) )); | |
if (padData) | |
x.range(xRange || [availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); | |
else | |
x.range(xRange || [0, availableWidth]); | |
y .domain(yDomain || [ | |
d3.min(data[0].values.map(getLow).concat(forceY)), | |
d3.max(data[0].values.map(getHigh).concat(forceY)) | |
]) | |
.range(yRange || [availableHeight, 0]); | |
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point | |
if (x.domain()[0] === x.domain()[1]) | |
x.domain()[0] ? | |
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) | |
: x.domain([-1,1]); | |
if (y.domain()[0] === y.domain()[1]) | |
y.domain()[0] ? | |
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01]) | |
: y.domain([-1,1]); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = d3.select(this).selectAll('g.nv-wrap.nv-ohlcBar').data([data[0].values]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-ohlcBar'); | |
var defsEnter = wrapEnter.append('defs'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-ticks'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
container | |
.on('click', function(d,i) { | |
dispatch.chartClick({ | |
data: d, | |
index: i, | |
pos: d3.event, | |
id: id | |
}); | |
}); | |
defsEnter.append('clipPath') | |
.attr('id', 'nv-chart-clip-path-' + id) | |
.append('rect'); | |
wrap.select('#nv-chart-clip-path-' + id + ' rect') | |
.attr('width', availableWidth) | |
.attr('height', availableHeight); | |
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : ''); | |
var ticks = wrap.select('.nv-ticks').selectAll('.nv-tick') | |
.data(function(d) { return d }); | |
ticks.exit().remove(); | |
var ticksEnter = ticks.enter().append('path') | |
.attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i }) | |
.attr('d', function(d,i) { | |
var w = (availableWidth / data[0].values.length) * .9; | |
return 'm0,0l0,' | |
+ (y(getOpen(d,i)) | |
- y(getHigh(d,i))) | |
+ 'l' | |
+ (-w/2) | |
+ ',0l' | |
+ (w/2) | |
+ ',0l0,' | |
+ (y(getLow(d,i)) - y(getOpen(d,i))) | |
+ 'l0,' | |
+ (y(getClose(d,i)) | |
- y(getLow(d,i))) | |
+ 'l' | |
+ (w/2) | |
+ ',0l' | |
+ (-w/2) | |
+ ',0z'; | |
}) | |
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; }) | |
//.attr('fill', function(d,i) { return color[0]; }) | |
//.attr('stroke', function(d,i) { return color[0]; }) | |
//.attr('x', 0 ) | |
//.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) | |
//.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }) | |
.on('mouseover', function(d,i) { | |
d3.select(this).classed('hover', true); | |
dispatch.elementMouseover({ | |
point: d, | |
series: data[0], | |
pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted | |
pointIndex: i, | |
seriesIndex: 0, | |
e: d3.event | |
}); | |
}) | |
.on('mouseout', function(d,i) { | |
d3.select(this).classed('hover', false); | |
dispatch.elementMouseout({ | |
point: d, | |
series: data[0], | |
pointIndex: i, | |
seriesIndex: 0, | |
e: d3.event | |
}); | |
}) | |
.on('click', function(d,i) { | |
dispatch.elementClick({ | |
//label: d[label], | |
value: getY(d,i), | |
data: d, | |
index: i, | |
pos: [x(getX(d,i)), y(getY(d,i))], | |
e: d3.event, | |
id: id | |
}); | |
d3.event.stopPropagation(); | |
}) | |
.on('dblclick', function(d,i) { | |
dispatch.elementDblClick({ | |
//label: d[label], | |
value: getY(d,i), | |
data: d, | |
index: i, | |
pos: [x(getX(d,i)), y(getY(d,i))], | |
e: d3.event, | |
id: id | |
}); | |
d3.event.stopPropagation(); | |
}); | |
ticks | |
.attr('class', function(d,i,j) { return (getOpen(d,i) > getClose(d,i) ? 'nv-tick negative' : 'nv-tick positive') + ' nv-tick-' + j + '-' + i }) | |
d3.transition(ticks) | |
.attr('transform', function(d,i) { return 'translate(' + x(getX(d,i)) + ',' + y(getHigh(d,i)) + ')'; }) | |
.attr('d', function(d,i) { | |
var w = (availableWidth / data[0].values.length) * .9; | |
return 'm0,0l0,' | |
+ (y(getOpen(d,i)) | |
- y(getHigh(d,i))) | |
+ 'l' | |
+ (-w/2) | |
+ ',0l' | |
+ (w/2) | |
+ ',0l0,' | |
+ (y(getLow(d,i)) | |
- y(getOpen(d,i))) | |
+ 'l0,' | |
+ (y(getClose(d,i)) | |
- y(getLow(d,i))) | |
+ 'l' | |
+ (w/2) | |
+ ',0l' | |
+ (-w/2) | |
+ ',0z'; | |
}) | |
//.attr('width', (availableWidth / data[0].values.length) * .9 ) | |
//d3.transition(ticks) | |
//.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) }) | |
//.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) }); | |
//.order(); // not sure if this makes any sense for this model | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = _; | |
return chart; | |
}; | |
chart.open = function(_) { | |
if (!arguments.length) return getOpen; | |
getOpen = _; | |
return chart; | |
}; | |
chart.close = function(_) { | |
if (!arguments.length) return getClose; | |
getClose = _; | |
return chart; | |
}; | |
chart.high = function(_) { | |
if (!arguments.length) return getHigh; | |
getHigh = _; | |
return chart; | |
}; | |
chart.low = function(_) { | |
if (!arguments.length) return getLow; | |
getLow = _; | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.xScale = function(_) { | |
if (!arguments.length) return x; | |
x = _; | |
return chart; | |
}; | |
chart.yScale = function(_) { | |
if (!arguments.length) return y; | |
y = _; | |
return chart; | |
}; | |
chart.xDomain = function(_) { | |
if (!arguments.length) return xDomain; | |
xDomain = _; | |
return chart; | |
}; | |
chart.yDomain = function(_) { | |
if (!arguments.length) return yDomain; | |
yDomain = _; | |
return chart; | |
}; | |
chart.xRange = function(_) { | |
if (!arguments.length) return xRange; | |
xRange = _; | |
return chart; | |
}; | |
chart.yRange = function(_) { | |
if (!arguments.length) return yRange; | |
yRange = _; | |
return chart; | |
}; | |
chart.forceX = function(_) { | |
if (!arguments.length) return forceX; | |
forceX = _; | |
return chart; | |
}; | |
chart.forceY = function(_) { | |
if (!arguments.length) return forceY; | |
forceY = _; | |
return chart; | |
}; | |
chart.padData = function(_) { | |
if (!arguments.length) return padData; | |
padData = _; | |
return chart; | |
}; | |
chart.clipEdge = function(_) { | |
if (!arguments.length) return clipEdge; | |
clipEdge = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.pie = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 500 | |
, height = 500 | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, getDescription = function(d) { return d.description } | |
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one | |
, color = nv.utils.defaultColor() | |
, valueFormat = d3.format(',.2f') | |
, showLabels = true | |
, pieLabelsOutside = true | |
, donutLabelsOutside = false | |
, labelType = "key" | |
, labelThreshold = .02 //if slice percentage is under this, don't show label | |
, donut = false | |
, labelSunbeamLayout = false | |
, startAngle = false | |
, endAngle = false | |
, donutRatio = 0.5 | |
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout') | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
radius = Math.min(availableWidth, availableHeight) / 2, | |
arcRadius = radius-(radius / 5), | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
//var wrap = container.selectAll('.nv-wrap.nv-pie').data([data]); | |
var wrap = container.selectAll('.nv-wrap.nv-pie').data(data); | |
var wrapEnter = wrap.enter().append('g').attr('class','nvd3 nv-wrap nv-pie nv-chart-' + id); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-pie'); | |
gEnter.append('g').attr('class', 'nv-pieLabels'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
g.select('.nv-pie').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')'); | |
g.select('.nv-pieLabels').attr('transform', 'translate(' + availableWidth / 2 + ',' + availableHeight / 2 + ')'); | |
//------------------------------------------------------------ | |
container | |
.on('click', function(d,i) { | |
dispatch.chartClick({ | |
data: d, | |
index: i, | |
pos: d3.event, | |
id: id | |
}); | |
}); | |
var arc = d3.svg.arc() | |
.outerRadius(arcRadius); | |
if (startAngle) arc.startAngle(startAngle) | |
if (endAngle) arc.endAngle(endAngle); | |
if (donut) arc.innerRadius(radius * donutRatio); | |
// Setup the Pie chart and choose the data element | |
var pie = d3.layout.pie() | |
.sort(null) | |
.value(function(d) { return d.disabled ? 0 : getY(d) }); | |
var slices = wrap.select('.nv-pie').selectAll('.nv-slice') | |
.data(pie); | |
var pieLabels = wrap.select('.nv-pieLabels').selectAll('.nv-label') | |
.data(pie); | |
slices.exit().remove(); | |
pieLabels.exit().remove(); | |
var ae = slices.enter().append('g') | |
.attr('class', 'nv-slice') | |
.on('mouseover', function(d,i){ | |
d3.select(this).classed('hover', true); | |
dispatch.elementMouseover({ | |
label: getX(d.data), | |
value: getY(d.data), | |
point: d.data, | |
pointIndex: i, | |
pos: [d3.event.pageX, d3.event.pageY], | |
id: id | |
}); | |
}) | |
.on('mouseout', function(d,i){ | |
d3.select(this).classed('hover', false); | |
dispatch.elementMouseout({ | |
label: getX(d.data), | |
value: getY(d.data), | |
point: d.data, | |
index: i, | |
id: id | |
}); | |
}) | |
.on('click', function(d,i) { | |
dispatch.elementClick({ | |
label: getX(d.data), | |
value: getY(d.data), | |
point: d.data, | |
index: i, | |
pos: d3.event, | |
id: id | |
}); | |
d3.event.stopPropagation(); | |
}) | |
.on('dblclick', function(d,i) { | |
dispatch.elementDblClick({ | |
label: getX(d.data), | |
value: getY(d.data), | |
point: d.data, | |
index: i, | |
pos: d3.event, | |
id: id | |
}); | |
d3.event.stopPropagation(); | |
}); | |
slices | |
.attr('fill', function(d,i) { return color(d, i); }) | |
.attr('stroke', function(d,i) { return color(d, i); }); | |
var paths = ae.append('path') | |
.each(function(d) { this._current = d; }); | |
//.attr('d', arc); | |
slices.select('path') | |
.transition() | |
.attr('d', arc) | |
.attrTween('d', arcTween); | |
if (showLabels) { | |
// This does the normal label | |
var labelsArc = d3.svg.arc().innerRadius(0); | |
if (pieLabelsOutside){ labelsArc = arc; } | |
if (donutLabelsOutside) { labelsArc = d3.svg.arc().outerRadius(arc.outerRadius()); } | |
pieLabels.enter().append("g").classed("nv-label",true) | |
.each(function(d,i) { | |
var group = d3.select(this); | |
group | |
.attr('transform', function(d) { | |
if (labelSunbeamLayout) { | |
d.outerRadius = arcRadius + 10; // Set Outer Coordinate | |
d.innerRadius = arcRadius + 15; // Set Inner Coordinate | |
var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI); | |
if ((d.startAngle+d.endAngle)/2 < Math.PI) { | |
rotateAngle -= 90; | |
} else { | |
rotateAngle += 90; | |
} | |
return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')'; | |
} else { | |
d.outerRadius = radius + 10; // Set Outer Coordinate | |
d.innerRadius = radius + 15; // Set Inner Coordinate | |
return 'translate(' + labelsArc.centroid(d) + ')' | |
} | |
}); | |
group.append('rect') | |
.style('stroke', '#fff') | |
.style('fill', '#fff') | |
.attr("rx", 3) | |
.attr("ry", 3); | |
group.append('text') | |
.style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned | |
.style('fill', '#000') | |
}); | |
var labelLocationHash = {}; | |
var avgHeight = 14; | |
var avgWidth = 140; | |
var createHashKey = function(coordinates) { | |
return Math.floor(coordinates[0]/avgWidth) * avgWidth + ',' + Math.floor(coordinates[1]/avgHeight) * avgHeight; | |
}; | |
pieLabels.transition() | |
.attr('transform', function(d) { | |
if (labelSunbeamLayout) { | |
d.outerRadius = arcRadius + 10; // Set Outer Coordinate | |
d.innerRadius = arcRadius + 15; // Set Inner Coordinate | |
var rotateAngle = (d.startAngle + d.endAngle) / 2 * (180 / Math.PI); | |
if ((d.startAngle+d.endAngle)/2 < Math.PI) { | |
rotateAngle -= 90; | |
} else { | |
rotateAngle += 90; | |
} | |
return 'translate(' + labelsArc.centroid(d) + ') rotate(' + rotateAngle + ')'; | |
} else { | |
d.outerRadius = radius + 10; // Set Outer Coordinate | |
d.innerRadius = radius + 15; // Set Inner Coordinate | |
/* | |
Overlapping pie labels are not good. What this attempts to do is, prevent overlapping. | |
Each label location is hashed, and if a hash collision occurs, we assume an overlap. | |
Adjust the label's y-position to remove the overlap. | |
*/ | |
var center = labelsArc.centroid(d); | |
var hashKey = createHashKey(center); | |
if (labelLocationHash[hashKey]) { | |
center[1] -= avgHeight; | |
} | |
labelLocationHash[createHashKey(center)] = true; | |
return 'translate(' + center + ')' | |
} | |
}); | |
pieLabels.select(".nv-label text") | |
.style('text-anchor', labelSunbeamLayout ? ((d.startAngle + d.endAngle) / 2 < Math.PI ? 'start' : 'end') : 'middle') //center the text on it's origin or begin/end if orthogonal aligned | |
.text(function(d, i) { | |
var percent = (d.endAngle - d.startAngle) / (2 * Math.PI); | |
var labelTypes = { | |
"key" : getX(d.data), | |
"value": getY(d.data), | |
"percent": d3.format('%')(percent) | |
}; | |
return (d.value && percent > labelThreshold) ? labelTypes[labelType] : ''; | |
}); | |
} | |
// Computes the angle of an arc, converting from radians to degrees. | |
function angle(d) { | |
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90; | |
return a > 90 ? a - 180 : a; | |
} | |
function arcTween(a) { | |
a.endAngle = isNaN(a.endAngle) ? 0 : a.endAngle; | |
a.startAngle = isNaN(a.startAngle) ? 0 : a.startAngle; | |
if (!donut) a.innerRadius = 0; | |
var i = d3.interpolate(this._current, a); | |
this._current = i(0); | |
return function(t) { | |
return arc(i(t)); | |
}; | |
} | |
function tweenPie(b) { | |
b.innerRadius = 0; | |
var i = d3.interpolate({startAngle: 0, endAngle: 0}, b); | |
return function(t) { | |
return arc(i(t)); | |
}; | |
} | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.values = function(_) { | |
nv.log("pie.values() is no longer supported."); | |
return chart; | |
}; | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = _; | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = d3.functor(_); | |
return chart; | |
}; | |
chart.description = function(_) { | |
if (!arguments.length) return getDescription; | |
getDescription = _; | |
return chart; | |
}; | |
chart.showLabels = function(_) { | |
if (!arguments.length) return showLabels; | |
showLabels = _; | |
return chart; | |
}; | |
chart.labelSunbeamLayout = function(_) { | |
if (!arguments.length) return labelSunbeamLayout; | |
labelSunbeamLayout = _; | |
return chart; | |
}; | |
chart.donutLabelsOutside = function(_) { | |
if (!arguments.length) return donutLabelsOutside; | |
donutLabelsOutside = _; | |
return chart; | |
}; | |
chart.pieLabelsOutside = function(_) { | |
if (!arguments.length) return pieLabelsOutside; | |
pieLabelsOutside = _; | |
return chart; | |
}; | |
chart.labelType = function(_) { | |
if (!arguments.length) return labelType; | |
labelType = _; | |
labelType = labelType || "key"; | |
return chart; | |
}; | |
chart.donut = function(_) { | |
if (!arguments.length) return donut; | |
donut = _; | |
return chart; | |
}; | |
chart.donutRatio = function(_) { | |
if (!arguments.length) return donutRatio; | |
donutRatio = _; | |
return chart; | |
}; | |
chart.startAngle = function(_) { | |
if (!arguments.length) return startAngle; | |
startAngle = _; | |
return chart; | |
}; | |
chart.endAngle = function(_) { | |
if (!arguments.length) return endAngle; | |
endAngle = _; | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.valueFormat = function(_) { | |
if (!arguments.length) return valueFormat; | |
valueFormat = _; | |
return chart; | |
}; | |
chart.labelThreshold = function(_) { | |
if (!arguments.length) return labelThreshold; | |
labelThreshold = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.pieChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var pie = nv.models.pie() | |
, legend = nv.models.legend() | |
; | |
var margin = {top: 30, right: 20, bottom: 20, left: 20} | |
, width = null | |
, height = null | |
, showLegend = true | |
, color = nv.utils.defaultColor() | |
, tooltips = true | |
, tooltip = function(key, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + '</p>' | |
} | |
, state = {} | |
, defaultState = null | |
, noData = "No Data Available." | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var tooltipLabel = pie.description()(e.point) || pie.x()(e.point) | |
var left = e.pos[0] + ( (offsetElement && offsetElement.offsetLeft) || 0 ), | |
top = e.pos[1] + ( (offsetElement && offsetElement.offsetTop) || 0), | |
y = pie.valueFormat()(pie.y()(e.point)), | |
content = tooltip(tooltipLabel, y, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().call(chart); }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-pieChart').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-pieChart').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-pieWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend | |
.width( availableWidth ) | |
.key(pie.x()); | |
wrap.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
wrap.select('.nv-legendWrap') | |
.attr('transform', 'translate(0,' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
pie | |
.width(availableWidth) | |
.height(availableHeight); | |
var pieWrap = g.select('.nv-pieWrap') | |
.datum([data]); | |
d3.transition(pieWrap).call(pie); | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
legend.dispatch.on('stateChange', function(newState) { | |
state = newState; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
pie.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
pie.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.legend = legend; | |
chart.dispatch = dispatch; | |
chart.pie = pie; | |
d3.rebind(chart, pie, 'valueFormat', 'values', 'x', 'y', 'description', 'id', 'showLabels', 'donutLabelsOutside', 'pieLabelsOutside', 'labelType', 'donut', 'donutRatio', 'labelThreshold'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
pie.color(color); | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.scatter = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, color = nv.utils.defaultColor() // chooses color | |
, id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't select one | |
, x = d3.scale.linear() | |
, y = d3.scale.linear() | |
, z = d3.scale.linear() //linear because d3.svg.shape.size is treated as area | |
, getX = function(d) { return d.x } // accessor to get the x value | |
, getY = function(d) { return d.y } // accessor to get the y value | |
, getSize = function(d) { return d.size || 1} // accessor to get the point size | |
, getShape = function(d) { return d.shape || 'circle' } // accessor to get point shape | |
, onlyCircles = true // Set to false to use shapes | |
, forceX = [] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.) | |
, forceY = [] // List of numbers to Force into the Y scale | |
, forceSize = [] // List of numbers to Force into the Size scale | |
, interactive = true // If true, plots a voronoi overlay for advanced point intersection | |
, pointKey = null | |
, pointActive = function(d) { return !d.notActive } // any points that return false will be filtered out | |
, padData = false // If true, adds half a data points width to front and back, for lining up a line chart with a bar chart | |
, padDataOuter = .1 //outerPadding to imitate ordinal scale outer padding | |
, clipEdge = false // if true, masks points within x and y scale | |
, clipVoronoi = true // if true, masks each point with a circle... can turn off to slightly increase performance | |
, clipRadius = function() { return 25 } // function to get the radius for voronoi point clips | |
, xDomain = null // Override x domain (skips the calculation from data) | |
, yDomain = null // Override y domain | |
, xRange = null // Override x range | |
, yRange = null // Override y range | |
, sizeDomain = null // Override point size domain | |
, sizeRange = null | |
, singlePoint = false | |
, dispatch = d3.dispatch('elementClick', 'elementMouseover', 'elementMouseout') | |
, useVoronoi = true | |
; | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x0, y0, z0 // used to store previous scales | |
, timeoutID | |
, needsUpdate = false // Flag for when the points are visually updating, but the interactive layer is behind, to disable tooltips | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
//add series index to each data point for reference | |
data.forEach(function(series, i) { | |
series.values.forEach(function(point) { | |
point.series = i; | |
}); | |
}); | |
//------------------------------------------------------------ | |
// Setup Scales | |
// remap and flatten the data for use in calculating the scales' domains | |
var seriesData = (xDomain && yDomain && sizeDomain) ? [] : // if we know xDomain and yDomain and sizeDomain, no need to calculate.... if Size is constant remember to set sizeDomain to speed up performance | |
d3.merge( | |
data.map(function(d) { | |
return d.values.map(function(d,i) { | |
return { x: getX(d,i), y: getY(d,i), size: getSize(d,i) } | |
}) | |
}) | |
); | |
x .domain(xDomain || d3.extent(seriesData.map(function(d) { return d.x; }).concat(forceX))) | |
if (padData && data[0]) | |
x.range(xRange || [(availableWidth * padDataOuter + availableWidth) / (2 *data[0].values.length), availableWidth - availableWidth * (1 + padDataOuter) / (2 * data[0].values.length) ]); | |
//x.range([availableWidth * .5 / data[0].values.length, availableWidth * (data[0].values.length - .5) / data[0].values.length ]); | |
else | |
x.range(xRange || [0, availableWidth]); | |
y .domain(yDomain || d3.extent(seriesData.map(function(d) { return d.y }).concat(forceY))) | |
.range(yRange || [availableHeight, 0]); | |
z .domain(sizeDomain || d3.extent(seriesData.map(function(d) { return d.size }).concat(forceSize))) | |
.range(sizeRange || [16, 256]); | |
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point | |
if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true; | |
if (x.domain()[0] === x.domain()[1]) | |
x.domain()[0] ? | |
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01]) | |
: x.domain([-1,1]); | |
if (y.domain()[0] === y.domain()[1]) | |
y.domain()[0] ? | |
y.domain([y.domain()[0] - y.domain()[0] * 0.01, y.domain()[1] + y.domain()[1] * 0.01]) | |
: y.domain([-1,1]); | |
if ( isNaN(x.domain()[0])) { | |
x.domain([-1,1]); | |
} | |
if ( isNaN(y.domain()[0])) { | |
y.domain([-1,1]); | |
} | |
x0 = x0 || x; | |
y0 = y0 || y; | |
z0 = z0 || z; | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-scatter').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatter nv-chart-' + id + (singlePoint ? ' nv-single-point' : '')); | |
var defsEnter = wrapEnter.append('defs'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-groups'); | |
gEnter.append('g').attr('class', 'nv-point-paths'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
defsEnter.append('clipPath') | |
.attr('id', 'nv-edge-clip-' + id) | |
.append('rect'); | |
wrap.select('#nv-edge-clip-' + id + ' rect') | |
.attr('width', availableWidth) | |
.attr('height', (availableHeight > 0) ? availableHeight : 0); | |
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); | |
function updateInteractiveLayer() { | |
if (!interactive) return false; | |
var eventElements; | |
var vertices = d3.merge(data.map(function(group, groupIndex) { | |
return group.values | |
.map(function(point, pointIndex) { | |
// *Adding noise to make duplicates very unlikely | |
// *Injecting series and point index for reference | |
/* *Adding a 'jitter' to the points, because there's an issue in d3.geom.voronoi. | |
*/ | |
var pX = getX(point,pointIndex); | |
var pY = getY(point,pointIndex); | |
return [x(pX)+ Math.random() * 1e-7, | |
y(pY)+ Math.random() * 1e-7, | |
groupIndex, | |
pointIndex, point]; //temp hack to add noise untill I think of a better way so there are no duplicates | |
}) | |
.filter(function(pointArray, pointIndex) { | |
return pointActive(pointArray[4], pointIndex); // Issue #237.. move filter to after map, so pointIndex is correct! | |
}) | |
}) | |
); | |
//inject series and point index for reference into voronoi | |
if (useVoronoi === true) { | |
if (clipVoronoi) { | |
var pointClipsEnter = wrap.select('defs').selectAll('.nv-point-clips') | |
.data([id]) | |
.enter(); | |
pointClipsEnter.append('clipPath') | |
.attr('class', 'nv-point-clips') | |
.attr('id', 'nv-points-clip-' + id); | |
var pointClips = wrap.select('#nv-points-clip-' + id).selectAll('circle') | |
.data(vertices); | |
pointClips.enter().append('circle') | |
.attr('r', clipRadius); | |
pointClips.exit().remove(); | |
pointClips | |
.attr('cx', function(d) { return d[0] }) | |
.attr('cy', function(d) { return d[1] }); | |
wrap.select('.nv-point-paths') | |
.attr('clip-path', 'url(#nv-points-clip-' + id + ')'); | |
} | |
if(vertices.length) { | |
// Issue #283 - Adding 2 dummy points to the voronoi b/c voronoi requires min 3 points to work | |
vertices.push([x.range()[0] - 20, y.range()[0] - 20, null, null]); | |
vertices.push([x.range()[1] + 20, y.range()[1] + 20, null, null]); | |
vertices.push([x.range()[0] - 20, y.range()[0] + 20, null, null]); | |
vertices.push([x.range()[1] + 20, y.range()[1] - 20, null, null]); | |
} | |
var bounds = d3.geom.polygon([ | |
[-10,-10], | |
[-10,height + 10], | |
[width + 10,height + 10], | |
[width + 10,-10] | |
]); | |
var voronoi = d3.geom.voronoi(vertices).map(function(d, i) { | |
return { | |
'data': bounds.clip(d), | |
'series': vertices[i][2], | |
'point': vertices[i][3] | |
} | |
}); | |
var pointPaths = wrap.select('.nv-point-paths').selectAll('path') | |
.data(voronoi); | |
pointPaths.enter().append('path') | |
.attr('class', function(d,i) { return 'nv-path-'+i; }); | |
pointPaths.exit().remove(); | |
pointPaths | |
.attr('d', function(d) { | |
if (d.data.length === 0) | |
return 'M 0 0' | |
else | |
return 'M' + d.data.join('L') + 'Z'; | |
}); | |
var mouseEventCallback = function(d,mDispatch) { | |
if (needsUpdate) return 0; | |
var series = data[d.series]; | |
if (typeof series === 'undefined') return; | |
var point = series.values[d.point]; | |
mDispatch({ | |
point: point, | |
series: series, | |
pos: [x(getX(point, d.point)) + margin.left, y(getY(point, d.point)) + margin.top], | |
seriesIndex: d.series, | |
pointIndex: d.point | |
}); | |
}; | |
pointPaths | |
.on('click', function(d) { | |
mouseEventCallback(d, dispatch.elementClick); | |
}) | |
.on('mouseover', function(d) { | |
mouseEventCallback(d, dispatch.elementMouseover); | |
}) | |
.on('mouseout', function(d, i) { | |
mouseEventCallback(d, dispatch.elementMouseout); | |
}); | |
} else { | |
/* | |
// bring data in form needed for click handlers | |
var dataWithPoints = vertices.map(function(d, i) { | |
return { | |
'data': d, | |
'series': vertices[i][2], | |
'point': vertices[i][3] | |
} | |
}); | |
*/ | |
// add event handlers to points instead voronoi paths | |
wrap.select('.nv-groups').selectAll('.nv-group') | |
.selectAll('.nv-point') | |
//.data(dataWithPoints) | |
//.style('pointer-events', 'auto') // recativate events, disabled by css | |
.on('click', function(d,i) { | |
//nv.log('test', d, i); | |
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point | |
var series = data[d.series], | |
point = series.values[i]; | |
dispatch.elementClick({ | |
point: point, | |
series: series, | |
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top], | |
seriesIndex: d.series, | |
pointIndex: i | |
}); | |
}) | |
.on('mouseover', function(d,i) { | |
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point | |
var series = data[d.series], | |
point = series.values[i]; | |
dispatch.elementMouseover({ | |
point: point, | |
series: series, | |
pos: [x(getX(point, i)) + margin.left, y(getY(point, i)) + margin.top], | |
seriesIndex: d.series, | |
pointIndex: i | |
}); | |
}) | |
.on('mouseout', function(d,i) { | |
if (needsUpdate || !data[d.series]) return 0; //check if this is a dummy point | |
var series = data[d.series], | |
point = series.values[i]; | |
dispatch.elementMouseout({ | |
point: point, | |
series: series, | |
seriesIndex: d.series, | |
pointIndex: i | |
}); | |
}); | |
} | |
needsUpdate = false; | |
} | |
needsUpdate = true; | |
var groups = wrap.select('.nv-groups').selectAll('.nv-group') | |
.data(function(d) { return d }, function(d) { return d.key }); | |
groups.enter().append('g') | |
.style('stroke-opacity', 1e-6) | |
.style('fill-opacity', 1e-6); | |
groups.exit() | |
.remove(); | |
groups | |
.attr('class', function(d,i) { return 'nv-group nv-series-' + i }) | |
.classed('hover', function(d) { return d.hover }); | |
groups | |
.transition() | |
.style('fill', function(d,i) { return color(d, i) }) | |
.style('stroke', function(d,i) { return color(d, i) }) | |
.style('stroke-opacity', 1) | |
.style('fill-opacity', .5); | |
if (onlyCircles) { | |
var points = groups.selectAll('circle.nv-point') | |
.data(function(d) { return d.values }, pointKey); | |
points.enter().append('circle') | |
.style('fill', function (d,i) { return d.color }) | |
.style('stroke', function (d,i) { return d.color }) | |
.attr('cx', function(d,i) { return nv.utils.NaNtoZero(x0(getX(d,i))) }) | |
.attr('cy', function(d,i) { return nv.utils.NaNtoZero(y0(getY(d,i))) }) | |
.attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) }); | |
points.exit().remove(); | |
groups.exit().selectAll('path.nv-point').transition() | |
.attr('cx', function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) }) | |
.attr('cy', function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) }) | |
.remove(); | |
points.each(function(d,i) { | |
d3.select(this) | |
.classed('nv-point', true) | |
.classed('nv-point-' + i, true) | |
.classed('hover',false) | |
; | |
}); | |
points.transition() | |
.attr('cx', function(d,i) { return nv.utils.NaNtoZero(x(getX(d,i))) }) | |
.attr('cy', function(d,i) { return nv.utils.NaNtoZero(y(getY(d,i))) }) | |
.attr('r', function(d,i) { return Math.sqrt(z(getSize(d,i))/Math.PI) }); | |
} else { | |
var points = groups.selectAll('path.nv-point') | |
.data(function(d) { return d.values }); | |
points.enter().append('path') | |
.style('fill', function (d,i) { return d.color }) | |
.style('stroke', function (d,i) { return d.color }) | |
.attr('transform', function(d,i) { | |
return 'translate(' + x0(getX(d,i)) + ',' + y0(getY(d,i)) + ')' | |
}) | |
.attr('d', | |
d3.svg.symbol() | |
.type(getShape) | |
.size(function(d,i) { return z(getSize(d,i)) }) | |
); | |
points.exit().remove(); | |
groups.exit().selectAll('path.nv-point') | |
.transition() | |
.attr('transform', function(d,i) { | |
return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')' | |
}) | |
.remove(); | |
points.each(function(d,i) { | |
d3.select(this) | |
.classed('nv-point', true) | |
.classed('nv-point-' + i, true) | |
.classed('hover',false) | |
; | |
}); | |
points.transition() | |
.attr('transform', function(d,i) { | |
//nv.log(d,i,getX(d,i), x(getX(d,i))); | |
return 'translate(' + x(getX(d,i)) + ',' + y(getY(d,i)) + ')' | |
}) | |
.attr('d', | |
d3.svg.symbol() | |
.type(getShape) | |
.size(function(d,i) { return z(getSize(d,i)) }) | |
); | |
} | |
// Delay updating the invisible interactive layer for smoother animation | |
clearTimeout(timeoutID); // stop repeat calls to updateInteractiveLayer | |
timeoutID = setTimeout(updateInteractiveLayer, 300); | |
//updateInteractiveLayer(); | |
//store old scales for use in transitions on update | |
x0 = x.copy(); | |
y0 = y.copy(); | |
z0 = z.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
chart.clearHighlights = function() { | |
//Remove the 'hover' class from all highlighted points. | |
d3.selectAll(".nv-chart-" + id + " .nv-point.hover").classed("hover",false); | |
}; | |
chart.highlightPoint = function(seriesIndex,pointIndex,isHoverOver) { | |
d3.select(".nv-chart-" + id + " .nv-series-" + seriesIndex + " .nv-point-" + pointIndex) | |
.classed("hover",isHoverOver); | |
}; | |
dispatch.on('elementMouseover.point', function(d) { | |
if (interactive) chart.highlightPoint(d.seriesIndex,d.pointIndex,true); | |
}); | |
dispatch.on('elementMouseout.point', function(d) { | |
if (interactive) chart.highlightPoint(d.seriesIndex,d.pointIndex,false); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = d3.functor(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = d3.functor(_); | |
return chart; | |
}; | |
chart.size = function(_) { | |
if (!arguments.length) return getSize; | |
getSize = d3.functor(_); | |
return chart; | |
}; | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.xScale = function(_) { | |
if (!arguments.length) return x; | |
x = _; | |
return chart; | |
}; | |
chart.yScale = function(_) { | |
if (!arguments.length) return y; | |
y = _; | |
return chart; | |
}; | |
chart.zScale = function(_) { | |
if (!arguments.length) return z; | |
z = _; | |
return chart; | |
}; | |
chart.xDomain = function(_) { | |
if (!arguments.length) return xDomain; | |
xDomain = _; | |
return chart; | |
}; | |
chart.yDomain = function(_) { | |
if (!arguments.length) return yDomain; | |
yDomain = _; | |
return chart; | |
}; | |
chart.sizeDomain = function(_) { | |
if (!arguments.length) return sizeDomain; | |
sizeDomain = _; | |
return chart; | |
}; | |
chart.xRange = function(_) { | |
if (!arguments.length) return xRange; | |
xRange = _; | |
return chart; | |
}; | |
chart.yRange = function(_) { | |
if (!arguments.length) return yRange; | |
yRange = _; | |
return chart; | |
}; | |
chart.sizeRange = function(_) { | |
if (!arguments.length) return sizeRange; | |
sizeRange = _; | |
return chart; | |
}; | |
chart.forceX = function(_) { | |
if (!arguments.length) return forceX; | |
forceX = _; | |
return chart; | |
}; | |
chart.forceY = function(_) { | |
if (!arguments.length) return forceY; | |
forceY = _; | |
return chart; | |
}; | |
chart.forceSize = function(_) { | |
if (!arguments.length) return forceSize; | |
forceSize = _; | |
return chart; | |
}; | |
chart.interactive = function(_) { | |
if (!arguments.length) return interactive; | |
interactive = _; | |
return chart; | |
}; | |
chart.pointKey = function(_) { | |
if (!arguments.length) return pointKey; | |
pointKey = _; | |
return chart; | |
}; | |
chart.pointActive = function(_) { | |
if (!arguments.length) return pointActive; | |
pointActive = _; | |
return chart; | |
}; | |
chart.padData = function(_) { | |
if (!arguments.length) return padData; | |
padData = _; | |
return chart; | |
}; | |
chart.padDataOuter = function(_) { | |
if (!arguments.length) return padDataOuter; | |
padDataOuter = _; | |
return chart; | |
}; | |
chart.clipEdge = function(_) { | |
if (!arguments.length) return clipEdge; | |
clipEdge = _; | |
return chart; | |
}; | |
chart.clipVoronoi= function(_) { | |
if (!arguments.length) return clipVoronoi; | |
clipVoronoi = _; | |
return chart; | |
}; | |
chart.useVoronoi= function(_) { | |
if (!arguments.length) return useVoronoi; | |
useVoronoi = _; | |
if (useVoronoi === false) { | |
clipVoronoi = false; | |
} | |
return chart; | |
}; | |
chart.clipRadius = function(_) { | |
if (!arguments.length) return clipRadius; | |
clipRadius = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.shape = function(_) { | |
if (!arguments.length) return getShape; | |
getShape = _; | |
return chart; | |
}; | |
chart.onlyCircles = function(_) { | |
if (!arguments.length) return onlyCircles; | |
onlyCircles = _; | |
return chart; | |
}; | |
chart.id = function(_) { | |
if (!arguments.length) return id; | |
id = _; | |
return chart; | |
}; | |
chart.singlePoint = function(_) { | |
if (!arguments.length) return singlePoint; | |
singlePoint = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.scatterChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var scatter = nv.models.scatter() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend() | |
, controls = nv.models.legend() | |
, distX = nv.models.distribution() | |
, distY = nv.models.distribution() | |
; | |
var margin = {top: 30, right: 20, bottom: 50, left: 75} | |
, width = null | |
, height = null | |
, color = nv.utils.defaultColor() | |
, x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale() | |
, y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale() | |
, xPadding = 0 | |
, yPadding = 0 | |
, showDistX = false | |
, showDistY = false | |
, showLegend = true | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, showControls = !!d3.fisheye | |
, fisheye = 0 | |
, pauseFisheye = false | |
, tooltips = true | |
, tooltipX = function(key, x, y) { return '<strong>' + x + '</strong>' } | |
, tooltipY = function(key, x, y) { return '<strong>' + y + '</strong>' } | |
, tooltip = null | |
, state = {} | |
, defaultState = null | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, noData = "No Data Available." | |
, transitionDuration = 250 | |
; | |
scatter | |
.xScale(x) | |
.yScale(y) | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(10) | |
; | |
yAxis | |
.orient((rightAlignYAxis) ? 'right' : 'left') | |
.tickPadding(10) | |
; | |
distX | |
.axis('x') | |
; | |
distY | |
.axis('y') | |
; | |
controls.updateState(false); | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x0, y0; | |
var showTooltip = function(e, offsetElement) { | |
//TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?) | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0), | |
leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ), | |
topY = e.pos[1] + ( offsetElement.offsetTop || 0), | |
xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)), | |
yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex)); | |
if( tooltipX != null ) | |
nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip'); | |
if( tooltipY != null ) | |
nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip'); | |
if( tooltip != null ) | |
nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement); | |
}; | |
var controlsData = [ | |
{ key: 'Magnify', disabled: true } | |
]; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart); }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display noData message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x0 = x0 || x; | |
y0 = y0 || y; | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id()); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
// background for pointer events | |
gEnter.append('rect').attr('class', 'nvd3 nv-background'); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis'); | |
gEnter.append('g').attr('class', 'nv-scatterWrap'); | |
gEnter.append('g').attr('class', 'nv-distWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
gEnter.append('g').attr('class', 'nv-controlsWrap'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
var legendWidth = (showControls) ? availableWidth / 2 : availableWidth; | |
legend.width(legendWidth); | |
wrap.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
wrap.select('.nv-legendWrap') | |
.attr('transform', 'translate(' + (availableWidth - legendWidth) + ',' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Controls | |
if (showControls) { | |
controls.width(180).color(['#444']); | |
g.select('.nv-controlsWrap') | |
.datum(controlsData) | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
.call(controls); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
scatter | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })); | |
if (xPadding !== 0) | |
scatter.xDomain(null); | |
if (yPadding !== 0) | |
scatter.yDomain(null); | |
wrap.select('.nv-scatterWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(scatter); | |
//Adjust for x and y padding | |
if (xPadding !== 0) { | |
var xRange = x.domain()[1] - x.domain()[0]; | |
scatter.xDomain([x.domain()[0] - (xPadding * xRange), x.domain()[1] + (xPadding * xRange)]); | |
} | |
if (yPadding !== 0) { | |
var yRange = y.domain()[1] - y.domain()[0]; | |
scatter.yDomain([y.domain()[0] - (yPadding * yRange), y.domain()[1] + (yPadding * yRange)]); | |
} | |
//Only need to update the scatter again if x/yPadding changed the domain. | |
if (yPadding !== 0 || xPadding !== 0) { | |
wrap.select('.nv-scatterWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(scatter); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.ticks( xAxis.ticks() && xAxis.ticks().length ? xAxis.ticks() : availableWidth / 100 ) | |
.tickSize( -availableHeight , 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')') | |
.call(xAxis); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( yAxis.ticks() && yAxis.ticks().length ? yAxis.ticks() : availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-y.nv-axis') | |
.call(yAxis); | |
} | |
if (showDistX) { | |
distX | |
.getData(scatter.x()) | |
.scale(x) | |
.width(availableWidth) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })); | |
gEnter.select('.nv-distWrap').append('g') | |
.attr('class', 'nv-distributionX'); | |
g.select('.nv-distributionX') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distX); | |
} | |
if (showDistY) { | |
distY | |
.getData(scatter.y()) | |
.scale(y) | |
.width(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })); | |
gEnter.select('.nv-distWrap').append('g') | |
.attr('class', 'nv-distributionY'); | |
g.select('.nv-distributionY') | |
.attr('transform', | |
'translate(' + (rightAlignYAxis ? availableWidth : -distY.size() ) + ',0)') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distY); | |
} | |
//------------------------------------------------------------ | |
if (d3.fisheye) { | |
g.select('.nv-background') | |
.attr('width', availableWidth) | |
.attr('height', availableHeight); | |
g.select('.nv-background').on('mousemove', updateFisheye); | |
g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;}); | |
scatter.dispatch.on('elementClick.freezeFisheye', function() { | |
pauseFisheye = !pauseFisheye; | |
}); | |
} | |
function updateFisheye() { | |
if (pauseFisheye) { | |
g.select('.nv-point-paths').style('pointer-events', 'all'); | |
return false; | |
} | |
g.select('.nv-point-paths').style('pointer-events', 'none' ); | |
var mouse = d3.mouse(this); | |
x.distortion(fisheye).focus(mouse[0]); | |
y.distortion(fisheye).focus(mouse[1]); | |
g.select('.nv-scatterWrap') | |
.call(scatter); | |
if (showXAxis) | |
g.select('.nv-x.nv-axis').call(xAxis); | |
if (showYAxis) | |
g.select('.nv-y.nv-axis').call(yAxis); | |
g.select('.nv-distributionX') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distX); | |
g.select('.nv-distributionY') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distY); | |
} | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
controls.dispatch.on('legendClick', function(d,i) { | |
d.disabled = !d.disabled; | |
fisheye = d.disabled ? 0 : 2.5; | |
g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all'); | |
g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' ); | |
if (d.disabled) { | |
x.distortion(fisheye).focus(0); | |
y.distortion(fisheye).focus(0); | |
g.select('.nv-scatterWrap').call(scatter); | |
g.select('.nv-x.nv-axis').call(xAxis); | |
g.select('.nv-y.nv-axis').call(yAxis); | |
} else { | |
pauseFisheye = false; | |
} | |
chart.update(); | |
}); | |
legend.dispatch.on('stateChange', function(newState) { | |
state.disabled = newState.disabled; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
scatter.dispatch.on('elementMouseover.tooltip', function(e) { | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) | |
.attr('y1', function(d,i) { return e.pos[1] - availableHeight;}); | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) | |
.attr('x2', e.pos[0] + distX.size()); | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
//store old scales for use in transitions on update | |
x0 = x.copy(); | |
y0 = y.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
scatter.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) | |
.attr('y1', 0); | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) | |
.attr('x2', distY.size()); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.scatter = scatter; | |
chart.legend = legend; | |
chart.controls = controls; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
chart.distX = distX; | |
chart.distY = distY; | |
d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
distX.color(color); | |
distY.color(color); | |
return chart; | |
}; | |
chart.showDistX = function(_) { | |
if (!arguments.length) return showDistX; | |
showDistX = _; | |
return chart; | |
}; | |
chart.showDistY = function(_) { | |
if (!arguments.length) return showDistY; | |
showDistY = _; | |
return chart; | |
}; | |
chart.showControls = function(_) { | |
if (!arguments.length) return showControls; | |
showControls = _; | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.fisheye = function(_) { | |
if (!arguments.length) return fisheye; | |
fisheye = _; | |
return chart; | |
}; | |
chart.xPadding = function(_) { | |
if (!arguments.length) return xPadding; | |
xPadding = _; | |
return chart; | |
}; | |
chart.yPadding = function(_) { | |
if (!arguments.length) return yPadding; | |
yPadding = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.tooltipXContent = function(_) { | |
if (!arguments.length) return tooltipX; | |
tooltipX = _; | |
return chart; | |
}; | |
chart.tooltipYContent = function(_) { | |
if (!arguments.length) return tooltipY; | |
tooltipY = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.scatterPlusLineChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var scatter = nv.models.scatter() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend() | |
, controls = nv.models.legend() | |
, distX = nv.models.distribution() | |
, distY = nv.models.distribution() | |
; | |
var margin = {top: 30, right: 20, bottom: 50, left: 75} | |
, width = null | |
, height = null | |
, color = nv.utils.defaultColor() | |
, x = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.xScale() | |
, y = d3.fisheye ? d3.fisheye.scale(d3.scale.linear).distortion(0) : scatter.yScale() | |
, showDistX = false | |
, showDistY = false | |
, showLegend = true | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, showControls = !!d3.fisheye | |
, fisheye = 0 | |
, pauseFisheye = false | |
, tooltips = true | |
, tooltipX = function(key, x, y) { return '<strong>' + x + '</strong>' } | |
, tooltipY = function(key, x, y) { return '<strong>' + y + '</strong>' } | |
, tooltip = function(key, x, y, date) { return '<h3>' + key + '</h3>' | |
+ '<p>' + date + '</p>' } | |
, state = {} | |
, defaultState = null | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, noData = "No Data Available." | |
, transitionDuration = 250 | |
; | |
scatter | |
.xScale(x) | |
.yScale(y) | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(10) | |
; | |
yAxis | |
.orient((rightAlignYAxis) ? 'right' : 'left') | |
.tickPadding(10) | |
; | |
distX | |
.axis('x') | |
; | |
distY | |
.axis('y') | |
; | |
controls.updateState(false); | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var x0, y0; | |
var showTooltip = function(e, offsetElement) { | |
//TODO: make tooltip style an option between single or dual on axes (maybe on all charts with axes?) | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
leftX = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
topX = y.range()[0] + margin.top + ( offsetElement.offsetTop || 0), | |
leftY = x.range()[0] + margin.left + ( offsetElement.offsetLeft || 0 ), | |
topY = e.pos[1] + ( offsetElement.offsetTop || 0), | |
xVal = xAxis.tickFormat()(scatter.x()(e.point, e.pointIndex)), | |
yVal = yAxis.tickFormat()(scatter.y()(e.point, e.pointIndex)); | |
if( tooltipX != null ) | |
nv.tooltip.show([leftX, topX], tooltipX(e.series.key, xVal, yVal, e, chart), 'n', 1, offsetElement, 'x-nvtooltip'); | |
if( tooltipY != null ) | |
nv.tooltip.show([leftY, topY], tooltipY(e.series.key, xVal, yVal, e, chart), 'e', 1, offsetElement, 'y-nvtooltip'); | |
if( tooltip != null ) | |
nv.tooltip.show([left, top], tooltip(e.series.key, xVal, yVal, e.point.tooltip, e, chart), e.value < 0 ? 'n' : 's', null, offsetElement); | |
}; | |
var controlsData = [ | |
{ key: 'Magnify', disabled: true } | |
]; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart); }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display noData message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = scatter.xScale(); | |
y = scatter.yScale(); | |
x0 = x0 || x; | |
y0 = y0 || y; | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-scatterChart').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-scatterChart nv-chart-' + scatter.id()); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g') | |
// background for pointer events | |
gEnter.append('rect').attr('class', 'nvd3 nv-background').style("pointer-events","none"); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis'); | |
gEnter.append('g').attr('class', 'nv-scatterWrap'); | |
gEnter.append('g').attr('class', 'nv-regressionLinesWrap'); | |
gEnter.append('g').attr('class', 'nv-distWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
gEnter.append('g').attr('class', 'nv-controlsWrap'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
legend.width( availableWidth / 2 ); | |
wrap.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
wrap.select('.nv-legendWrap') | |
.attr('transform', 'translate(' + (availableWidth / 2) + ',' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Controls | |
if (showControls) { | |
controls.width(180).color(['#444']); | |
g.select('.nv-controlsWrap') | |
.datum(controlsData) | |
.attr('transform', 'translate(0,' + (-margin.top) +')') | |
.call(controls); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
scatter | |
.width(availableWidth) | |
.height(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })) | |
wrap.select('.nv-scatterWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(scatter); | |
wrap.select('.nv-regressionLinesWrap') | |
.attr('clip-path', 'url(#nv-edge-clip-' + scatter.id() + ')'); | |
var regWrap = wrap.select('.nv-regressionLinesWrap').selectAll('.nv-regLines') | |
.data(function(d) {return d }); | |
regWrap.enter().append('g').attr('class', 'nv-regLines'); | |
var regLine = regWrap.selectAll('.nv-regLine').data(function(d){return [d]}); | |
var regLineEnter = regLine.enter() | |
.append('line').attr('class', 'nv-regLine') | |
.style('stroke-opacity', 0); | |
regLine | |
.transition() | |
.attr('x1', x.range()[0]) | |
.attr('x2', x.range()[1]) | |
.attr('y1', function(d,i) {return y(x.domain()[0] * d.slope + d.intercept) }) | |
.attr('y2', function(d,i) { return y(x.domain()[1] * d.slope + d.intercept) }) | |
.style('stroke', function(d,i,j) { return color(d,j) }) | |
.style('stroke-opacity', function(d,i) { | |
return (d.disabled || typeof d.slope === 'undefined' || typeof d.intercept === 'undefined') ? 0 : 1 | |
}); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.ticks( xAxis.ticks() ? xAxis.ticks() : availableWidth / 100 ) | |
.tickSize( -availableHeight , 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')') | |
.call(xAxis); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks( yAxis.ticks() ? yAxis.ticks() : availableHeight / 36 ) | |
.tickSize( -availableWidth, 0); | |
g.select('.nv-y.nv-axis') | |
.call(yAxis); | |
} | |
if (showDistX) { | |
distX | |
.getData(scatter.x()) | |
.scale(x) | |
.width(availableWidth) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })); | |
gEnter.select('.nv-distWrap').append('g') | |
.attr('class', 'nv-distributionX'); | |
g.select('.nv-distributionX') | |
.attr('transform', 'translate(0,' + y.range()[0] + ')') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distX); | |
} | |
if (showDistY) { | |
distY | |
.getData(scatter.y()) | |
.scale(y) | |
.width(availableHeight) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, i); | |
}).filter(function(d,i) { return !data[i].disabled })); | |
gEnter.select('.nv-distWrap').append('g') | |
.attr('class', 'nv-distributionY'); | |
g.select('.nv-distributionY') | |
.attr('transform', 'translate(' + (rightAlignYAxis ? availableWidth : -distY.size() ) + ',0)') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distY); | |
} | |
//------------------------------------------------------------ | |
if (d3.fisheye) { | |
g.select('.nv-background') | |
.attr('width', availableWidth) | |
.attr('height', availableHeight) | |
; | |
g.select('.nv-background').on('mousemove', updateFisheye); | |
g.select('.nv-background').on('click', function() { pauseFisheye = !pauseFisheye;}); | |
scatter.dispatch.on('elementClick.freezeFisheye', function() { | |
pauseFisheye = !pauseFisheye; | |
}); | |
} | |
function updateFisheye() { | |
if (pauseFisheye) { | |
g.select('.nv-point-paths').style('pointer-events', 'all'); | |
return false; | |
} | |
g.select('.nv-point-paths').style('pointer-events', 'none' ); | |
var mouse = d3.mouse(this); | |
x.distortion(fisheye).focus(mouse[0]); | |
y.distortion(fisheye).focus(mouse[1]); | |
g.select('.nv-scatterWrap') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(scatter); | |
if (showXAxis) | |
g.select('.nv-x.nv-axis').call(xAxis); | |
if (showYAxis) | |
g.select('.nv-y.nv-axis').call(yAxis); | |
g.select('.nv-distributionX') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distX); | |
g.select('.nv-distributionY') | |
.datum(data.filter(function(d) { return !d.disabled })) | |
.call(distY); | |
} | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
controls.dispatch.on('legendClick', function(d,i) { | |
d.disabled = !d.disabled; | |
fisheye = d.disabled ? 0 : 2.5; | |
g.select('.nv-background') .style('pointer-events', d.disabled ? 'none' : 'all'); | |
g.select('.nv-point-paths').style('pointer-events', d.disabled ? 'all' : 'none' ); | |
if (d.disabled) { | |
x.distortion(fisheye).focus(0); | |
y.distortion(fisheye).focus(0); | |
g.select('.nv-scatterWrap').call(scatter); | |
g.select('.nv-x.nv-axis').call(xAxis); | |
g.select('.nv-y.nv-axis').call(yAxis); | |
} else { | |
pauseFisheye = false; | |
} | |
chart.update(); | |
}); | |
legend.dispatch.on('stateChange', function(newState) { | |
state = newState; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
scatter.dispatch.on('elementMouseover.tooltip', function(e) { | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) | |
.attr('y1', e.pos[1] - availableHeight); | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) | |
.attr('x2', e.pos[0] + distX.size()); | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top]; | |
dispatch.tooltipShow(e); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined') { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
chart.update(); | |
}); | |
//============================================================ | |
//store old scales for use in transitions on update | |
x0 = x.copy(); | |
y0 = y.copy(); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
scatter.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-distx-' + e.pointIndex) | |
.attr('y1', 0); | |
d3.select('.nv-chart-' + scatter.id() + ' .nv-series-' + e.seriesIndex + ' .nv-disty-' + e.pointIndex) | |
.attr('x2', distY.size()); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.scatter = scatter; | |
chart.legend = legend; | |
chart.controls = controls; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
chart.distX = distX; | |
chart.distY = distY; | |
d3.rebind(chart, scatter, 'id', 'interactive', 'pointActive', 'x', 'y', 'shape', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange', 'sizeDomain', 'sizeRange', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'clipRadius', 'useVoronoi'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
distX.color(color); | |
distY.color(color); | |
return chart; | |
}; | |
chart.showDistX = function(_) { | |
if (!arguments.length) return showDistX; | |
showDistX = _; | |
return chart; | |
}; | |
chart.showDistY = function(_) { | |
if (!arguments.length) return showDistY; | |
showDistY = _; | |
return chart; | |
}; | |
chart.showControls = function(_) { | |
if (!arguments.length) return showControls; | |
showControls = _; | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.fisheye = function(_) { | |
if (!arguments.length) return fisheye; | |
fisheye = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.tooltipXContent = function(_) { | |
if (!arguments.length) return tooltipX; | |
tooltipX = _; | |
return chart; | |
}; | |
chart.tooltipYContent = function(_) { | |
if (!arguments.length) return tooltipY; | |
tooltipY = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.sparkline = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 2, right: 0, bottom: 2, left: 0} | |
, width = 400 | |
, height = 32 | |
, animate = true | |
, x = d3.scale.linear() | |
, y = d3.scale.linear() | |
, getX = function(d) { return d.x } | |
, getY = function(d) { return d.y } | |
, color = nv.utils.getColor(['#000']) | |
, xDomain | |
, yDomain | |
, xRange | |
, yRange | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup Scales | |
x .domain(xDomain || d3.extent(data, getX )) | |
.range(xRange || [0, availableWidth]); | |
y .domain(yDomain || d3.extent(data, getY )) | |
.range(yRange || [availableHeight, 0]); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-sparkline').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparkline'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') | |
//------------------------------------------------------------ | |
var paths = wrap.selectAll('path') | |
.data(function(d) { return [d] }); | |
paths.enter().append('path'); | |
paths.exit().remove(); | |
paths | |
.style('stroke', function(d,i) { return d.color || color(d, i) }) | |
.attr('d', d3.svg.line() | |
.x(function(d,i) { return x(getX(d,i)) }) | |
.y(function(d,i) { return y(getY(d,i)) }) | |
); | |
// TODO: Add CURRENT data point (Need Min, Mac, Current / Most recent) | |
var points = wrap.selectAll('circle.nv-point') | |
.data(function(data) { | |
var yValues = data.map(function(d, i) { return getY(d,i); }); | |
function pointIndex(index) { | |
if (index != -1) { | |
var result = data[index]; | |
result.pointIndex = index; | |
return result; | |
} else { | |
return null; | |
} | |
} | |
var maxPoint = pointIndex(yValues.lastIndexOf(y.domain()[1])), | |
minPoint = pointIndex(yValues.indexOf(y.domain()[0])), | |
currentPoint = pointIndex(yValues.length - 1); | |
return [minPoint, maxPoint, currentPoint].filter(function (d) {return d != null;}); | |
}); | |
points.enter().append('circle'); | |
points.exit().remove(); | |
points | |
.attr('cx', function(d,i) { return x(getX(d,d.pointIndex)) }) | |
.attr('cy', function(d,i) { return y(getY(d,d.pointIndex)) }) | |
.attr('r', 2) | |
.attr('class', function(d,i) { | |
return getX(d, d.pointIndex) == x.domain()[1] ? 'nv-point nv-currentValue' : | |
getY(d, d.pointIndex) == y.domain()[0] ? 'nv-point nv-minValue' : 'nv-point nv-maxValue' | |
}); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = d3.functor(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = d3.functor(_); | |
return chart; | |
}; | |
chart.xScale = function(_) { | |
if (!arguments.length) return x; | |
x = _; | |
return chart; | |
}; | |
chart.yScale = function(_) { | |
if (!arguments.length) return y; | |
y = _; | |
return chart; | |
}; | |
chart.xDomain = function(_) { | |
if (!arguments.length) return xDomain; | |
xDomain = _; | |
return chart; | |
}; | |
chart.yDomain = function(_) { | |
if (!arguments.length) return yDomain; | |
yDomain = _; | |
return chart; | |
}; | |
chart.xRange = function(_) { | |
if (!arguments.length) return xRange; | |
xRange = _; | |
return chart; | |
}; | |
chart.yRange = function(_) { | |
if (!arguments.length) return yRange; | |
yRange = _; | |
return chart; | |
}; | |
chart.animate = function(_) { | |
if (!arguments.length) return animate; | |
animate = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.sparklinePlus = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var sparkline = nv.models.sparkline(); | |
var margin = {top: 15, right: 100, bottom: 10, left: 50} | |
, width = null | |
, height = null | |
, x | |
, y | |
, index = [] | |
, paused = false | |
, xTickFormat = d3.format(',r') | |
, yTickFormat = d3.format(',.2f') | |
, showValue = true | |
, alignValue = true | |
, rightAlignValue = false | |
, noData = "No Data Available." | |
; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this); | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { chart(selection) }; | |
chart.container = this; | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
var currentValue = sparkline.y()(data[data.length-1], data.length-1); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = sparkline.xScale(); | |
y = sparkline.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-sparklineplus').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-sparklineplus'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-sparklineWrap'); | |
gEnter.append('g').attr('class', 'nv-valueWrap'); | |
gEnter.append('g').attr('class', 'nv-hoverArea'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
var sparklineWrap = g.select('.nv-sparklineWrap'); | |
sparkline | |
.width(availableWidth) | |
.height(availableHeight); | |
sparklineWrap | |
.call(sparkline); | |
//------------------------------------------------------------ | |
var valueWrap = g.select('.nv-valueWrap'); | |
var value = valueWrap.selectAll('.nv-currentValue') | |
.data([currentValue]); | |
value.enter().append('text').attr('class', 'nv-currentValue') | |
.attr('dx', rightAlignValue ? -8 : 8) | |
.attr('dy', '.9em') | |
.style('text-anchor', rightAlignValue ? 'end' : 'start'); | |
value | |
.attr('x', availableWidth + (rightAlignValue ? margin.right : 0)) | |
.attr('y', alignValue ? function(d) { return y(d) } : 0) | |
.style('fill', sparkline.color()(data[data.length-1], data.length-1)) | |
.text(yTickFormat(currentValue)); | |
gEnter.select('.nv-hoverArea').append('rect') | |
.on('mousemove', sparklineHover) | |
.on('click', function() { paused = !paused }) | |
.on('mouseout', function() { index = []; updateValueLine(); }); | |
//.on('mouseout', function() { index = null; updateValueLine(); }); | |
g.select('.nv-hoverArea rect') | |
.attr('transform', function(d) { return 'translate(' + -margin.left + ',' + -margin.top + ')' }) | |
.attr('width', availableWidth + margin.left + margin.right) | |
.attr('height', availableHeight + margin.top); | |
function updateValueLine() { //index is currently global (within the chart), may or may not keep it that way | |
if (paused) return; | |
var hoverValue = g.selectAll('.nv-hoverValue').data(index) | |
var hoverEnter = hoverValue.enter() | |
.append('g').attr('class', 'nv-hoverValue') | |
.style('stroke-opacity', 0) | |
.style('fill-opacity', 0); | |
hoverValue.exit() | |
.transition().duration(250) | |
.style('stroke-opacity', 0) | |
.style('fill-opacity', 0) | |
.remove(); | |
hoverValue | |
.attr('transform', function(d) { return 'translate(' + x(sparkline.x()(data[d],d)) + ',0)' }) | |
.transition().duration(250) | |
.style('stroke-opacity', 1) | |
.style('fill-opacity', 1); | |
if (!index.length) return; | |
hoverEnter.append('line') | |
.attr('x1', 0) | |
.attr('y1', -margin.top) | |
.attr('x2', 0) | |
.attr('y2', availableHeight); | |
hoverEnter.append('text').attr('class', 'nv-xValue') | |
.attr('x', -6) | |
.attr('y', -margin.top) | |
.attr('text-anchor', 'end') | |
.attr('dy', '.9em') | |
g.select('.nv-hoverValue .nv-xValue') | |
.text(xTickFormat(sparkline.x()(data[index[0]], index[0]))); | |
hoverEnter.append('text').attr('class', 'nv-yValue') | |
.attr('x', 6) | |
.attr('y', -margin.top) | |
.attr('text-anchor', 'start') | |
.attr('dy', '.9em') | |
g.select('.nv-hoverValue .nv-yValue') | |
.text(yTickFormat(sparkline.y()(data[index[0]], index[0]))); | |
} | |
function sparklineHover() { | |
if (paused) return; | |
var pos = d3.mouse(this)[0] - margin.left; | |
function getClosestIndex(data, x) { | |
var distance = Math.abs(sparkline.x()(data[0], 0) - x); | |
var closestIndex = 0; | |
for (var i = 0; i < data.length; i++){ | |
if (Math.abs(sparkline.x()(data[i], i) - x) < distance) { | |
distance = Math.abs(sparkline.x()(data[i], i) - x); | |
closestIndex = i; | |
} | |
} | |
return closestIndex; | |
} | |
index = [getClosestIndex(data, Math.round(x.invert(pos)))]; | |
updateValueLine(); | |
} | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.sparkline = sparkline; | |
d3.rebind(chart, sparkline, 'x', 'y', 'xScale', 'yScale', 'color'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.xTickFormat = function(_) { | |
if (!arguments.length) return xTickFormat; | |
xTickFormat = _; | |
return chart; | |
}; | |
chart.yTickFormat = function(_) { | |
if (!arguments.length) return yTickFormat; | |
yTickFormat = _; | |
return chart; | |
}; | |
chart.showValue = function(_) { | |
if (!arguments.length) return showValue; | |
showValue = _; | |
return chart; | |
}; | |
chart.alignValue = function(_) { | |
if (!arguments.length) return alignValue; | |
alignValue = _; | |
return chart; | |
}; | |
chart.rightAlignValue = function(_) { | |
if (!arguments.length) return rightAlignValue; | |
rightAlignValue = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.stackedArea = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var margin = {top: 0, right: 0, bottom: 0, left: 0} | |
, width = 960 | |
, height = 500 | |
, color = nv.utils.defaultColor() // a function that computes the color | |
, id = Math.floor(Math.random() * 100000) //Create semi-unique ID incase user doesn't selet one | |
, getX = function(d) { return d.x } // accessor to get the x value from a data point | |
, getY = function(d) { return d.y } // accessor to get the y value from a data point | |
, style = 'stack' | |
, offset = 'zero' | |
, order = 'default' | |
, interpolate = 'linear' // controls the line interpolation | |
, clipEdge = false // if true, masks lines within x and y scale | |
, x //can be accessed via chart.xScale() | |
, y //can be accessed via chart.yScale() | |
, scatter = nv.models.scatter() | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'areaClick', 'areaMouseover', 'areaMouseout') | |
; | |
scatter | |
.size(2.2) // default size | |
.sizeDomain([2.2,2.2]) // all the same size by default | |
; | |
/************************************ | |
* offset: | |
* 'wiggle' (stream) | |
* 'zero' (stacked) | |
* 'expand' (normalize to 100%) | |
* 'silhouette' (simple centered) | |
* | |
* order: | |
* 'inside-out' (stream) | |
* 'default' (input order) | |
************************************/ | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var availableWidth = width - margin.left - margin.right, | |
availableHeight = height - margin.top - margin.bottom, | |
container = d3.select(this); | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = scatter.xScale(); | |
y = scatter.yScale(); | |
//------------------------------------------------------------ | |
var dataRaw = data; | |
// Injecting point index into each point because d3.layout.stack().out does not give index | |
data.forEach(function(aseries, i) { | |
aseries.seriesIndex = i; | |
aseries.values = aseries.values.map(function(d, j) { | |
d.index = j; | |
d.seriesIndex = i; | |
return d; | |
}); | |
}); | |
var dataFiltered = data.filter(function(series) { | |
return !series.disabled; | |
}); | |
data = d3.layout.stack() | |
.order(order) | |
.offset(offset) | |
.values(function(d) { return d.values }) //TODO: make values customizeable in EVERY model in this fashion | |
.x(getX) | |
.y(getY) | |
.out(function(d, y0, y) { | |
var yHeight = (getY(d) === 0) ? 0 : y; | |
d.display = { | |
y: yHeight, | |
y0: y0 | |
}; | |
}) | |
(dataFiltered); | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-stackedarea').data([data]); | |
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedarea'); | |
var defsEnter = wrapEnter.append('defs'); | |
var gEnter = wrapEnter.append('g'); | |
var g = wrap.select('g'); | |
gEnter.append('g').attr('class', 'nv-areaWrap'); | |
gEnter.append('g').attr('class', 'nv-scatterWrap'); | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
//------------------------------------------------------------ | |
scatter | |
.width(availableWidth) | |
.height(availableHeight) | |
.x(getX) | |
.y(function(d) { return d.display.y + d.display.y0 }) | |
.forceY([0]) | |
.color(data.map(function(d,i) { | |
return d.color || color(d, d.seriesIndex); | |
})); | |
var scatterWrap = g.select('.nv-scatterWrap') | |
.datum(data); | |
scatterWrap.call(scatter); | |
defsEnter.append('clipPath') | |
.attr('id', 'nv-edge-clip-' + id) | |
.append('rect'); | |
wrap.select('#nv-edge-clip-' + id + ' rect') | |
.attr('width', availableWidth) | |
.attr('height', availableHeight); | |
g .attr('clip-path', clipEdge ? 'url(#nv-edge-clip-' + id + ')' : ''); | |
var area = d3.svg.area() | |
.x(function(d,i) { return x(getX(d,i)) }) | |
.y0(function(d) { | |
return y(d.display.y0) | |
}) | |
.y1(function(d) { | |
return y(d.display.y + d.display.y0) | |
}) | |
.interpolate(interpolate); | |
var zeroArea = d3.svg.area() | |
.x(function(d,i) { return x(getX(d,i)) }) | |
.y0(function(d) { return y(d.display.y0) }) | |
.y1(function(d) { return y(d.display.y0) }); | |
var path = g.select('.nv-areaWrap').selectAll('path.nv-area') | |
.data(function(d) { return d }); | |
path.enter().append('path').attr('class', function(d,i) { return 'nv-area nv-area-' + i }) | |
.attr('d', function(d,i){ | |
return zeroArea(d.values, d.seriesIndex); | |
}) | |
.on('mouseover', function(d,i) { | |
d3.select(this).classed('hover', true); | |
dispatch.areaMouseover({ | |
point: d, | |
series: d.key, | |
pos: [d3.event.pageX, d3.event.pageY], | |
seriesIndex: d.seriesIndex | |
}); | |
}) | |
.on('mouseout', function(d,i) { | |
d3.select(this).classed('hover', false); | |
dispatch.areaMouseout({ | |
point: d, | |
series: d.key, | |
pos: [d3.event.pageX, d3.event.pageY], | |
seriesIndex: d.seriesIndex | |
}); | |
}) | |
.on('click', function(d,i) { | |
d3.select(this).classed('hover', false); | |
dispatch.areaClick({ | |
point: d, | |
series: d.key, | |
pos: [d3.event.pageX, d3.event.pageY], | |
seriesIndex: d.seriesIndex | |
}); | |
}) | |
path.exit().remove(); | |
path | |
.style('fill', function(d,i){ | |
return d.color || color(d, d.seriesIndex) | |
}) | |
.style('stroke', function(d,i){ return d.color || color(d, d.seriesIndex) }); | |
path.transition() | |
.attr('d', function(d,i) { | |
return area(d.values,i) | |
}); | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
scatter.dispatch.on('elementMouseover.area', function(e) { | |
g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', true); | |
}); | |
scatter.dispatch.on('elementMouseout.area', function(e) { | |
g.select('.nv-chart-' + id + ' .nv-area-' + e.seriesIndex).classed('hover', false); | |
}); | |
//============================================================ | |
//Special offset functions | |
chart.d3_stackedOffset_stackPercent = function(stackData) { | |
var n = stackData.length, //How many series | |
m = stackData[0].length, //how many points per series | |
k = 1 / n, | |
i, | |
j, | |
o, | |
y0 = []; | |
for (j = 0; j < m; ++j) { //Looping through all points | |
for (i = 0, o = 0; i < dataRaw.length; i++) //looping through series' | |
o += getY(dataRaw[i].values[j]) //total value of all points at a certian point in time. | |
if (o) for (i = 0; i < n; i++) | |
stackData[i][j][1] /= o; | |
else | |
for (i = 0; i < n; i++) | |
stackData[i][j][1] = k; | |
} | |
for (j = 0; j < m; ++j) y0[j] = 0; | |
return y0; | |
}; | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
scatter.dispatch.on('elementClick.area', function(e) { | |
dispatch.areaClick(e); | |
}) | |
scatter.dispatch.on('elementMouseover.tooltip', function(e) { | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], | |
dispatch.tooltipShow(e); | |
}); | |
scatter.dispatch.on('elementMouseout.tooltip', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
//============================================================ | |
//============================================================ | |
// Global getters and setters | |
//------------------------------------------------------------ | |
chart.dispatch = dispatch; | |
chart.scatter = scatter; | |
d3.rebind(chart, scatter, 'interactive', 'size', 'xScale', 'yScale', 'zScale', 'xDomain', 'yDomain', 'xRange', 'yRange', | |
'sizeDomain', 'forceX', 'forceY', 'forceSize', 'clipVoronoi', 'useVoronoi','clipRadius','highlightPoint','clearHighlights'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.x = function(_) { | |
if (!arguments.length) return getX; | |
getX = d3.functor(_); | |
return chart; | |
}; | |
chart.y = function(_) { | |
if (!arguments.length) return getY; | |
getY = d3.functor(_); | |
return chart; | |
} | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.clipEdge = function(_) { | |
if (!arguments.length) return clipEdge; | |
clipEdge = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
return chart; | |
}; | |
chart.offset = function(_) { | |
if (!arguments.length) return offset; | |
offset = _; | |
return chart; | |
}; | |
chart.order = function(_) { | |
if (!arguments.length) return order; | |
order = _; | |
return chart; | |
}; | |
//shortcut for offset + order | |
chart.style = function(_) { | |
if (!arguments.length) return style; | |
style = _; | |
switch (style) { | |
case 'stack': | |
chart.offset('zero'); | |
chart.order('default'); | |
break; | |
case 'stream': | |
chart.offset('wiggle'); | |
chart.order('inside-out'); | |
break; | |
case 'stream-center': | |
chart.offset('silhouette'); | |
chart.order('inside-out'); | |
break; | |
case 'expand': | |
chart.offset('expand'); | |
chart.order('default'); | |
break; | |
case 'stack_percent': | |
chart.offset(chart.d3_stackedOffset_stackPercent); | |
chart.order('default'); | |
break; | |
} | |
return chart; | |
}; | |
chart.interpolate = function(_) { | |
if (!arguments.length) return interpolate; | |
interpolate = _; | |
return chart; | |
}; | |
//============================================================ | |
return chart; | |
} | |
nv.models.stackedAreaChart = function() { | |
"use strict"; | |
//============================================================ | |
// Public Variables with Default Settings | |
//------------------------------------------------------------ | |
var stacked = nv.models.stackedArea() | |
, xAxis = nv.models.axis() | |
, yAxis = nv.models.axis() | |
, legend = nv.models.legend() | |
, controls = nv.models.legend() | |
, interactiveLayer = nv.interactiveGuideline() | |
; | |
var margin = {top: 30, right: 25, bottom: 50, left: 60} | |
, width = null | |
, height = null | |
, color = nv.utils.defaultColor() // a function that takes in d, i and returns color | |
, showControls = true | |
, showLegend = true | |
, showXAxis = true | |
, showYAxis = true | |
, rightAlignYAxis = false | |
, useInteractiveGuideline = false | |
, tooltips = true | |
, tooltip = function(key, x, y, e, graph) { | |
return '<h3>' + key + '</h3>' + | |
'<p>' + y + ' on ' + x + '</p>' | |
} | |
, x //can be accessed via chart.xScale() | |
, y //can be accessed via chart.yScale() | |
, yAxisTickFormat = d3.format(',.2f') | |
, state = { style: stacked.style() } | |
, defaultState = null | |
, noData = 'No Data Available.' | |
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide', 'stateChange', 'changeState') | |
, controlWidth = 250 | |
, cData = ['Stacked','Stream','Expanded'] | |
, controlLabels = {} | |
, transitionDuration = 250 | |
; | |
xAxis | |
.orient('bottom') | |
.tickPadding(7) | |
; | |
yAxis | |
.orient((rightAlignYAxis) ? 'right' : 'left') | |
; | |
controls.updateState(false); | |
//============================================================ | |
//============================================================ | |
// Private Variables | |
//------------------------------------------------------------ | |
var showTooltip = function(e, offsetElement) { | |
var left = e.pos[0] + ( offsetElement.offsetLeft || 0 ), | |
top = e.pos[1] + ( offsetElement.offsetTop || 0), | |
x = xAxis.tickFormat()(stacked.x()(e.point, e.pointIndex)), | |
y = yAxis.tickFormat()(stacked.y()(e.point, e.pointIndex)), | |
content = tooltip(e.series.key, x, y, e, chart); | |
nv.tooltip.show([left, top], content, e.value < 0 ? 'n' : 's', null, offsetElement); | |
}; | |
//============================================================ | |
function chart(selection) { | |
selection.each(function(data) { | |
var container = d3.select(this), | |
that = this; | |
var availableWidth = (width || parseInt(container.style('width')) || 960) | |
- margin.left - margin.right, | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
chart.update = function() { container.transition().duration(transitionDuration).call(chart); }; | |
chart.container = this; | |
//set state.disabled | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
if (!defaultState) { | |
var key; | |
defaultState = {}; | |
for (key in state) { | |
if (state[key] instanceof Array) | |
defaultState[key] = state[key].slice(0); | |
else | |
defaultState[key] = state[key]; | |
} | |
} | |
//------------------------------------------------------------ | |
// Display No Data message if there's nothing to show. | |
if (!data || !data.length || !data.filter(function(d) { return d.values.length }).length) { | |
var noDataText = container.selectAll('.nv-noData').data([noData]); | |
noDataText.enter().append('text') | |
.attr('class', 'nvd3 nv-noData') | |
.attr('dy', '-.7em') | |
.style('text-anchor', 'middle'); | |
noDataText | |
.attr('x', margin.left + availableWidth / 2) | |
.attr('y', margin.top + availableHeight / 2) | |
.text(function(d) { return d }); | |
return chart; | |
} else { | |
container.selectAll('.nv-noData').remove(); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Scales | |
x = stacked.xScale(); | |
y = stacked.yScale(); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup containers and skeleton of chart | |
var wrap = container.selectAll('g.nv-wrap.nv-stackedAreaChart').data([data]); | |
var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-stackedAreaChart').append('g'); | |
var g = wrap.select('g'); | |
gEnter.append("rect").style("opacity",0); | |
gEnter.append('g').attr('class', 'nv-x nv-axis'); | |
gEnter.append('g').attr('class', 'nv-y nv-axis'); | |
gEnter.append('g').attr('class', 'nv-stackedWrap'); | |
gEnter.append('g').attr('class', 'nv-legendWrap'); | |
gEnter.append('g').attr('class', 'nv-controlsWrap'); | |
gEnter.append('g').attr('class', 'nv-interactive'); | |
g.select("rect").attr("width",availableWidth).attr("height",availableHeight); | |
//------------------------------------------------------------ | |
// Legend | |
if (showLegend) { | |
var legendWidth = (showControls) ? availableWidth - controlWidth : availableWidth; | |
legend | |
.width(legendWidth); | |
g.select('.nv-legendWrap') | |
.datum(data) | |
.call(legend); | |
if ( margin.top != legend.height()) { | |
margin.top = legend.height(); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
g.select('.nv-legendWrap') | |
.attr('transform', 'translate(' + (availableWidth-legendWidth) + ',' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Controls | |
if (showControls) { | |
var controlsData = [ | |
{ | |
key: controlLabels.stacked || 'Stacked', | |
metaKey: 'Stacked', | |
disabled: stacked.style() != 'stack', | |
style: 'stack' | |
}, | |
{ | |
key: controlLabels.stream || 'Stream', | |
metaKey: 'Stream', | |
disabled: stacked.style() != 'stream', | |
style: 'stream' | |
}, | |
{ | |
key: controlLabels.expanded || 'Expanded', | |
metaKey: 'Expanded', | |
disabled: stacked.style() != 'expand', | |
style: 'expand' | |
}, | |
{ | |
key: controlLabels.stack_percent || 'Stack %', | |
metaKey: 'Stack_Percent', | |
disabled: stacked.style() != 'stack_percent', | |
style: 'stack_percent' | |
} | |
]; | |
controlWidth = (cData.length/3) * 260; | |
controlsData = controlsData.filter(function(d) { | |
return cData.indexOf(d.metaKey) !== -1; | |
}) | |
controls | |
.width( controlWidth ) | |
.color(['#444', '#444', '#444']); | |
g.select('.nv-controlsWrap') | |
.datum(controlsData) | |
.call(controls); | |
if ( margin.top != Math.max(controls.height(), legend.height()) ) { | |
margin.top = Math.max(controls.height(), legend.height()); | |
availableHeight = (height || parseInt(container.style('height')) || 400) | |
- margin.top - margin.bottom; | |
} | |
g.select('.nv-controlsWrap') | |
.attr('transform', 'translate(0,' + (-margin.top) +')'); | |
} | |
//------------------------------------------------------------ | |
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); | |
if (rightAlignYAxis) { | |
g.select(".nv-y.nv-axis") | |
.attr("transform", "translate(" + availableWidth + ",0)"); | |
} | |
//------------------------------------------------------------ | |
// Main Chart Component(s) | |
//------------------------------------------------------------ | |
//Set up interactive layer | |
if (useInteractiveGuideline) { | |
interactiveLayer | |
.width(availableWidth) | |
.height(availableHeight) | |
.margin({left: margin.left, top: margin.top}) | |
.svgContainer(container) | |
.xScale(x); | |
wrap.select(".nv-interactive").call(interactiveLayer); | |
} | |
stacked | |
.width(availableWidth) | |
.height(availableHeight) | |
var stackedWrap = g.select('.nv-stackedWrap') | |
.datum(data); | |
stackedWrap.transition().call(stacked); | |
//------------------------------------------------------------ | |
//------------------------------------------------------------ | |
// Setup Axes | |
if (showXAxis) { | |
xAxis | |
.scale(x) | |
.ticks( availableWidth / 100 ) | |
.tickSize( -availableHeight, 0); | |
g.select('.nv-x.nv-axis') | |
.attr('transform', 'translate(0,' + availableHeight + ')'); | |
g.select('.nv-x.nv-axis') | |
.transition().duration(0) | |
.call(xAxis); | |
} | |
if (showYAxis) { | |
yAxis | |
.scale(y) | |
.ticks(stacked.offset() == 'wiggle' ? 0 : availableHeight / 36) | |
.tickSize(-availableWidth, 0) | |
.setTickFormat( (stacked.style() == 'expand' || stacked.style() == 'stack_percent') | |
? d3.format('%') : yAxisTickFormat); | |
g.select('.nv-y.nv-axis') | |
.transition().duration(0) | |
.call(yAxis); | |
} | |
//------------------------------------------------------------ | |
//============================================================ | |
// Event Handling/Dispatching (in chart's scope) | |
//------------------------------------------------------------ | |
stacked.dispatch.on('areaClick.toggle', function(e) { | |
if (data.filter(function(d) { return !d.disabled }).length === 1) | |
data.forEach(function(d) { | |
d.disabled = false; | |
}); | |
else | |
data.forEach(function(d,i) { | |
d.disabled = (i != e.seriesIndex); | |
}); | |
state.disabled = data.map(function(d) { return !!d.disabled }); | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
legend.dispatch.on('stateChange', function(newState) { | |
state.disabled = newState.disabled; | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
controls.dispatch.on('legendClick', function(d,i) { | |
if (!d.disabled) return; | |
controlsData = controlsData.map(function(s) { | |
s.disabled = true; | |
return s; | |
}); | |
d.disabled = false; | |
stacked.style(d.style); | |
state.style = stacked.style(); | |
dispatch.stateChange(state); | |
chart.update(); | |
}); | |
interactiveLayer.dispatch.on('elementMousemove', function(e) { | |
stacked.clearHighlights(); | |
var singlePoint, pointIndex, pointXLocation, allData = []; | |
data | |
.filter(function(series, i) { | |
series.seriesIndex = i; | |
return !series.disabled; | |
}) | |
.forEach(function(series,i) { | |
pointIndex = nv.interactiveBisect(series.values, e.pointXValue, chart.x()); | |
stacked.highlightPoint(i, pointIndex, true); | |
var point = series.values[pointIndex]; | |
if (typeof point === 'undefined') return; | |
if (typeof singlePoint === 'undefined') singlePoint = point; | |
if (typeof pointXLocation === 'undefined') pointXLocation = chart.xScale()(chart.x()(point,pointIndex)); | |
//If we are in 'expand' mode, use the stacked percent value instead of raw value. | |
var tooltipValue = (stacked.style() == 'expand') ? point.display.y : chart.y()(point,pointIndex); | |
allData.push({ | |
key: series.key, | |
value: tooltipValue, | |
color: color(series,series.seriesIndex), | |
stackedValue: point.display | |
}); | |
}); | |
allData.reverse(); | |
//Highlight the tooltip entry based on which stack the mouse is closest to. | |
if (allData.length > 2) { | |
var yValue = chart.yScale().invert(e.mouseY); | |
var yDistMax = Infinity, indexToHighlight = null; | |
allData.forEach(function(series,i) { | |
//To handle situation where the stacked area chart is negative, we need to use absolute values | |
//when checking if the mouse Y value is within the stack area. | |
yValue = Math.abs(yValue); | |
var stackedY0 = Math.abs(series.stackedValue.y0); | |
var stackedY = Math.abs(series.stackedValue.y); | |
if ( yValue >= stackedY0 && yValue <= (stackedY + stackedY0)) | |
{ | |
indexToHighlight = i; | |
return; | |
} | |
}); | |
if (indexToHighlight != null) | |
allData[indexToHighlight].highlight = true; | |
} | |
var xValue = xAxis.tickFormat()(chart.x()(singlePoint,pointIndex)); | |
//If we are in 'expand' mode, force the format to be a percentage. | |
var valueFormatter = (stacked.style() == 'expand') ? | |
function(d,i) {return d3.format(".1%")(d);} : | |
function(d,i) {return yAxis.tickFormat()(d); }; | |
interactiveLayer.tooltip | |
.position({left: pointXLocation + margin.left, top: e.mouseY + margin.top}) | |
.chartContainer(that.parentNode) | |
.enabled(tooltips) | |
.valueFormatter(valueFormatter) | |
.data( | |
{ | |
value: xValue, | |
series: allData | |
} | |
)(); | |
interactiveLayer.renderGuideLine(pointXLocation); | |
}); | |
interactiveLayer.dispatch.on("elementMouseout",function(e) { | |
dispatch.tooltipHide(); | |
stacked.clearHighlights(); | |
}); | |
dispatch.on('tooltipShow', function(e) { | |
if (tooltips) showTooltip(e, that.parentNode); | |
}); | |
// Update chart from a state object passed to event handler | |
dispatch.on('changeState', function(e) { | |
if (typeof e.disabled !== 'undefined' && data.length === e.disabled.length) { | |
data.forEach(function(series,i) { | |
series.disabled = e.disabled[i]; | |
}); | |
state.disabled = e.disabled; | |
} | |
if (typeof e.style !== 'undefined') { | |
stacked.style(e.style); | |
} | |
chart.update(); | |
}); | |
}); | |
return chart; | |
} | |
//============================================================ | |
// Event Handling/Dispatching (out of chart's scope) | |
//------------------------------------------------------------ | |
stacked.dispatch.on('tooltipShow', function(e) { | |
//disable tooltips when value ~= 0 | |
//// TODO: consider removing points from voronoi that have 0 value instead of this hack | |
/* | |
if (!Math.round(stacked.y()(e.point) * 100)) { // 100 will not be good for very small numbers... will have to think about making this valu dynamic, based on data range | |
setTimeout(function() { d3.selectAll('.point.hover').classed('hover', false) }, 0); | |
return false; | |
} | |
*/ | |
e.pos = [e.pos[0] + margin.left, e.pos[1] + margin.top], | |
dispatch.tooltipShow(e); | |
}); | |
stacked.dispatch.on('tooltipHide', function(e) { | |
dispatch.tooltipHide(e); | |
}); | |
dispatch.on('tooltipHide', function() { | |
if (tooltips) nv.tooltip.cleanup(); | |
}); | |
//============================================================ | |
//============================================================ | |
// Expose Public Variables | |
//------------------------------------------------------------ | |
// expose chart's sub-components | |
chart.dispatch = dispatch; | |
chart.stacked = stacked; | |
chart.legend = legend; | |
chart.controls = controls; | |
chart.xAxis = xAxis; | |
chart.yAxis = yAxis; | |
chart.interactiveLayer = interactiveLayer; | |
d3.rebind(chart, stacked, 'x', 'y', 'size', 'xScale', 'yScale', 'xDomain', 'yDomain', 'xRange', 'yRange', 'sizeDomain', 'interactive', 'useVoronoi', 'offset', 'order', 'style', 'clipEdge', 'forceX', 'forceY', 'forceSize', 'interpolate'); | |
chart.options = nv.utils.optionsFunc.bind(chart); | |
chart.margin = function(_) { | |
if (!arguments.length) return margin; | |
margin.top = typeof _.top != 'undefined' ? _.top : margin.top; | |
margin.right = typeof _.right != 'undefined' ? _.right : margin.right; | |
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom; | |
margin.left = typeof _.left != 'undefined' ? _.left : margin.left; | |
return chart; | |
}; | |
chart.width = function(_) { | |
if (!arguments.length) return width; | |
width = _; | |
return chart; | |
}; | |
chart.height = function(_) { | |
if (!arguments.length) return height; | |
height = _; | |
return chart; | |
}; | |
chart.color = function(_) { | |
if (!arguments.length) return color; | |
color = nv.utils.getColor(_); | |
legend.color(color); | |
stacked.color(color); | |
return chart; | |
}; | |
chart.showControls = function(_) { | |
if (!arguments.length) return showControls; | |
showControls = _; | |
return chart; | |
}; | |
chart.showLegend = function(_) { | |
if (!arguments.length) return showLegend; | |
showLegend = _; | |
return chart; | |
}; | |
chart.showXAxis = function(_) { | |
if (!arguments.length) return showXAxis; | |
showXAxis = _; | |
return chart; | |
}; | |
chart.showYAxis = function(_) { | |
if (!arguments.length) return showYAxis; | |
showYAxis = _; | |
return chart; | |
}; | |
chart.rightAlignYAxis = function(_) { | |
if(!arguments.length) return rightAlignYAxis; | |
rightAlignYAxis = _; | |
yAxis.orient( (_) ? 'right' : 'left'); | |
return chart; | |
}; | |
chart.useInteractiveGuideline = function(_) { | |
if(!arguments.length) return useInteractiveGuideline; | |
useInteractiveGuideline = _; | |
if (_ === true) { | |
chart.interactive(false); | |
chart.useVoronoi(false); | |
} | |
return chart; | |
}; | |
chart.tooltip = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.tooltips = function(_) { | |
if (!arguments.length) return tooltips; | |
tooltips = _; | |
return chart; | |
}; | |
chart.tooltipContent = function(_) { | |
if (!arguments.length) return tooltip; | |
tooltip = _; | |
return chart; | |
}; | |
chart.state = function(_) { | |
if (!arguments.length) return state; | |
state = _; | |
return chart; | |
}; | |
chart.defaultState = function(_) { | |
if (!arguments.length) return defaultState; | |
defaultState = _; | |
return chart; | |
}; | |
chart.noData = function(_) { | |
if (!arguments.length) return noData; | |
noData = _; | |
return chart; | |
}; | |
chart.transitionDuration = function(_) { | |
if (!arguments.length) return transitionDuration; | |
transitionDuration = _; | |
return chart; | |
}; | |
chart.controlsData = function(_) { | |
if (!arguments.length) return cData; | |
cData = _; | |
return chart; | |
}; | |
chart.controlLabels = function(_) { | |
if (!arguments.length) return controlLabels; | |
if (typeof _ !== 'object') return controlLabels; | |
controlLabels = _; | |
return chart; | |
}; | |
yAxis.setTickFormat = yAxis.tickFormat; | |
yAxis.tickFormat = function(_) { | |
if (!arguments.length) return yAxisTickFormat; | |
yAxisTickFormat = _; | |
return yAxis; | |
}; | |
//============================================================ | |
return chart; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment