├── .gitignore ├── Gemfile ├── Gemfile.lock ├── Guardfile ├── README.md ├── app ├── css │ ├── bootstrap-responsive.min.css │ ├── bootstrap.min.css │ ├── dashboard.scss │ ├── high-contrast.scss │ └── index.css └── js │ ├── d3.gauge.js │ ├── graphene.coffee │ ├── graphene.events.js │ └── index.js ├── build ├── .gitkeep ├── index.css └── index.js ├── devstart.sh ├── example ├── dashboard-autodiscover.html ├── dashboard.html └── example-dash.js ├── graphene.min.css ├── graphene.min.js ├── images ├── dark_stripes.png └── diagmonds.png ├── run_browser.sh ├── tools └── gencolors.rb └── vendor └── js ├── backbone.js ├── d3.js ├── jquery-1.7.1.min.js └── underscore.js /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | example/spreadus.html 3 | 4 | example/spreadus.js 5 | 6 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'guard-sprockets', :git => 'https://github.com/jondot/guard-sprockets.git' 4 | gem 'coffee-script' 5 | gem 'uglifier' 6 | gem 'sass' 7 | gem 'listen', '= 1.2.2' 8 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GIT 2 | remote: https://github.com/jondot/guard-sprockets.git 3 | revision: 4c6ebac094d5f06452bcc74fe75e7c1e2c4f99f2 4 | specs: 5 | guard-sprockets (0.2.0) 6 | guard (>= 0.2.2) 7 | sprockets (~> 2) 8 | 9 | GEM 10 | remote: https://rubygems.org/ 11 | specs: 12 | coderay (1.0.9) 13 | coffee-script (2.2.0) 14 | coffee-script-source 15 | execjs 16 | coffee-script-source (1.2.0) 17 | execjs (1.3.0) 18 | multi_json (~> 1.0) 19 | ffi (1.9.0) 20 | formatador (0.2.4) 21 | guard (1.8.2) 22 | formatador (>= 0.2.4) 23 | listen (>= 1.0.0) 24 | lumberjack (>= 1.0.2) 25 | pry (>= 0.9.10) 26 | thor (>= 0.14.6) 27 | hike (1.2.3) 28 | listen (1.2.2) 29 | rb-fsevent (>= 0.9.3) 30 | rb-inotify (>= 0.9) 31 | rb-kqueue (>= 0.2) 32 | lumberjack (1.0.4) 33 | method_source (0.8.2) 34 | multi_json (1.0.4) 35 | pry (0.9.12.2) 36 | coderay (~> 1.0.5) 37 | method_source (~> 0.8) 38 | slop (~> 3.4) 39 | rack (1.5.2) 40 | rb-fsevent (0.9.3) 41 | rb-inotify (0.9.2) 42 | ffi (>= 0.5.0) 43 | rb-kqueue (0.2.0) 44 | ffi (>= 0.5.0) 45 | sass (3.1.15) 46 | slop (3.4.6) 47 | sprockets (2.10.0) 48 | hike (~> 1.2) 49 | multi_json (~> 1.0) 50 | rack (~> 1.0) 51 | tilt (~> 1.1, != 1.3.0) 52 | thor (0.18.1) 53 | tilt (1.4.1) 54 | uglifier (1.2.3) 55 | execjs (>= 0.3.0) 56 | multi_json (>= 1.0.2) 57 | 58 | PLATFORMS 59 | ruby 60 | 61 | DEPENDENCIES 62 | coffee-script 63 | guard-sprockets! 64 | listen (= 1.2.2) 65 | sass 66 | uglifier 67 | -------------------------------------------------------------------------------- /Guardfile: -------------------------------------------------------------------------------- 1 | # A sample Guardfile 2 | # More info at https://github.com/guard/guard#readme 3 | 4 | guard 'sprockets', :destination => "build", :asset_paths => ['app', '.'], :minify => true do 5 | watch (%r{^app/js/.*}){ |m| "app/js/index.js" } 6 | watch (%r{^app/css/.*}){ |m| "app/css/index.css" } 7 | end 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Graphene 2 | 3 | [Graphene](http://jondot.github.com/graphene/) is a realtime dashboard & graphing toolkit based on [D3](http://mbostock.github.com/d3/) and [Backbone](http://documentcloud.github.com/backbone/). 4 | 5 | It was made to offer a very aesthetic realtime dashboard that lives on top of [Graphite](http://graphite.wikidot.com/) (but could be tailored to any back 6 | end, eventually). 7 | 8 | Combining D3's immense capabilities of managing live data, and Backbone's 9 | ease of development, Graphene provides a solution capable of 10 | displaying thousands upon thousands of datapoints in your dashboard, as well as presenting a very hackable project to build on and customize. 11 | 12 | # Getting Started 13 | 14 | Currently, Graphene loves Graphite's data model (through its API). 15 | 16 | 17 | To start, 18 | 19 | $ git clone git://github.com/jondot/graphene.git 20 | $ cd graphene 21 | 22 | 23 | ## Running the Example 24 | 25 | Use the `/example` dashboard to build on. 26 | 27 | You should serve that folder off some kind of a helper webserver. For 28 | Ruby: 29 | 30 | $ gem install serve 31 | $ serve . 32 | 33 | And open up your browser at `http://localhost:4000/example/dashboard.html`. You 34 | should see the dashboard alive, rigged with a demo data provider. 35 | 36 | ## Setting up a Dev Env 37 | 38 | This is a no brainer. You gotta have Ruby though; back to your root 39 | Graphene folder, 40 | 41 | $ bundle install 42 | $ bundle exec guard start 43 | 44 | This gives you an autogenerated build when you modify stuff in app/css 45 | and app/js. Take note that `dashboard.html` points to the `build` folder 46 | where your assets are automatically built to. 47 | 48 | 49 | 50 | 51 | ## Building a Dashboard 52 | 53 | You are probably wondering how do you disconnect the demo data provider 54 | and plug the Graphite data source. Don't worry - more about it 55 | after this. 56 | 57 | 58 | As of now, you can place 3 types of data-enabled widgets on your 59 | dashboard: `TimeSeries`, `GaugeLabel`, and a `GaugeGadget` 60 | You can have as many of these as you want, and you can also hook up 61 | several widgets to the same data source. 62 | 63 | 64 | To build a new dashboard, you can/should use the builder: 65 | 66 | ```javascript 67 | var g = new Graphene; 68 | g.demo(); // hook up demo provider, override all urls. 69 | g.build(description); 70 | ``` 71 | 72 | 73 | Where `description` will be the hardest thing you'll have to do here. It is a hash structure, note that urls (since we use demo provider) do nothing. Here: 74 | 75 | ```javascript 76 | description = { 77 | "Total Notifications": { 78 | source: "http://localhost:4567/", 79 | GaugeLabel: { 80 | parent: "#hero-one", 81 | title: "Notifications Served", 82 | type: "max" 83 | } 84 | }, 85 | "Poll Time": { 86 | source: "http://localhost:4567/", 87 | GaugeGadget: { 88 | parent: "#hero-one", 89 | title: "P1" 90 | } 91 | }, 92 | "": { 93 | source: "", 94 | "": { 95 | parent: "", 96 | title: "" 97 | // ... many other view opts ... 98 | } 99 | } 100 | } 101 | ``` 102 | 103 | 104 | That's it basically. Advise the example for how your page should be 105 | structured. 106 | 107 | 108 | ## Using Real Data 109 | 110 | Lets see how to hook up a Graphite data source. You should first have an 111 | idea of how your dashboard looks like in "standard" graphite dashboard. 112 | 113 | This means you can go ahead and build (or use) your dash with the 114 | "standard" dashboard tool that Graphite provides. 115 | 116 | ## Cross-Domain 117 | In any case, if you don't have your dashboard on the Graphite domain, 118 | you might have a cross-domain issue. In this case please set up your Chrome browser with `google-chrome --disable-web-security`. 119 | 120 | ## Graphite Data API 121 | Then, given that you saved your Graphite dashboard named `resources`, 122 | fetch this URL: 123 | 124 | http://<graphite>/dashboard/load/resources 125 | 126 | You should see a JSON structure which contain these: 127 | 128 | 129 | /render?from=-2hours&until=now&width=400&height=250&target=some.metric&title=my_metric 130 | 131 | Use that query. Append `&format=json` to it and you've got a 132 | Graphene-ready URL! 133 | 134 | 135 | http://<graphite>/render?from=-2hours&until=now&width=400&height=250&target=some.metric&title=my_metric&format=json 136 | 137 | 138 | 139 | # Autodiscovery 140 | 141 | If all you really want is to migrate your Graphite "old" dash, a good 142 | starting point would be with `discover()`, which will take all of your 143 | timeseries and convert to a dashboard running Graphene TimeSeries: 144 | 145 | ```javascript 146 | var g = new Graphene; 147 | g.discover('http://my.graphite.host.com', 'dev-pollers', function(i, url){ return "#dashboard"; }, function(description){ 148 | g.build(description); 149 | console.log(description); 150 | }); 151 | ``` 152 | 153 | You should specify `graphite host`, `dashboard name`, a `parent 154 | specifier` which is responsible to spit out the next graph parent, and a 155 | `result callback`. 156 | 157 | You can also use the `description` result as a starting point for 158 | building a more elaborate dashboard. 159 | 160 | Check out an example at `/examples/dashboard-autodiscover.html` 161 | 162 | 163 | # I Want More! 164 | 165 | Since Graphene is really a Backbone application (View, and Model, no 166 | Controller here), you should be aware that your data is fetched to a 167 | Model, munged on, and 'broadcasted' to interested parties (such as widgets). 168 | 169 | This means you can take a look at the Model, and be able to configure it 170 | to your own needs. One example is specifying a `refresh_interval`. 171 | 172 | It wouldn't make sense to poll on your Graphite backend frequently, if the 173 | data is updated slowly; turn `refresh_interval` up a notch. 174 | 175 | ## Extra View options 176 | You can drop any of the below options in the builder's dashboard 177 | description. 178 | 179 | 180 | ### GaugeLabel 181 | 182 | * `unit` - unit to display, example "km", or "req/s" 183 | * `title` - the gauge title 184 | * `type` - how should data get aggregated? 185 | * `max` picks the largest value in the set of datapoints, 186 | * `min` picks the smallest value in the set of datapoints, 187 | * `current` picks the newest value in the set of datapoints, 188 | * null or no setting picks the first value in the set. 189 | * `value_format` - you can specify a value formatter (see d3) 190 | 191 | 192 | 193 | ### GaugeGadget 194 | 195 | * `title` - again, gauge title 196 | * `type` - same as GaugeLabel 197 | * `value_format` - value format 198 | * `from` - start value of the gauge 199 | * `to` - end value of the gauge 200 | 201 | 202 | ### TimeSeries 203 | 204 | * `line_height` - visuals, default 16 205 | * `animate_ms` - new data animation in 206 | * `num_labels` - max labels to display at the bottom 207 | * `sort_labels` - order labels will be sorted 208 | * `display_verticals` - display vertical ticks (eww!) 209 | * `width` - box width 210 | * `height` - box height 211 | * `padding` - the kind of padding you need 212 | * `title` - box title 213 | * `label_formatter` - and a formatter, as before. 214 | * `ymax` - the max value for the Y axis. If not specified and the URL has a yMax parameter, the value will be taken from the URL. Otherwise, this option will have precedence. 215 | * `ymin` - the min value for the Y axis. 216 | 217 | 218 | # Visuals 219 | 220 | Good news, other than problems with managing TONS of data points, I avoided using common graphing libraries because it's kinda hard to fit to how they see the world in terms of styling. 221 | 222 | Here you'll be able to just style with CSS. Most graph elements are SVG, 223 | and you already have a good example of a high-contrast styling that I 224 | use. 225 | 226 | Futher SVG is vector graphics. Try stretching up your dashboard, and 227 | you'll find the quality of render isn't affected. 228 | 229 | Applying just common CSS rules should give you everything that you need. 230 | 231 | ## Colors 232 | A good thing to think about is colors in your graph. In a time series, 233 | you'd want each graph to appear distinct from the other, but still keep 234 | a general notion of style (relate to the previous one). 235 | To do that, I've generated colors based on HSL, taking the next color on 236 | the wheel serially, and keeping a good distance for a good contrast. 237 | For more detail, see `/tools` 238 | 239 | 240 | # Roadmap 241 | 242 | These significant features will happen in the following weeks: 243 | 244 | * Visual hints. Lower/upper threshold options for TimeSeries. Once a 245 | value passes above/below these, the Graph will give a visual cue 246 | (flashing, heartbeat) 247 | * RSS widget. Include a stream of events using an RSS feed; provide 248 | regex rules which cause RSS entries to be included, or be classified 249 | as various levels of alerts. The goal is to be able to incorporate 250 | source control history (GitHub events), and alert feeds from other systems. 251 | 252 | 253 | 254 | 255 | 256 | # Thanks! 257 | I'd like to thank (chronological order): 258 | 259 | * Mike Bostock - for D3 itself, its awesome!. I found myself experimenting hours upon hours with it, 260 | but not caring about the time flying by at all. 261 | * Tomer Doron (tomerd) - for the awesome D3 gauge gadget example which I've 262 | customized and included here. 263 | * Chris Mytton (hecticjeff) - contributions 264 | * Michael Garski (mgarski) - contributions 265 | * dcartoon - JSONP cross domain support 266 | * Sean Kilgore (logikal) - contributions 267 | * arctanb - contributions 268 | * Dennis van der Vliet (dennisvdvliet) - bar graphs and other 269 | contributions 270 | * cognusion - contributions 271 | * David Fisher (tibbon) - README fixes 272 | * Jean-Louis Giordano (Jell) - contributions 273 | * Michael Lavrisha (vrish88)- "current" gauge type 274 | * EButlerIV - contributions 275 | * David CHAU (davidchau) - contributions 276 | * Phil Cohen (phlipper) - contributions 277 | 278 | # Contributing 279 | 280 | Fork, implement, add tests, pull request, get my everlasting thanks and a respectable place here :). 281 | 282 | 283 | # Copyright 284 | 285 | Copyright (c) 2012 [Dotan Nahum](http://gplus.to/dotan) [@jondot](http://twitter.com/jondot). See MIT-LICENSE for further details. 286 | -------------------------------------------------------------------------------- /app/css/bootstrap-responsive.min.css: -------------------------------------------------------------------------------- 1 | 2 | .hidden{display:none;visibility:hidden;} 3 | @media (max-width:480px){.nav-collapse{-webkit-transform:translate3d(0, 0, 0);} .page-header h1 small{display:block;line-height:18px;} input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;height:28px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box;} .input-prepend input[class*="span"],.input-append input[class*="span"]{width:auto;} input[type="checkbox"],input[type="radio"]{border:1px solid #ccc;} .form-horizontal .control-group>label{float:none;width:auto;padding-top:0;text-align:left;} .form-horizontal .controls{margin-left:0;} .form-horizontal .control-list{padding-top:0;} .form-horizontal .form-actions{padding-left:10px;padding-right:10px;} .modal{position:absolute;top:10px;left:10px;right:10px;width:auto;margin:0;}.modal.fade.in{top:auto;} .modal-header .close{padding:10px;margin:-10px;} .carousel-caption{position:static;}}@media (max-width:768px){.container{width:auto;padding:0 20px;} .row-fluid{width:100%;} .row{margin-left:0;} .row>[class*="span"],.row-fluid>[class*="span"]{float:none;display:block;width:auto;margin:0;}}@media (min-width:768px) and (max-width:980px){.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";} .row:after{clear:both;} [class*="span"]{float:left;margin-left:20px;} .span1{width:42px;} .span2{width:104px;} .span3{width:166px;} .span4{width:228px;} .span5{width:290px;} .span6{width:352px;} .span7{width:414px;} .span8{width:476px;} .span9{width:538px;} .span10{width:600px;} .span11{width:662px;} .span12,.container{width:724px;} .offset1{margin-left:82px;} .offset2{margin-left:144px;} .offset3{margin-left:206px;} .offset4{margin-left:268px;} .offset5{margin-left:330px;} .offset6{margin-left:392px;} .offset7{margin-left:454px;} .offset8{margin-left:516px;} .offset9{margin-left:578px;} .offset10{margin-left:640px;} .offset11{margin-left:702px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";} .row-fluid:after{clear:both;} .row-fluid>[class*="span"]{float:left;margin-left:2.762430939%;} .row-fluid>[class*="span"]:first-child{margin-left:0;} .row-fluid .span1{width:5.801104972%;} .row-fluid .span2{width:14.364640883%;} .row-fluid .span3{width:22.928176794%;} .row-fluid .span4{width:31.491712705%;} .row-fluid .span5{width:40.055248616%;} .row-fluid .span6{width:48.618784527%;} .row-fluid .span7{width:57.182320438000005%;} .row-fluid .span8{width:65.74585634900001%;} .row-fluid .span9{width:74.30939226%;} .row-fluid .span10{width:82.87292817100001%;} .row-fluid .span11{width:91.436464082%;} .row-fluid .span12{width:99.999999993%;} input.span1,textarea.span1,.uneditable-input.span1{width:32px;} input.span2,textarea.span2,.uneditable-input.span2{width:94px;} input.span3,textarea.span3,.uneditable-input.span3{width:156px;} input.span4,textarea.span4,.uneditable-input.span4{width:218px;} input.span5,textarea.span5,.uneditable-input.span5{width:280px;} input.span6,textarea.span6,.uneditable-input.span6{width:342px;} input.span7,textarea.span7,.uneditable-input.span7{width:404px;} input.span8,textarea.span8,.uneditable-input.span8{width:466px;} input.span9,textarea.span9,.uneditable-input.span9{width:528px;} input.span10,textarea.span10,.uneditable-input.span10{width:590px;} input.span11,textarea.span11,.uneditable-input.span11{width:652px;} input.span12,textarea.span12,.uneditable-input.span12{width:714px;}}@media (max-width:980px){body{padding-top:0;} .navbar-fixed-top{position:static;margin-bottom:18px;} .navbar-fixed-top .navbar-inner{padding:5px;} .navbar .container{width:auto;padding:0;} .navbar .brand{padding-left:10px;padding-right:10px;margin:0 0 0 -5px;} .navbar .nav-collapse{clear:left;} .navbar .nav{float:none;margin:0 0 9px;} .navbar .nav>li{float:none;} .navbar .nav>li>a{margin-bottom:2px;} .navbar .nav>.divider-vertical{display:none;} .navbar .nav>li>a,.navbar .dropdown-menu a{padding:6px 15px;font-weight:bold;color:#999999;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} .navbar .dropdown-menu li+li a{margin-bottom:2px;} .navbar .nav>li>a:hover,.navbar .dropdown-menu a:hover{background-color:#222222;} .navbar .dropdown-menu{position:static;top:auto;left:auto;float:none;display:block;max-width:none;margin:0 15px;padding:0;background-color:transparent;border:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} .navbar .dropdown-menu:before,.navbar .dropdown-menu:after{display:none;} .navbar .dropdown-menu .divider{display:none;} .navbar-form,.navbar-search{float:none;padding:9px 15px;margin:9px 0;border-top:1px solid #222222;border-bottom:1px solid #222222;-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1),0 1px 0 rgba(255, 255, 255, 0.1);-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1),0 1px 0 rgba(255, 255, 255, 0.1);box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1),0 1px 0 rgba(255, 255, 255, 0.1);} .navbar .nav.pull-right{float:none;margin-left:0;} .navbar-static .navbar-inner{padding-left:10px;padding-right:10px;} .btn-navbar{display:block;} .nav-collapse{overflow:hidden;height:0;}}@media (min-width:980px){.nav-collapse.collapse{height:auto !important;}}@media (min-width:1200px){.row{margin-left:-30px;*zoom:1;}.row:before,.row:after{display:table;content:"";} .row:after{clear:both;} [class*="span"]{float:left;margin-left:30px;} .span1{width:70px;} .span2{width:170px;} .span3{width:270px;} .span4{width:370px;} .span5{width:470px;} .span6{width:570px;} .span7{width:670px;} .span8{width:770px;} .span9{width:870px;} .span10{width:970px;} .span11{width:1070px;} .span12,.container{width:1170px;} .offset1{margin-left:130px;} .offset2{margin-left:230px;} .offset3{margin-left:330px;} .offset4{margin-left:430px;} .offset5{margin-left:530px;} .offset6{margin-left:630px;} .offset7{margin-left:730px;} .offset8{margin-left:830px;} .offset9{margin-left:930px;} .offset10{margin-left:1030px;} .offset11{margin-left:1130px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";} .row-fluid:after{clear:both;} .row-fluid>[class*="span"]{float:left;margin-left:2.564102564%;} .row-fluid>[class*="span"]:first-child{margin-left:0;} .row-fluid .span1{width:5.982905983%;} .row-fluid .span2{width:14.529914530000001%;} .row-fluid .span3{width:23.076923077%;} .row-fluid .span4{width:31.623931624%;} .row-fluid .span5{width:40.170940171000005%;} .row-fluid .span6{width:48.717948718%;} .row-fluid .span7{width:57.264957265%;} .row-fluid .span8{width:65.81196581200001%;} .row-fluid .span9{width:74.358974359%;} .row-fluid .span10{width:82.905982906%;} .row-fluid .span11{width:91.45299145300001%;} .row-fluid .span12{width:100%;} input.span1,textarea.span1,.uneditable-input.span1{width:60px;} input.span2,textarea.span2,.uneditable-input.span2{width:160px;} input.span3,textarea.span3,.uneditable-input.span3{width:260px;} input.span4,textarea.span4,.uneditable-input.span4{width:360px;} input.span5,textarea.span5,.uneditable-input.span5{width:460px;} input.span6,textarea.span6,.uneditable-input.span6{width:560px;} input.span7,textarea.span7,.uneditable-input.span7{width:660px;} input.span8,textarea.span8,.uneditable-input.span8{width:760px;} input.span9,textarea.span9,.uneditable-input.span9{width:860px;} input.span10,textarea.span10,.uneditable-input.span10{width:960px;} input.span11,textarea.span11,.uneditable-input.span11{width:1060px;} input.span12,textarea.span12,.uneditable-input.span12{width:1160px;} .thumbnails{margin-left:-30px;} .thumbnails>li{margin-left:30px;}} 4 | -------------------------------------------------------------------------------- /app/css/dashboard.scss: -------------------------------------------------------------------------------- 1 | #dashboard{ 2 | padding-top:6em; 3 | } 4 | 5 | -------------------------------------------------------------------------------- /app/css/high-contrast.scss: -------------------------------------------------------------------------------- 1 | 2 | 3 | /* 4 | * Generated high contrast colors. See tools/gencolors.rb 5 | */ 6 | 7 | .h-col-1{ stroke: hsl(0, 100%, 50%); fill: hsl(0, 100%, 50%);} 8 | .h-col-2{ stroke: hsl(36, 100%, 50%); fill: hsl(36, 100%, 50%);} 9 | .h-col-3{ stroke: hsl(72, 100%, 50%); fill: hsl(72, 100%, 50%);} 10 | .h-col-4{ stroke: hsl(108, 100%, 50%); fill: hsl(108, 100%, 50%);} 11 | .h-col-5{ stroke: hsl(144, 100%, 50%); fill: hsl(144, 100%, 50%);} 12 | .h-col-6{ stroke: hsl(180, 100%, 50%); fill: hsl(180, 100%, 50%);} 13 | .h-col-7{ stroke: hsl(216, 100%, 50%); fill: hsl(216, 100%, 50%);} 14 | .h-col-8{ stroke: hsl(252, 100%, 50%); fill: hsl(252, 100%, 50%);} 15 | .h-col-9{ stroke: hsl(288, 100%, 50%); fill: hsl(288, 100%, 50%);} 16 | .h-col-10{ stroke: hsl(324, 100%, 50%); fill: hsl(324, 100%, 50%);} 17 | 18 | 19 | 20 | 21 | 22 | 23 | body { 24 | background:url(/images/dark_stripes.png); 25 | color:#fff; 26 | stroke:#fff; 27 | } 28 | a{ 29 | color:#F90; 30 | &:hover{ 31 | color:#fc0; 32 | text-decoration: none; 33 | } 34 | } 35 | svg.tsview{ 36 | background: #111; 37 | box-shadow: 0px 1px 4px 0px #000; 38 | margin:1em; 39 | border-radius: 4px; 40 | } 41 | line.tick { 42 | shape-rendering: crispEdges; 43 | } 44 | 45 | 46 | .area{ 47 | fill-opacity:0.2; 48 | } 49 | .line { 50 | fill: none; 51 | stroke-width: 1px; 52 | } 53 | 54 | .line-highlight { 55 | stroke-width: 5px; 56 | } 57 | 58 | .area-highlight { 59 | } 60 | 61 | .axis { 62 | shape-rendering: crispEdges; 63 | } 64 | 65 | .x.axis{ 66 | line{ 67 | stroke-opacity:0.3; 68 | } 69 | path{ 70 | display: none; 71 | } 72 | .minor{ 73 | stroke-opacity: .5; 74 | } 75 | } 76 | 77 | .y.axis line, .y.axis path { 78 | fill: none; 79 | stroke-opacity: 0.3; 80 | } 81 | 82 | path.line-warn { 83 | stroke: yellow; 84 | fill: yellow; 85 | stroke-width: 2px; 86 | } 87 | path.line-error { 88 | stroke: red; 89 | fill: red; 90 | stroke-width: 2px; 91 | } 92 | 93 | .min-tag{ 94 | fill:red; 95 | margin: 0 1em; 96 | } 97 | 98 | .max-tag{ 99 | fill:green; 100 | margin: 0 1em; 101 | } 102 | 103 | .ts-color{ 104 | stroke:none; 105 | } 106 | 107 | text, tspan{ 108 | stroke:none; 109 | fill:#fff; 110 | } 111 | 112 | 113 | /* 114 | * Gauge Label 115 | */ 116 | .glview{ 117 | text-align: center; 118 | 119 | .metric .value{ 120 | font-size:6em; 121 | } 122 | 123 | .label{ 124 | background:none; 125 | } 126 | } 127 | 128 | 129 | 130 | /* 131 | * Gauge Gadget 132 | */ 133 | .ggview{ 134 | text-align:center; 135 | 136 | .gauge{ 137 | circle{ 138 | &.outer{ 139 | fill: #101010; 140 | stroke: #000; 141 | stroke-width: 0.5px; 142 | } 143 | 144 | &.inner{ 145 | fill: #050505; 146 | stroke: #000; 147 | stroke-width: 2px; 148 | } 149 | 150 | &.pointer-circle{ 151 | fill:#dd0000; 152 | stroke:#000; 153 | opacity:1; 154 | } 155 | } 156 | 157 | line{ 158 | &.small-tick{ 159 | stroke: red; 160 | stroke-opacity:0.3; 161 | stroke-width: 1px; 162 | } 163 | 164 | &.big-tick{ 165 | stroke: red; 166 | stroke-opacity: 0.8; 167 | stroke-width: 2px; 168 | } 169 | } 170 | 171 | 172 | text{ 173 | &.label{ 174 | fill: red; 175 | stroke-width: 0px; 176 | fill-opacity:0.4; 177 | } 178 | 179 | &.limit{ 180 | fill: red; 181 | stroke-width: 0px; 182 | fill-opacity: 0.3; 183 | } 184 | 185 | &.value{ 186 | fill:red; 187 | stroke:red; 188 | stroke-width:1px; 189 | } 190 | } 191 | 192 | path{ 193 | &.pointer{ 194 | fill:red; 195 | stroke:#c63310; 196 | fill-opacity: 0.5; 197 | } 198 | 199 | &.band{ 200 | stroke:none; 201 | fill-opacity:0.9; 202 | } 203 | } 204 | } 205 | } 206 | 207 | -------------------------------------------------------------------------------- /app/css/index.css: -------------------------------------------------------------------------------- 1 | /* 2 | *= require 'css/bootstrap.min.css' 3 | *= require 'css/bootstrap-responsive.min.css' 4 | *= require 'css/high-contrast' 5 | *= require 'css/dashboard' 6 | */ 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/js/d3.gauge.js: -------------------------------------------------------------------------------- 1 | // 2 | // this example is based on Tomer Doron's Google Gauge, 3 | // https://github.com/tomerd 4 | // 5 | 6 | function Gauge(placeholderName, configuration) 7 | { 8 | this.placeholderName = placeholderName; 9 | 10 | var self = this; // some internal d3 functions do not "like" the "this" keyword, hence setting a local variable 11 | 12 | this.configure = function(configuration) 13 | { 14 | this.config = configuration; 15 | 16 | this.config.size = this.config.size * 0.9; 17 | 18 | this.config.raduis = this.config.size * 0.97 / 2; 19 | this.config.cx = this.config.size / 2; 20 | this.config.cy = this.config.size / 2; 21 | 22 | this.config.min = configuration.min || 0; 23 | this.config.max = configuration.max || 100; 24 | this.config.range = this.config.max - this.config.min; 25 | 26 | this.config.majorTicks = configuration.majorTicks || 5; 27 | this.config.minorTicks = configuration.minorTicks || 2; 28 | 29 | this.config.greenColor = configuration.greenColor || "#109618"; 30 | this.config.yellowColor = configuration.yellowColor || "#FF9900"; 31 | this.config.redColor = configuration.redColor || "#DC3912"; 32 | } 33 | 34 | this.render = function() 35 | { 36 | this.body = d3.select("#" + this.placeholderName) 37 | .append("svg:svg") 38 | .attr("class", "gauge") 39 | .attr("width", this.config.size) 40 | .attr("height", this.config.size); 41 | 42 | this.body.append("svg:circle") 43 | .attr("class","outer") 44 | .attr("cx", this.config.cx) 45 | .attr("cy", this.config.cy) 46 | .attr("r", this.config.raduis); 47 | 48 | this.body.append("svg:circle") 49 | .attr("class","inner") 50 | .attr("cx", this.config.cx) 51 | .attr("cy", this.config.cy) 52 | .attr("r", 0.9 * this.config.raduis); 53 | 54 | for (var index in this.config.greenZones) 55 | { 56 | this.drawBand(this.config.greenZones[index].from, this.config.greenZones[index].to, self.config.greenColor); 57 | } 58 | 59 | for (var index in this.config.yellowZones) 60 | { 61 | this.drawBand(this.config.yellowZones[index].from, this.config.yellowZones[index].to, self.config.yellowColor); 62 | } 63 | 64 | for (var index in this.config.redZones) 65 | { 66 | this.drawBand(this.config.redZones[index].from, this.config.redZones[index].to, self.config.redColor); 67 | } 68 | 69 | if (undefined != this.config.label) 70 | { 71 | var fontSize = Math.round(this.config.size / 9); 72 | this.body.append("svg:text") 73 | .attr("class", "label") 74 | .attr("x", this.config.cx) 75 | .attr("y", this.config.cy / 2 + fontSize / 2) 76 | .attr("dy", fontSize / 2) 77 | .attr("text-anchor", "middle") 78 | .text(this.config.label) 79 | .style("font-size", fontSize + "px"); 80 | } 81 | 82 | var fontSize = Math.round(this.config.size / 16); 83 | var majorDelta = this.config.range / (this.config.majorTicks - 1); 84 | for (var major = this.config.min; major <= this.config.max; major += majorDelta) 85 | { 86 | var minorDelta = majorDelta / this.config.minorTicks; 87 | for (var minor = major + minorDelta; minor < Math.min(major + majorDelta, this.config.max); minor += minorDelta) 88 | { 89 | var point1 = this.valueToPoint(minor, 0.75); 90 | var point2 = this.valueToPoint(minor, 0.85); 91 | 92 | this.body.append("svg:line") 93 | .attr("class","small-tick") 94 | .attr("x1", point1.x) 95 | .attr("y1", point1.y) 96 | .attr("x2", point2.x) 97 | .attr("y2", point2.y); 98 | } 99 | 100 | var point1 = this.valueToPoint(major, 0.7); 101 | var point2 = this.valueToPoint(major, 0.85); 102 | 103 | this.body.append("svg:line") 104 | .attr("class","big-tick") 105 | .attr("x1", point1.x) 106 | .attr("y1", point1.y) 107 | .attr("x2", point2.x) 108 | .attr("y2", point2.y); 109 | 110 | if (major == this.config.min || major == this.config.max) 111 | { 112 | var point = this.valueToPoint(major, 0.63); 113 | 114 | this.body.append("svg:text") 115 | .attr("class", "limit") 116 | .attr("x", point.x) 117 | .attr("y", point.y) 118 | .attr("dy", fontSize / 3) 119 | .attr("text-anchor", major == this.config.min ? "start" : "end") 120 | .text(major) 121 | .style("font-size", fontSize + "px"); 122 | 123 | } 124 | } 125 | 126 | var pointerContainer = this.body.append("svg:g").attr("class", "pointerContainer"); 127 | this.drawPointer(0); 128 | pointerContainer.append("svg:circle") 129 | .attr("class", "pointer-circle") 130 | .attr("cx", this.config.cx) 131 | .attr("cy", this.config.cy) 132 | .attr("r", 0.12 * this.config.raduis); 133 | } 134 | 135 | this.redraw = function(value, value_format) 136 | { 137 | this.drawPointer(value, value_format); 138 | } 139 | 140 | this.drawBand = function(start, end, color) 141 | { 142 | if (0 >= end - start) return; 143 | 144 | this.body.append("svg:path") 145 | .style("fill", color) 146 | .attr("class", "band") 147 | .attr("d", d3.svg.arc() 148 | .startAngle(this.valueToRadians(start)) 149 | .endAngle(this.valueToRadians(end)) 150 | .innerRadius(0.80 * this.config.raduis) 151 | .outerRadius(0.85 * this.config.raduis)) 152 | .attr("transform", function() { return "translate(" + self.config.cx + ", " + self.config.cy + ") rotate(270)" }); 153 | } 154 | 155 | this.drawPointer = function(value, value_format) 156 | { 157 | var delta = this.config.range / 13; 158 | 159 | var head = this.valueToPoint(value, 0.85); 160 | var head1 = this.valueToPoint(value - delta, 0.12); 161 | var head2 = this.valueToPoint(value + delta, 0.12); 162 | 163 | var tailValue = value - (this.config.range * (1/(270/360)) / 2); 164 | var tail = this.valueToPoint(tailValue, 0.28); 165 | var tail1 = this.valueToPoint(tailValue - delta, 0.12); 166 | var tail2 = this.valueToPoint(tailValue + delta, 0.12); 167 | 168 | var data = [head, head1, tail2, tail, tail1, head2, head]; 169 | 170 | var line = d3.svg.line() 171 | .x(function(d) { return d.x }) 172 | .y(function(d) { return d.y }) 173 | .interpolate("basis"); 174 | 175 | var pointerContainer = this.body.select(".pointerContainer"); 176 | 177 | var pointer = pointerContainer.selectAll("path").data([data]) 178 | 179 | pointer.enter() 180 | .append("svg:path") 181 | .attr("class", "pointer") 182 | .attr("d", line); 183 | 184 | pointer.transition() 185 | .attr("d", line) 186 | //.ease("linear") 187 | //.duration(5000); 188 | 189 | var fontSize = Math.round(this.config.size / 10); 190 | pointerContainer.selectAll("text") 191 | .data([value]) 192 | .text(d3.format(value_format)(value)) 193 | .enter() 194 | .append("svg:text") 195 | .attr("class", "value") 196 | .attr("x", this.config.cx) 197 | .attr("y", this.config.size - this.config.cy / 4 - fontSize) 198 | .attr("dy", fontSize / 2) 199 | .attr("text-anchor", "middle") 200 | .text(d3.format(value_format)(value)) 201 | .style("font-size", fontSize + "px"); 202 | } 203 | 204 | this.valueToDegrees = function(value) 205 | { 206 | return value / this.config.range * 270 - 45; 207 | } 208 | 209 | this.valueToRadians = function(value) 210 | { 211 | return this.valueToDegrees(value) * Math.PI / 180; 212 | } 213 | 214 | this.valueToPoint = function(value, factor) 215 | { 216 | var point = 217 | { 218 | x: this.config.cx - this.config.raduis * factor * Math.cos(this.valueToRadians(value)), 219 | y: this.config.cy - this.config.raduis * factor * Math.sin(this.valueToRadians(value)) 220 | } 221 | 222 | return point; 223 | } 224 | 225 | // initialization 226 | this.configure(configuration); 227 | } 228 | -------------------------------------------------------------------------------- /app/js/graphene.coffee: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Graphene 4 | constructor:-> 5 | @models = {} 6 | 7 | demo:-> 8 | @is_demo = true 9 | 10 | build: (json)=> 11 | _.each _.keys(json), (k)=> 12 | console.log "building [#{k}]" 13 | if @is_demo 14 | klass = Graphene.DemoTimeSeries 15 | else 16 | klass = Graphene.TimeSeries 17 | 18 | model_opts = {source: json[k].source} 19 | delete json[k].source 20 | if json[k].refresh_interval 21 | model_opts.refresh_interval = json[k].refresh_interval 22 | delete json[k].refresh_interval 23 | ts = new klass(model_opts) 24 | @models[k] = ts 25 | 26 | _.each json[k], (opts, view)=> 27 | klass = eval("Graphene.#{view}View") 28 | console.log _.extend({ model: ts, ymin:@getUrlParam(model_opts.source, "yMin"), ymax:@getUrlParam(model_opts.source, "yMax") }, opts) 29 | new klass(_.extend({ model: ts, ymin:@getUrlParam(model_opts.source, "yMin"), ymax:@getUrlParam(model_opts.source, "yMax") }, opts)) 30 | ts.start() 31 | 32 | discover: (url, dash, parent_specifier, cb)-> 33 | $.getJSON "#{url}/dashboard/load/#{dash}", (data)-> 34 | i = 0 35 | desc = {} 36 | _.each data['state']['graphs'], (graph)-> 37 | path = graph[2] 38 | conf = graph[1] 39 | title = if conf.title then conf.title else "n/a" 40 | desc["Graph #{i}"] = 41 | source: "#{url}#{path}&format=json" 42 | TimeSeries: 43 | title: title 44 | ymin: conf.yMin 45 | parent: parent_specifier(i, url) 46 | i++ 47 | cb(desc) 48 | 49 | getUrlParam: (url, variable)-> 50 | value = '' 51 | query = url.split('?')[1] 52 | return value unless query 53 | 54 | vars = query.split('&') 55 | return value unless vars && vars.length > 0 56 | 57 | _.each vars, (v)-> 58 | pair = v.split('=') 59 | if decodeURIComponent(pair[0]) == variable 60 | value = decodeURIComponent(pair[1]) 61 | value 62 | 63 | 64 | @Graphene = Graphene 65 | 66 | 67 | 68 | 69 | class Graphene.GraphiteModel extends Backbone.Model 70 | defaults: 71 | source:'' 72 | data: null 73 | ymin: 0 74 | ymax: 0 75 | refresh_interval: 10000 76 | 77 | debug:()-> 78 | console.log("#{@get('refresh_interval')}") 79 | 80 | start: ()=> 81 | @refresh() 82 | console.log("Starting to poll at #{@get('refresh_interval')}") 83 | @t_index = setInterval(@refresh, @get('refresh_interval')) 84 | 85 | stop: ()=> 86 | clearInterval(@t_index) 87 | 88 | refresh: ()=> 89 | url = @get('source') 90 | #jQuery expects to see 'jsonp=?' in the url in order to perform JSONP-style requests 91 | if -1 == url.indexOf('&jsonp=?') 92 | url = url + '&jsonp=?' 93 | 94 | options = 95 | url: url 96 | dataType: 'json' 97 | jsonp: 'jsonp' 98 | success: (js) => 99 | console.log("got data.") 100 | @process_data(js) 101 | $.ajax options 102 | 103 | process_data: ()=> 104 | return null 105 | 106 | 107 | 108 | 109 | 110 | class Graphene.DemoTimeSeries extends Backbone.Model 111 | defaults: 112 | range: [0, 1000] 113 | num_points: 100 114 | num_new_points: 1 115 | num_series: 2 116 | refresh_interval: 3000 117 | 118 | debug:()-> 119 | console.log("#{@get('refresh_interval')}") 120 | 121 | start: ()=> 122 | console.log("Starting to poll at #{@get('refresh_interval')}") 123 | @data = [] 124 | _.each _.range(@get 'num_series'), (i)=> 125 | @data.push({ 126 | label: "Series #{i}", 127 | ymin: 0, 128 | ymax: 0, 129 | points: [] 130 | }) 131 | @point_interval = @get('refresh_interval') / @get('num_new_points') 132 | 133 | _.each @data, (d)=> 134 | @add_points(new Date(), @get('range'), @get('num_points'), @point_interval, d) 135 | @set(data:@data) 136 | 137 | @t_index = setInterval(@refresh, @get('refresh_interval')) 138 | 139 | stop: ()=> 140 | clearInterval(@t_index) 141 | 142 | refresh: ()=> 143 | # clone data - tricks d3/backbone refs 144 | @data = _.map @data, (d)-> 145 | d = _.clone(d) 146 | d.points = _.map(d.points, (p)-> [p[0], p[1]]) 147 | d 148 | 149 | last = @data[0].points.pop() 150 | @data[0].points.push last 151 | start_date = last[1] 152 | 153 | num_new_points = @get 'num_new_points' 154 | _.each @data, (d)=> 155 | @add_points(start_date, @get('range'), num_new_points, @point_interval, d) 156 | @set(data: @data) 157 | 158 | 159 | add_points: (start_date, range, num_new_points, point_interval, d)=> 160 | _.each _.range(num_new_points), (i)=> 161 | # lay out i points in time. base time x i*interval 162 | new_point = [ 163 | range[0] + Math.random()*(range[1]-range[0]), 164 | new Date(start_date.getTime() + (i+1)*point_interval) 165 | ] 166 | d.points.push(new_point) 167 | d.points.shift() if d.points.length > @get('num_points') 168 | d.ymin = d3.min(d.points, (d) -> d[0]) 169 | d.ymax = d3.max(d.points, (d) -> d[0]) 170 | 171 | 172 | 173 | 174 | class Graphene.BarChart extends Graphene.GraphiteModel 175 | process_data: (js)=> 176 | console.log 'process data barchart' 177 | data = _.map js, (dp)-> 178 | min = d3.min(dp.datapoints, (d) -> d[0]) 179 | return null unless min != undefined 180 | max = d3.max(dp.datapoints, (d) -> d[0]) 181 | return null unless max != undefined 182 | 183 | _.each dp.datapoints, (d) -> d[1] = new Date(d[1]*1000) 184 | return { 185 | points: _.reject(dp.datapoints, (d)-> d[0] == null), 186 | ymin: min, 187 | ymax: max, 188 | label: dp.target 189 | } 190 | data = _.reject data, (d)-> d == null 191 | @set(data:data) 192 | 193 | class Graphene.TimeSeries extends Graphene.GraphiteModel 194 | process_data: (js)=> 195 | data = _.map js, (dp)-> 196 | min = d3.min(dp.datapoints, (d) -> d[0]) 197 | return null unless min != undefined 198 | max = d3.max(dp.datapoints, (d) -> d[0]) 199 | return null unless max != undefined 200 | last = _.last(dp.datapoints)[0] ? 0 201 | return null unless last != undefined 202 | _.each dp.datapoints, (d) -> d[1] = new Date(d[1]*1000) 203 | return { 204 | points: _.reject(dp.datapoints, (d)-> d[0] == null), 205 | ymin: min, 206 | ymax: max, 207 | last: last, 208 | label: dp.target 209 | } 210 | data = _.reject data, (d)-> d == null 211 | @set(data:data) 212 | 213 | 214 | 215 | 216 | 217 | 218 | class Graphene.GaugeGadgetView extends Backbone.View 219 | className: 'gauge-gadget-view' 220 | tagName: 'div' 221 | initialize: ()-> 222 | @title = @options.title 223 | @type = @options.type 224 | 225 | @parent = @options.parent || '#parent' 226 | @value_format = @options.value_format || ".3s" 227 | @null_value = 0 228 | 229 | @from = @options.from || 0 230 | @to = @options.to || 100 231 | 232 | @observer = @options.observer 233 | 234 | @vis = d3.select(@parent).append("div") 235 | .attr("class", "ggview") 236 | .attr("id", @title+"GaugeContainer") 237 | 238 | config = 239 | size: @options.size || 120 240 | label: @title 241 | minorTicks: 5 242 | min: @from 243 | max: @to 244 | 245 | 246 | config.redZones = [] 247 | config.redZones.push({ from: @options.red_from || 0.9*@to, to: @options.red_to || @to }) 248 | 249 | config.yellowZones = [] 250 | config.yellowZones.push({ from: @options.yellow_from || 0.75*@to, to: @options.yellow_to || 0.9*@to }) 251 | 252 | @gauge = new Gauge("#{@title}GaugeContainer", config) 253 | @gauge.render() 254 | 255 | @model.bind('change', @render) 256 | console.log("GG view ") 257 | 258 | 259 | by_type:(d)=> 260 | switch @type 261 | when "min" then d.ymin 262 | when "max" then d.ymax 263 | when "current" then d.last 264 | else d.points[0][0] 265 | 266 | render: ()=> 267 | console.log("rendering.") 268 | data = @model.get('data') 269 | datum = if data && data.length > 0 then data[0] else { ymax: @null_value, ymin: @null_value, points: [[@null_value, 0]] } 270 | 271 | @observer(@by_type(datum)) if @observer 272 | 273 | @gauge.redraw(@by_type(datum), @value_format) 274 | 275 | 276 | 277 | 278 | 279 | 280 | class Graphene.GaugeLabelView extends Backbone.View 281 | className: 'gauge-label-view' 282 | tagName: 'div' 283 | initialize: ()-> 284 | @unit = @options.unit 285 | @title = @options.title 286 | @type = @options.type 287 | @parent = @options.parent || '#parent' 288 | @value_format = @options.value_format || ".3s" 289 | @value_format = d3.format(@value_format) 290 | @null_value = 0 291 | @observer = @options.observer 292 | 293 | @vis = d3.select(@parent).append("div") 294 | .attr("class", "glview") 295 | if @title 296 | @vis.append("div") 297 | .attr("class", "label") 298 | .text(@title) 299 | 300 | @model.bind('change', @render) 301 | console.log("GL view ") 302 | 303 | 304 | by_type:(d)=> 305 | switch @type 306 | when "min" then d.ymin 307 | when "max" then d.ymax 308 | when "current" then d.last 309 | else d.points[0][0] 310 | 311 | render: ()=> 312 | data = @model.get('data') 313 | console.log data 314 | datum = if data && data.length > 0 then data[0] else { ymax: @null_value, ymin: @null_value, points: [[@null_value, 0]] } 315 | 316 | # let observer know about this 317 | @observer(@by_type(datum)) if @observer 318 | 319 | vis = @vis 320 | metric_items = vis.selectAll('div.metric') 321 | .data([datum], (d)=> @by_type(d)) 322 | 323 | metric_items.exit().remove() 324 | 325 | metric = metric_items.enter() 326 | .insert('div', ":first-child") 327 | .attr('class',"metric#{if @type then ' '+@type else ''}") 328 | 329 | metric.append('span') 330 | .attr('class', 'value') 331 | .text((d)=>@value_format(@by_type(d))) 332 | if @unit 333 | metric.append('span') 334 | .attr('class', 'unit') 335 | .text(@unit) 336 | 337 | 338 | 339 | class Graphene.TimeSeriesView extends Backbone.View 340 | tagName: 'div' 341 | 342 | initialize: ()-> 343 | @name = @options.name || "g-" + parseInt(Math.random() * 1000000) 344 | @line_height = @options.line_height || 16 345 | @x_ticks = @options.x_ticks || 4 346 | @y_ticks = @options.y_ticks || 4 347 | @animate_ms = @options.animate_ms || 500 348 | @label_offset = @options.label_offset || 0 349 | @label_columns = @options.label_columns || 1 350 | @label_href = @options.label_href || (label) -> '#' 351 | @label_formatter = @options.label_formatter || (label) -> label 352 | @num_labels = @options.num_labels || 3 353 | @sort_labels = @options.labels_sort 354 | @display_verticals = @options.display_verticals || false 355 | @width = @options.width || 400 356 | @height = @options.height || 100 357 | @padding = @options.padding || [@line_height*2, 32, @line_height*(3+(@num_labels / @label_columns)), 32] #trbl 358 | @title = @options.title 359 | @firstrun = true 360 | @parent = @options.parent || '#parent' 361 | @null_value = 0 362 | @show_current = @options.show_current || false 363 | @observer = @options.observer 364 | @postrender = @options.post_render || postRenderTimeSeriesView 365 | 366 | @vis = d3.select(@parent).append("svg") 367 | .attr("class", "tsview") 368 | .attr("width", @width + (@padding[1]+@padding[3])) 369 | .attr("height", @height + (@padding[0]+@padding[2])) 370 | .append("g") 371 | .attr("transform", "translate(" + @padding[3] + "," + @padding[0] + ")") 372 | # Is this used in the timeseries? -dvdv 373 | @value_format = @options.value_format || ".3s" 374 | @value_format = d3.format(@value_format) 375 | 376 | @model.bind('change', @render) 377 | console.log("TS view: #{@name} #{@width}x#{@height} padding:#{@padding} animate: #{@animate_ms} labels: #{@num_labels}") 378 | 379 | 380 | render: ()=> 381 | console.log("rendering.") 382 | data = @model.get('data') 383 | 384 | data = if data && data.length > 0 then data else [{ ymax: @null_value, ymin: @null_value, points: [[@null_value, 0],[@null_value, 0]] }] 385 | 386 | # 387 | # find overall min/max of sets 388 | # 389 | dmax = _.max data, (d)-> d.ymax 390 | dmax.ymax_graph = @options.ymax || dmax.ymax 391 | dmin = _.min data, (d)-> d.ymin 392 | dmin.ymin_graph = @options.ymin ? dmin.ymin 393 | 394 | # 395 | # build dynamic x & y metrics. 396 | # 397 | xpoints = _.flatten (d.points.map((p)->p[1]) for d in data) 398 | xmin = _.min xpoints, (x)->x.valueOf() 399 | xmax = _.max xpoints, (x)->x.valueOf() 400 | 401 | x = d3.time.scale().domain([xmin, xmax]).range([0, @width]) 402 | y = d3.scale.linear().domain([dmin.ymin_graph, dmax.ymax_graph]).range([@height, 0]).nice() 403 | 404 | # 405 | # build axis 406 | # 407 | xtick_sz = if @display_verticals then -@height else 0 408 | xAxis = d3.svg.axis().scale(x).ticks(@x_ticks).tickSize(xtick_sz).tickSubdivide(true) 409 | yAxis = d3.svg.axis().scale(y).ticks(@y_ticks).tickSize(-@width).orient("left").tickFormat(d3.format("s")) 410 | 411 | vis = @vis 412 | 413 | # 414 | # build dynamic line & area, note that we're using dynamic x & y. 415 | # 416 | line = d3.svg.line().x((d) -> x(d[1])).y((d) -> y(d[0])) 417 | area = d3.svg.area().x((d) -> x(d[1])).y0(@height - 1).y1((d) -> y(d[0])) 418 | 419 | # 420 | # get first X labels 421 | # 422 | if @sort_labels 423 | order = if(@sort_labels == 'desc') then -1 else 1 424 | data = _.sortBy(data, (d)-> order*d.ymax) 425 | 426 | 427 | # let observer know about this 428 | @observer(data) if @observer 429 | 430 | # 431 | # get raw data points (throw away all of the other blabber 432 | # 433 | points = _.map data, (d)-> d.points 434 | 435 | 436 | if @firstrun 437 | @firstrun = false 438 | 439 | # 440 | # Axis 441 | # 442 | vis.append("svg:g") 443 | .attr("class", "x axis") 444 | .attr("transform", "translate(0," + @height + ")") 445 | .transition() 446 | .duration(@animate_ms) 447 | .call(xAxis) 448 | 449 | vis.append("svg:g").attr("class", "y axis").call(yAxis) 450 | 451 | # 452 | # Line + Area 453 | # 454 | # Note that we can't use idiomatic d3 here - data is one big chunk of data (single property), 455 | # this is a result of us wanting to use a *single* SVG line element to render the data. 456 | # so enter() exit() semantics are invalid. We will append here, and later just replace (update). 457 | # To see an idiomatic d3 handling, take a look at the legend fixture. 458 | # 459 | vis.selectAll("path.line").data(points).enter().append('path').attr("d", line).attr('class', (d,i) -> 'line '+"h-col-#{i+1}") 460 | vis.selectAll("path.area").data(points).enter().append('path').attr("d", area).attr('class', (d,i) -> 'area '+"h-col-#{i+1}") 461 | 462 | if (@options.warn && (dmax.ymax_graph > @options.warn)) 463 | warnData = [[[@options.warn, xmin],[@options.warn, xmax]]] 464 | vis.selectAll("path.line-warn") 465 | .data(warnData) 466 | .enter() 467 | .append('path') 468 | .attr('d', line) 469 | .attr('stroke-dasharray', '10,10') 470 | .attr('class', 'line-warn') 471 | 472 | if (@options.error && (dmax.ymax_graph > @options.error)) 473 | errorData= [[[@options.error, xmin],[@options.error, xmax]]] 474 | vis.selectAll("path.line-error") 475 | .data(errorData) 476 | .enter() 477 | .append('path') 478 | .attr('d', line) 479 | .attr('stroke-dasharray', '10,10') 480 | .attr('class', 'line-error') 481 | 482 | # 483 | # Title + Legend 484 | # 485 | if @title 486 | title = vis.append('svg:text') 487 | .attr('class', 'title') 488 | .attr('transform', "translate(0, -#{@line_height})") 489 | .text(@title) 490 | 491 | @legend = vis.append('svg:g') 492 | .attr('transform', "translate(0, #{@height+@line_height*2})") 493 | .attr('class', 'legend') 494 | 495 | #---------------------------------------------------------------------------------------# 496 | # Update Graph 497 | #---------------------------------------------------------------------------------------# 498 | 499 | 500 | # 501 | # update the legend (dynamic legend ordering responds to min/max) 502 | # 503 | 504 | # first inject datapoints into legend items. 505 | # note the data mapping is by label name (not index) 506 | leg_items = @legend.selectAll('g.l').data(_.first(data, @num_labels), (d)->Math.random()) 507 | 508 | # remove legend item. 509 | leg_items.exit().remove() 510 | 511 | # only per entering item, attach a color box and text. 512 | litem_enters = leg_items.enter() 513 | .append('svg:g') 514 | .attr('transform', (d, i) => "translate(#{(i % @label_columns) * @label_offset}, #{parseInt(i / @label_columns) * @line_height})") 515 | .attr('class', 'l') 516 | litem_enters.append('svg:rect') 517 | .attr('width', 5) 518 | .attr('height', 5) 519 | .attr('class', (d,i) -> 'ts-color '+"h-col-#{i+1}") 520 | 521 | litem_enters_a = litem_enters.append('svg:a') 522 | .attr('xlink:href', (d) => @label_href(d.label)) 523 | .attr('class', 'l') 524 | .attr('id', (d, i) => @name + "-" + i) 525 | 526 | litem_enters_text = litem_enters_a.append('svg:text') 527 | .attr('dx', 10) 528 | .attr('dy', 6) 529 | .attr('class', 'ts-text') 530 | .text((d) => @label_formatter(d.label)) 531 | 532 | litem_enters_text.append('svg:tspan') 533 | .attr('class', 'min-tag') 534 | .attr('dx', 10) 535 | .text((d) => @value_format(d.ymin)+"min") 536 | 537 | litem_enters_text.append('svg:tspan') 538 | .attr('class', 'max-tag') 539 | .attr('dx', 2) 540 | .text((d) => @value_format(d.ymax)+"max") 541 | 542 | if @show_current is true 543 | litem_enters_text.append('svg:tspan') 544 | .attr('class', 'last-tag') 545 | .attr('dx', 2) 546 | .text((d) => @value_format(d.last)+"last") 547 | 548 | # 549 | # update the graph 550 | # 551 | vis.transition().ease("linear").duration(@animate_ms).select(".x.axis").call(xAxis) 552 | vis.select(".y.axis").call(yAxis) 553 | 554 | vis.selectAll("path.area") 555 | .data(points) 556 | .attr("d", area) 557 | .attr("id", (d, i) => "a-" + @name + "-" + i) 558 | .transition() 559 | .ease("linear") 560 | .duration(@animate_ms) 561 | 562 | vis.selectAll("path.line") 563 | .data(points) 564 | .attr("d", line) 565 | .attr("id", (d, i) => "l-" + @name + "-" + i) 566 | .transition() 567 | .ease("linear") 568 | .duration(@animate_ms) 569 | 570 | @postrender(@vis) 571 | 572 | # Barcharts 573 | class Graphene.BarChartView extends Backbone.View 574 | tagName: 'div' 575 | initialize: () -> 576 | @line_height = @options.line_height || 16 577 | @animate_ms = @options.animate_ms || 500 578 | @num_labels = @options.num_labels || 3 579 | @sort_labels = @options.labels_sort || 'desc' 580 | @display_verticals = @options.display_verticals || false 581 | @width = @options.width || 400 582 | @height = @options.height || 100 583 | @padding = @options.padding || [@line_height*2, 32, @line_height*(3+@num_labels), 32] #trbl 584 | @title = @options.title 585 | @label_formatter = @options.label_formatter || (label) -> label 586 | @firstrun = true 587 | @parent = @options.parent || '#parent' 588 | @null_value = 0 589 | @value_format = @options.value_format || ".3s" 590 | @value_format = d3.format(@value_format) 591 | 592 | @vis = d3.select(@parent).append("svg") 593 | .attr("class", "tsview") 594 | .attr("width", @width + (@padding[1]+@padding[3])) 595 | .attr("height", @height + (@padding[0]+@padding[2])) 596 | .append("g") 597 | .attr("transform", "translate(" + @padding[3] + "," + @padding[0] + ")") 598 | @model.bind('change', @render) 599 | render: () => 600 | console.log "rendering bar chart." 601 | 602 | # Getting data 603 | data = @model.get('data') 604 | 605 | dmax = _.max data, (d)-> d.ymax 606 | dmin = _.min data, (d)-> d.ymin 607 | data = _.sortBy(data, (d)-> 1*d.ymax) 608 | points = _.map data, (d)-> d.points 609 | 610 | # Find the minimum and maximum timestamps 611 | timestamps = _.flatten (_.map points, (series)-> (_.map series, (point)-> point[1])) 612 | minTimestamp = _.min timestamps 613 | maxTimestamp = _.max timestamps 614 | 615 | # Find the closest two timestamps (that aren't equal), use that as the difference between timestamps 616 | orderedTimestamps = _.uniq (_.sortBy timestamps, (ts)-> ts), true, (ts)-> ts.getTime() 617 | differences = [] 618 | _.each orderedTimestamps, (ts, index, list)-> 619 | if list[index+1] != undefined 620 | differences.push list[index+1] - ts 621 | timestampDifference = (_.min differences) 622 | 623 | # Create x and y scales 624 | x = d3.time.scale().domain([minTimestamp, maxTimestamp + timestampDifference]).range([0, @width]) 625 | y = d3.scale.linear().domain([dmin.ymin, dmax.ymax]).range([@height, 0]).nice() 626 | 627 | # The total number of groups of columns 628 | columnGroups = (maxTimestamp - minTimestamp) / timestampDifference + 1 629 | # The number of columns per group (the number of targets) 630 | columnsPerGroup = points.length 631 | # The total number of columns 632 | columnsTotal = columnGroups * columnsPerGroup 633 | # The width of each bar 634 | barWidth = _.max [@width / columnsTotal - 2, 0.1] 635 | 636 | # Functions used to draw rectangles 637 | calculateX = (d, outerIndex, innerIndex)-> 638 | x(d[1]) + innerIndex * (barWidth + 2) 639 | calculateY = (d)-> 640 | y(d[0]) 641 | 642 | # Create axes 643 | xtick_sz = if @display_verticals then -@height else 0 644 | xAxis = d3.svg.axis().scale(x).ticks(_.min([4, columnGroups])).tickSize(xtick_sz).tickSubdivide(true) 645 | yAxis = d3.svg.axis().scale(y).ticks(4).tickSize(-@width).orient("left").tickFormat(d3.format("s")) 646 | vis = @vis 647 | 648 | # We need this value because the bars are drawn starting at the top 649 | canvas_height = @height 650 | 651 | if @firstrun 652 | @firstrun = false 653 | 654 | # Draw axes 655 | vis.append("svg:g") 656 | .attr("class", "x axis") 657 | .attr("transform", "translate(0," + @height + ")") 658 | .transition() 659 | .duration(@animate_ms) 660 | .call(xAxis) 661 | vis.append("svg:g").attr("class", "y axis").call(yAxis) 662 | 663 | # Draw title and legend 664 | if @title 665 | title = vis.append('svg:text') 666 | .attr('class', 'title') 667 | .attr('transform', "translate(0, -#{@line_height})") 668 | .text(@title) 669 | 670 | @legend = vis.append('svg:g') 671 | .attr('transform', "translate(0, #{@height+@line_height*2})") 672 | .attr('class', 'legend') 673 | 674 | #---------------------------------------------------------------------------------------# 675 | # Update Graph 676 | #---------------------------------------------------------------------------------------# 677 | 678 | # update the legend (dynamic legend ordering responds to min/max) 679 | # first inject datapoints into legend items. 680 | # note the data mapping is by label name (not index) 681 | leg_items = @legend.selectAll('g.l').data(_.first(data, @num_labels), (d)->Math.random()) 682 | 683 | # remove legend item. 684 | leg_items.exit().remove() 685 | 686 | # only per entering item, attach a color box and text. 687 | litem_enters = leg_items.enter() 688 | .append('svg:g') 689 | .attr('transform', (d, i) => "translate(0, #{i*@line_height})") 690 | .attr('class', 'l') 691 | litem_enters.append('svg:rect') 692 | .attr('width', 5) 693 | .attr('height', 5) 694 | .attr('class', (d,i) -> 'ts-color '+"h-col-#{i+1}") 695 | litem_enters_text = litem_enters.append('svg:text') 696 | .attr('dx', 10) 697 | .attr('dy', 6) 698 | .attr('class', 'ts-text') 699 | .text((d) => @label_formatter(d.label)) 700 | 701 | # Draw minimum and maximum information 702 | litem_enters_text.append('svg:tspan') 703 | .attr('class', 'min-tag') 704 | .attr('dx', 10) 705 | .text((d) => @value_format(d.ymin)+"min") 706 | litem_enters_text.append('svg:tspan') 707 | .attr('class', 'max-tag') 708 | .attr('dx', 2) 709 | .text((d) => @value_format(d.ymax)+"max") 710 | 711 | # Draw new rectangles 712 | _.each points, (series, i)-> 713 | className = "h-col-" + (i+1) 714 | vis.selectAll("rect.area."+className) 715 | .data(series) 716 | .enter() 717 | .append("rect") 718 | .attr("class", className + " area") 719 | .attr("x", (d, j)-> calculateX(d, j, i)) 720 | .attr("y", canvas_height) 721 | .attr("width", barWidth) 722 | 723 | # Update existing rectangles 724 | _.each points, (series, i)-> 725 | className = "h-col-" + (i+1) 726 | vis.selectAll("rect.area."+className) 727 | .data(series) 728 | .transition().ease("linear").duration(@animate_ms) 729 | .attr("x", (d, j)-> calculateX(d, j, i)) 730 | .attr("y", (d, j)-> calculateY(d)) 731 | .attr("width", barWidth) 732 | .attr("height", (d, j) -> canvas_height - calculateY(d)) 733 | .attr("class", className + " area") 734 | 735 | # Update axes 736 | vis.transition().ease("linear").duration(@animate_ms).select(".x.axis").call(xAxis) 737 | vis.select(".y.axis").call(yAxis) 738 | 739 | console.log "done drawing" 740 | -------------------------------------------------------------------------------- /app/js/graphene.events.js: -------------------------------------------------------------------------------- 1 | function toggleHighlight(classVal, toggleVal) { 2 | function replaceAll(find, replace, str) { 3 | return str.replace(new RegExp(find, 'g'), replace); 4 | } 5 | 6 | if (classVal.indexOf(toggleVal) != -1) { 7 | return replaceAll("highlight", "", classVal) 8 | } 9 | else { 10 | return classVal + " " + toggleVal; 11 | } 12 | } 13 | 14 | function postRenderTimeSeriesView(vis) { 15 | var svg = vis; 16 | svg.selectAll('a.l').forEach( function(g) { 17 | g.forEach(function(a){ 18 | var aid = a.getAttribute('id') 19 | a.addEventListener('mouseenter', function() { 20 | svg.selectAll('path#l-' + aid).forEach ( function (g) { 21 | g.forEach(function (path) { 22 | path.setAttribute('class', toggleHighlight(path.getAttribute('class'), "line-highlight")); 23 | }) 24 | }) 25 | svg.selectAll('path#a-' + aid).forEach ( function (g) { 26 | g.forEach(function (path) { 27 | path.setAttribute('class', toggleHighlight(path.getAttribute('class'), "area-highlight")); 28 | }) 29 | }) 30 | }) 31 | a.addEventListener('mouseleave', function() { 32 | svg.selectAll('path#l-' + aid).forEach ( function (g) { 33 | g.forEach(function (path) { 34 | path.setAttribute('class', toggleHighlight(path.getAttribute('class'), "line-highlight")); 35 | }) 36 | }) 37 | svg.selectAll('path#a-' + aid).forEach ( function (g) { 38 | g.forEach(function (path) { 39 | path.setAttribute('class', toggleHighlight(path.getAttribute('class'), "area-highlight")); 40 | }) 41 | }) 42 | }) 43 | }) 44 | }) 45 | } -------------------------------------------------------------------------------- /app/js/index.js: -------------------------------------------------------------------------------- 1 | //= require 'vendor/js/underscore' 2 | //= require 'vendor/js/backbone' 3 | //= require 'vendor/js/d3' 4 | 5 | //= require 'js/d3.gauge' 6 | //= require 'js/graphene.events' 7 | //= require 'js/graphene' 8 | 9 | 10 | -------------------------------------------------------------------------------- /build/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jondot/graphene/04275b84eb8e1c8441daf1e626d61af1022e3368/build/.gitkeep -------------------------------------------------------------------------------- /devstart.sh: -------------------------------------------------------------------------------- 1 | bundle exec guard start & 2 | serve . & 3 | gvim . & 4 | 5 | -------------------------------------------------------------------------------- /example/dashboard-autodiscover.html: -------------------------------------------------------------------------------- 1 | <!DOCTYPE html> 2 | <html> 3 | <head> 4 | <title>Dashboard 5 | 6 | 51 | 52 | 53 | 54 | 55 |
56 | 57 |
58 | 59 | 60 | 61 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /example/dashboard.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dashboard 5 | 6 | 48 | 49 | 50 | 51 | 52 |
53 |
54 |
55 |
56 |
57 | 59 | 60 | 62 | 64 | 65 | 67 | 69 | 70 | 72 | 74 | 75 | 77 | 79 | 80 | 82 | 83 | 84 | 86 | 87 | 88 | 90 | 91 |

92 |

A D3.js, Backbone.js based Graphite Dashboard Toolkit.

94 |

95 | 96 | View on Github   98 | Follow @jondot 100 | 101 |
102 |
103 | 104 |
105 |
106 | 107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 | 116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /example/example-dash.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | var description; 3 | description = { 4 | "Total Notifications": { 5 | source: "http://localhost:4567/", 6 | GaugeLabel: { 7 | parent: "#hero-one", 8 | observer: function(data){ 9 | console.log("Label observing " + data); 10 | }, 11 | title: "Notifications Served", 12 | type: "max" 13 | } 14 | }, 15 | "Poll Time": { 16 | source: "http://localhost:4567/", 17 | GaugeGadget: { 18 | parent: "#hero-one", 19 | title: "P1", 20 | observer: function(data){ 21 | console.log("Gadget observing " +data); 22 | } 23 | } 24 | }, 25 | 26 | 27 | "Total Installs": { 28 | source: "http://localhost:4567/", 29 | GaugeLabel: { 30 | parent: "#hero-three", 31 | title: "Clients Installed" 32 | } 33 | }, 34 | "Clients 1": { 35 | source: "http://localhost:4567/", 36 | GaugeGadget: { 37 | parent: "#hero-three", 38 | title: "Cl1" 39 | } 40 | }, 41 | "New Message": { 42 | source: "http://localhost:4567/", 43 | TimeSeries: { 44 | parent: '#g1-1', 45 | title: 'New Message', 46 | label_offset: 200, 47 | label_columns: 2, 48 | time_span_mins: 12, 49 | observer: function(data){ 50 | console.log("Time series observing ", data); 51 | } 52 | } 53 | }, 54 | "Feed Poll": { 55 | source: "http://localhost:4567/", 56 | TimeSeries: { 57 | title: 'Feed Poll', 58 | y_ticks: 2, 59 | display_verticals: true, 60 | parent: '#g1-2' 61 | } 62 | }, 63 | "Topics": { 64 | source: "http://localhost:4567/", 65 | refresh_interval: 20000, 66 | TimeSeries: { 67 | title: 'Topics', 68 | parent: '#g1-3' 69 | } 70 | }, 71 | "Queue Push": { 72 | source: "http://localhost:4567/", 73 | TimeSeries: { 74 | title: 'Queue Push', 75 | ymax: 1000, 76 | warn: 600, 77 | error: 800, 78 | parent: '#g2-1' 79 | } 80 | }, 81 | "Queue Work": { 82 | source: "http://localhost:4567/", 83 | TimeSeries: { 84 | parent: '#g2-2' 85 | } 86 | }, 87 | "Foo Work": { 88 | source: "http://localhost:4567/", 89 | BarChart: { 90 | parent: '#g2-3' 91 | } 92 | } 93 | }; 94 | 95 | 96 | var g = new Graphene; 97 | g.demo(); 98 | g.build(description); 99 | 100 | 101 | }).call(this); 102 | -------------------------------------------------------------------------------- /images/dark_stripes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jondot/graphene/04275b84eb8e1c8441daf1e626d61af1022e3368/images/dark_stripes.png -------------------------------------------------------------------------------- /images/diagmonds.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jondot/graphene/04275b84eb8e1c8441daf1e626d61af1022e3368/images/diagmonds.png -------------------------------------------------------------------------------- /run_browser.sh: -------------------------------------------------------------------------------- 1 | google-chrome --disable-web-security 2 | -------------------------------------------------------------------------------- /tools/gencolors.rb: -------------------------------------------------------------------------------- 1 | # 2 | # This should generate colors for a CSS dashboard theme. 3 | # 4 | # Some theory: 5 | # 6 | # I use HSL form since it is much, much more convenient, essentially, 7 | # to generate colors around the spectrum (or variants of color families), 8 | # all you have to do (programmatically) is travel on a circle (divided to 360deg). 9 | # Really like slicing a Pizza. 10 | # 11 | # Below I chose to generate 10 colors, which provides enough spacing on slices 12 | # so that colors are highly contrasted yet still share a gradual rainbow theme. 13 | # 14 | # You might want to tweak the ordering to create a more cheerful theme for you own 15 | # dashboard. 16 | # 17 | 18 | NUM_COLORS = 10 19 | 20 | interval = 360/NUM_COLORS 21 | i = 190 22 | j = 1 23 | 24 | # Figure out what a full circle from the start would be 25 | max = i + 360 26 | 27 | # Iterate until we make a full circle 28 | while i < max 29 | 30 | # Since we can get higher than 360, find the right value 31 | color = i % 360 32 | 33 | puts ".h-col-#{j}{ stroke: hsl(#{color}, 100%, 50%); fill: hsl(#{color}, 100%, 50%);}" 34 | j +=1 35 | i += interval 36 | end 37 | 38 | -------------------------------------------------------------------------------- /vendor/js/backbone.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 0.5.3 2 | // (c) 2010 Jeremy Ashkenas, DocumentCloud Inc. 3 | // Backbone may be freely distributed under the MIT license. 4 | // For all details and documentation: 5 | // http://documentcloud.github.com/backbone 6 | 7 | (function(){ 8 | 9 | // Initial Setup 10 | // ------------- 11 | 12 | // Save a reference to the global object. 13 | var root = this; 14 | 15 | // Save the previous value of the `Backbone` variable. 16 | var previousBackbone = root.Backbone; 17 | 18 | // The top-level namespace. All public Backbone classes and modules will 19 | // be attached to this. Exported for both CommonJS and the browser. 20 | var Backbone; 21 | if (typeof exports !== 'undefined') { 22 | Backbone = exports; 23 | } else { 24 | Backbone = root.Backbone = {}; 25 | } 26 | 27 | // Current version of the library. Keep in sync with `package.json`. 28 | Backbone.VERSION = '0.5.3'; 29 | 30 | // Require Underscore, if we're on the server, and it's not already present. 31 | var _ = root._; 32 | if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._; 33 | 34 | // For Backbone's purposes, jQuery or Zepto owns the `$` variable. 35 | var $ = root.jQuery || root.Zepto; 36 | 37 | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable 38 | // to its previous owner. Returns a reference to this Backbone object. 39 | Backbone.noConflict = function() { 40 | root.Backbone = previousBackbone; 41 | return this; 42 | }; 43 | 44 | // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option will 45 | // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a 46 | // `X-Http-Method-Override` header. 47 | Backbone.emulateHTTP = false; 48 | 49 | // Turn on `emulateJSON` to support legacy servers that can't deal with direct 50 | // `application/json` requests ... will encode the body as 51 | // `application/x-www-form-urlencoded` instead and will send the model in a 52 | // form param named `model`. 53 | Backbone.emulateJSON = false; 54 | 55 | // Backbone.Events 56 | // ----------------- 57 | 58 | // A module that can be mixed in to *any object* in order to provide it with 59 | // custom events. You may `bind` or `unbind` a callback function to an event; 60 | // `trigger`-ing an event fires all callbacks in succession. 61 | // 62 | // var object = {}; 63 | // _.extend(object, Backbone.Events); 64 | // object.bind('expand', function(){ alert('expanded'); }); 65 | // object.trigger('expand'); 66 | // 67 | Backbone.Events = { 68 | 69 | // Bind an event, specified by a string name, `ev`, to a `callback` function. 70 | // Passing `"all"` will bind the callback to all events fired. 71 | bind : function(ev, callback, context) { 72 | var calls = this._callbacks || (this._callbacks = {}); 73 | var list = calls[ev] || (calls[ev] = []); 74 | list.push([callback, context]); 75 | return this; 76 | }, 77 | 78 | // Remove one or many callbacks. If `callback` is null, removes all 79 | // callbacks for the event. If `ev` is null, removes all bound callbacks 80 | // for all events. 81 | unbind : function(ev, callback) { 82 | var calls; 83 | if (!ev) { 84 | this._callbacks = {}; 85 | } else if (calls = this._callbacks) { 86 | if (!callback) { 87 | calls[ev] = []; 88 | } else { 89 | var list = calls[ev]; 90 | if (!list) return this; 91 | for (var i = 0, l = list.length; i < l; i++) { 92 | if (list[i] && callback === list[i][0]) { 93 | list[i] = null; 94 | break; 95 | } 96 | } 97 | } 98 | } 99 | return this; 100 | }, 101 | 102 | // Trigger an event, firing all bound callbacks. Callbacks are passed the 103 | // same arguments as `trigger` is, apart from the event name. 104 | // Listening for `"all"` passes the true event name as the first argument. 105 | trigger : function(eventName) { 106 | var list, calls, ev, callback, args; 107 | var both = 2; 108 | if (!(calls = this._callbacks)) return this; 109 | while (both--) { 110 | ev = both ? eventName : 'all'; 111 | if (list = calls[ev]) { 112 | for (var i = 0, l = list.length; i < l; i++) { 113 | if (!(callback = list[i])) { 114 | list.splice(i, 1); i--; l--; 115 | } else { 116 | args = both ? Array.prototype.slice.call(arguments, 1) : arguments; 117 | callback[0].apply(callback[1] || this, args); 118 | } 119 | } 120 | } 121 | } 122 | return this; 123 | } 124 | 125 | }; 126 | 127 | // Backbone.Model 128 | // -------------- 129 | 130 | // Create a new model, with defined attributes. A client id (`cid`) 131 | // is automatically generated and assigned for you. 132 | Backbone.Model = function(attributes, options) { 133 | var defaults; 134 | attributes || (attributes = {}); 135 | if (defaults = this.defaults) { 136 | if (_.isFunction(defaults)) defaults = defaults.call(this); 137 | attributes = _.extend({}, defaults, attributes); 138 | } 139 | this.attributes = {}; 140 | this._escapedAttributes = {}; 141 | this.cid = _.uniqueId('c'); 142 | this.set(attributes, {silent : true}); 143 | this._changed = false; 144 | this._previousAttributes = _.clone(this.attributes); 145 | if (options && options.collection) this.collection = options.collection; 146 | this.initialize(attributes, options); 147 | }; 148 | 149 | // Attach all inheritable methods to the Model prototype. 150 | _.extend(Backbone.Model.prototype, Backbone.Events, { 151 | 152 | // A snapshot of the model's previous attributes, taken immediately 153 | // after the last `"change"` event was fired. 154 | _previousAttributes : null, 155 | 156 | // Has the item been changed since the last `"change"` event? 157 | _changed : false, 158 | 159 | // The default name for the JSON `id` attribute is `"id"`. MongoDB and 160 | // CouchDB users may want to set this to `"_id"`. 161 | idAttribute : 'id', 162 | 163 | // Initialize is an empty function by default. Override it with your own 164 | // initialization logic. 165 | initialize : function(){}, 166 | 167 | // Return a copy of the model's `attributes` object. 168 | toJSON : function() { 169 | return _.clone(this.attributes); 170 | }, 171 | 172 | // Get the value of an attribute. 173 | get : function(attr) { 174 | return this.attributes[attr]; 175 | }, 176 | 177 | // Get the HTML-escaped value of an attribute. 178 | escape : function(attr) { 179 | var html; 180 | if (html = this._escapedAttributes[attr]) return html; 181 | var val = this.attributes[attr]; 182 | return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val); 183 | }, 184 | 185 | // Returns `true` if the attribute contains a value that is not null 186 | // or undefined. 187 | has : function(attr) { 188 | return this.attributes[attr] != null; 189 | }, 190 | 191 | // Set a hash of model attributes on the object, firing `"change"` unless you 192 | // choose to silence it. 193 | set : function(attrs, options) { 194 | 195 | // Extract attributes and options. 196 | options || (options = {}); 197 | if (!attrs) return this; 198 | if (attrs.attributes) attrs = attrs.attributes; 199 | var now = this.attributes, escaped = this._escapedAttributes; 200 | 201 | // Run validation. 202 | if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false; 203 | 204 | // Check for changes of `id`. 205 | if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; 206 | 207 | // We're about to start triggering change events. 208 | var alreadyChanging = this._changing; 209 | this._changing = true; 210 | 211 | // Update attributes. 212 | for (var attr in attrs) { 213 | var val = attrs[attr]; 214 | if (!_.isEqual(now[attr], val)) { 215 | now[attr] = val; 216 | delete escaped[attr]; 217 | this._changed = true; 218 | if (!options.silent) this.trigger('change:' + attr, this, val, options); 219 | } 220 | } 221 | 222 | // Fire the `"change"` event, if the model has been changed. 223 | if (!alreadyChanging && !options.silent && this._changed) this.change(options); 224 | this._changing = false; 225 | return this; 226 | }, 227 | 228 | // Remove an attribute from the model, firing `"change"` unless you choose 229 | // to silence it. `unset` is a noop if the attribute doesn't exist. 230 | unset : function(attr, options) { 231 | if (!(attr in this.attributes)) return this; 232 | options || (options = {}); 233 | var value = this.attributes[attr]; 234 | 235 | // Run validation. 236 | var validObj = {}; 237 | validObj[attr] = void 0; 238 | if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false; 239 | 240 | // Remove the attribute. 241 | delete this.attributes[attr]; 242 | delete this._escapedAttributes[attr]; 243 | if (attr == this.idAttribute) delete this.id; 244 | this._changed = true; 245 | if (!options.silent) { 246 | this.trigger('change:' + attr, this, void 0, options); 247 | this.change(options); 248 | } 249 | return this; 250 | }, 251 | 252 | // Clear all attributes on the model, firing `"change"` unless you choose 253 | // to silence it. 254 | clear : function(options) { 255 | options || (options = {}); 256 | var attr; 257 | var old = this.attributes; 258 | 259 | // Run validation. 260 | var validObj = {}; 261 | for (attr in old) validObj[attr] = void 0; 262 | if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false; 263 | 264 | this.attributes = {}; 265 | this._escapedAttributes = {}; 266 | this._changed = true; 267 | if (!options.silent) { 268 | for (attr in old) { 269 | this.trigger('change:' + attr, this, void 0, options); 270 | } 271 | this.change(options); 272 | } 273 | return this; 274 | }, 275 | 276 | // Fetch the model from the server. If the server's representation of the 277 | // model differs from its current attributes, they will be overriden, 278 | // triggering a `"change"` event. 279 | fetch : function(options) { 280 | options || (options = {}); 281 | var model = this; 282 | var success = options.success; 283 | options.success = function(resp, status, xhr) { 284 | if (!model.set(model.parse(resp, xhr), options)) return false; 285 | if (success) success(model, resp); 286 | }; 287 | options.error = wrapError(options.error, model, options); 288 | return (this.sync || Backbone.sync).call(this, 'read', this, options); 289 | }, 290 | 291 | // Set a hash of model attributes, and sync the model to the server. 292 | // If the server returns an attributes hash that differs, the model's 293 | // state will be `set` again. 294 | save : function(attrs, options) { 295 | options || (options = {}); 296 | if (attrs && !this.set(attrs, options)) return false; 297 | var model = this; 298 | var success = options.success; 299 | options.success = function(resp, status, xhr) { 300 | if (!model.set(model.parse(resp, xhr), options)) return false; 301 | if (success) success(model, resp, xhr); 302 | }; 303 | options.error = wrapError(options.error, model, options); 304 | var method = this.isNew() ? 'create' : 'update'; 305 | return (this.sync || Backbone.sync).call(this, method, this, options); 306 | }, 307 | 308 | // Destroy this model on the server if it was already persisted. Upon success, the model is removed 309 | // from its collection, if it has one. 310 | destroy : function(options) { 311 | options || (options = {}); 312 | if (this.isNew()) return this.trigger('destroy', this, this.collection, options); 313 | var model = this; 314 | var success = options.success; 315 | options.success = function(resp) { 316 | model.trigger('destroy', model, model.collection, options); 317 | if (success) success(model, resp); 318 | }; 319 | options.error = wrapError(options.error, model, options); 320 | return (this.sync || Backbone.sync).call(this, 'delete', this, options); 321 | }, 322 | 323 | // Default URL for the model's representation on the server -- if you're 324 | // using Backbone's restful methods, override this to change the endpoint 325 | // that will be called. 326 | url : function() { 327 | var base = getUrl(this.collection) || this.urlRoot || urlError(); 328 | if (this.isNew()) return base; 329 | return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); 330 | }, 331 | 332 | // **parse** converts a response into the hash of attributes to be `set` on 333 | // the model. The default implementation is just to pass the response along. 334 | parse : function(resp, xhr) { 335 | return resp; 336 | }, 337 | 338 | // Create a new model with identical attributes to this one. 339 | clone : function() { 340 | return new this.constructor(this); 341 | }, 342 | 343 | // A model is new if it has never been saved to the server, and lacks an id. 344 | isNew : function() { 345 | return this.id == null; 346 | }, 347 | 348 | // Call this method to manually fire a `change` event for this model. 349 | // Calling this will cause all objects observing the model to update. 350 | change : function(options) { 351 | this.trigger('change', this, options); 352 | this._previousAttributes = _.clone(this.attributes); 353 | this._changed = false; 354 | }, 355 | 356 | // Determine if the model has changed since the last `"change"` event. 357 | // If you specify an attribute name, determine if that attribute has changed. 358 | hasChanged : function(attr) { 359 | if (attr) return this._previousAttributes[attr] != this.attributes[attr]; 360 | return this._changed; 361 | }, 362 | 363 | // Return an object containing all the attributes that have changed, or false 364 | // if there are no changed attributes. Useful for determining what parts of a 365 | // view need to be updated and/or what attributes need to be persisted to 366 | // the server. 367 | changedAttributes : function(now) { 368 | now || (now = this.attributes); 369 | var old = this._previousAttributes; 370 | var changed = false; 371 | for (var attr in now) { 372 | if (!_.isEqual(old[attr], now[attr])) { 373 | changed = changed || {}; 374 | changed[attr] = now[attr]; 375 | } 376 | } 377 | return changed; 378 | }, 379 | 380 | // Get the previous value of an attribute, recorded at the time the last 381 | // `"change"` event was fired. 382 | previous : function(attr) { 383 | if (!attr || !this._previousAttributes) return null; 384 | return this._previousAttributes[attr]; 385 | }, 386 | 387 | // Get all of the attributes of the model at the time of the previous 388 | // `"change"` event. 389 | previousAttributes : function() { 390 | return _.clone(this._previousAttributes); 391 | }, 392 | 393 | // Run validation against a set of incoming attributes, returning `true` 394 | // if all is well. If a specific `error` callback has been passed, 395 | // call that instead of firing the general `"error"` event. 396 | _performValidation : function(attrs, options) { 397 | var error = this.validate(attrs); 398 | if (error) { 399 | if (options.error) { 400 | options.error(this, error, options); 401 | } else { 402 | this.trigger('error', this, error, options); 403 | } 404 | return false; 405 | } 406 | return true; 407 | } 408 | 409 | }); 410 | 411 | // Backbone.Collection 412 | // ------------------- 413 | 414 | // Provides a standard collection class for our sets of models, ordered 415 | // or unordered. If a `comparator` is specified, the Collection will maintain 416 | // its models in sort order, as they're added and removed. 417 | Backbone.Collection = function(models, options) { 418 | options || (options = {}); 419 | if (options.comparator) this.comparator = options.comparator; 420 | _.bindAll(this, '_onModelEvent', '_removeReference'); 421 | this._reset(); 422 | if (models) this.reset(models, {silent: true}); 423 | this.initialize.apply(this, arguments); 424 | }; 425 | 426 | // Define the Collection's inheritable methods. 427 | _.extend(Backbone.Collection.prototype, Backbone.Events, { 428 | 429 | // The default model for a collection is just a **Backbone.Model**. 430 | // This should be overridden in most cases. 431 | model : Backbone.Model, 432 | 433 | // Initialize is an empty function by default. Override it with your own 434 | // initialization logic. 435 | initialize : function(){}, 436 | 437 | // The JSON representation of a Collection is an array of the 438 | // models' attributes. 439 | toJSON : function() { 440 | return this.map(function(model){ return model.toJSON(); }); 441 | }, 442 | 443 | // Add a model, or list of models to the set. Pass **silent** to avoid 444 | // firing the `added` event for every new model. 445 | add : function(models, options) { 446 | if (_.isArray(models)) { 447 | for (var i = 0, l = models.length; i < l; i++) { 448 | this._add(models[i], options); 449 | } 450 | } else { 451 | this._add(models, options); 452 | } 453 | return this; 454 | }, 455 | 456 | // Remove a model, or a list of models from the set. Pass silent to avoid 457 | // firing the `removed` event for every model removed. 458 | remove : function(models, options) { 459 | if (_.isArray(models)) { 460 | for (var i = 0, l = models.length; i < l; i++) { 461 | this._remove(models[i], options); 462 | } 463 | } else { 464 | this._remove(models, options); 465 | } 466 | return this; 467 | }, 468 | 469 | // Get a model from the set by id. 470 | get : function(id) { 471 | if (id == null) return null; 472 | return this._byId[id.id != null ? id.id : id]; 473 | }, 474 | 475 | // Get a model from the set by client id. 476 | getByCid : function(cid) { 477 | return cid && this._byCid[cid.cid || cid]; 478 | }, 479 | 480 | // Get the model at the given index. 481 | at: function(index) { 482 | return this.models[index]; 483 | }, 484 | 485 | // Force the collection to re-sort itself. You don't need to call this under normal 486 | // circumstances, as the set will maintain sort order as each item is added. 487 | sort : function(options) { 488 | options || (options = {}); 489 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); 490 | this.models = this.sortBy(this.comparator); 491 | if (!options.silent) this.trigger('reset', this, options); 492 | return this; 493 | }, 494 | 495 | // Pluck an attribute from each model in the collection. 496 | pluck : function(attr) { 497 | return _.map(this.models, function(model){ return model.get(attr); }); 498 | }, 499 | 500 | // When you have more items than you want to add or remove individually, 501 | // you can reset the entire set with a new list of models, without firing 502 | // any `added` or `removed` events. Fires `reset` when finished. 503 | reset : function(models, options) { 504 | models || (models = []); 505 | options || (options = {}); 506 | this.each(this._removeReference); 507 | this._reset(); 508 | this.add(models, {silent: true}); 509 | if (!options.silent) this.trigger('reset', this, options); 510 | return this; 511 | }, 512 | 513 | // Fetch the default set of models for this collection, resetting the 514 | // collection when they arrive. If `add: true` is passed, appends the 515 | // models to the collection instead of resetting. 516 | fetch : function(options) { 517 | options || (options = {}); 518 | var collection = this; 519 | var success = options.success; 520 | options.success = function(resp, status, xhr) { 521 | collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); 522 | if (success) success(collection, resp); 523 | }; 524 | options.error = wrapError(options.error, collection, options); 525 | return (this.sync || Backbone.sync).call(this, 'read', this, options); 526 | }, 527 | 528 | // Create a new instance of a model in this collection. After the model 529 | // has been created on the server, it will be added to the collection. 530 | // Returns the model, or 'false' if validation on a new model fails. 531 | create : function(model, options) { 532 | var coll = this; 533 | options || (options = {}); 534 | model = this._prepareModel(model, options); 535 | if (!model) return false; 536 | var success = options.success; 537 | options.success = function(nextModel, resp, xhr) { 538 | coll.add(nextModel, options); 539 | if (success) success(nextModel, resp, xhr); 540 | }; 541 | model.save(null, options); 542 | return model; 543 | }, 544 | 545 | // **parse** converts a response into a list of models to be added to the 546 | // collection. The default implementation is just to pass it through. 547 | parse : function(resp, xhr) { 548 | return resp; 549 | }, 550 | 551 | // Proxy to _'s chain. Can't be proxied the same way the rest of the 552 | // underscore methods are proxied because it relies on the underscore 553 | // constructor. 554 | chain: function () { 555 | return _(this.models).chain(); 556 | }, 557 | 558 | // Reset all internal state. Called when the collection is reset. 559 | _reset : function(options) { 560 | this.length = 0; 561 | this.models = []; 562 | this._byId = {}; 563 | this._byCid = {}; 564 | }, 565 | 566 | // Prepare a model to be added to this collection 567 | _prepareModel: function(model, options) { 568 | if (!(model instanceof Backbone.Model)) { 569 | var attrs = model; 570 | model = new this.model(attrs, {collection: this}); 571 | if (model.validate && !model._performValidation(attrs, options)) model = false; 572 | } else if (!model.collection) { 573 | model.collection = this; 574 | } 575 | return model; 576 | }, 577 | 578 | // Internal implementation of adding a single model to the set, updating 579 | // hash indexes for `id` and `cid` lookups. 580 | // Returns the model, or 'false' if validation on a new model fails. 581 | _add : function(model, options) { 582 | options || (options = {}); 583 | model = this._prepareModel(model, options); 584 | if (!model) return false; 585 | var already = this.getByCid(model); 586 | if (already) throw new Error(["Can't add the same model to a set twice", already.id]); 587 | this._byId[model.id] = model; 588 | this._byCid[model.cid] = model; 589 | var index = options.at != null ? options.at : 590 | this.comparator ? this.sortedIndex(model, this.comparator) : 591 | this.length; 592 | this.models.splice(index, 0, model); 593 | model.bind('all', this._onModelEvent); 594 | this.length++; 595 | if (!options.silent) model.trigger('add', model, this, options); 596 | return model; 597 | }, 598 | 599 | // Internal implementation of removing a single model from the set, updating 600 | // hash indexes for `id` and `cid` lookups. 601 | _remove : function(model, options) { 602 | options || (options = {}); 603 | model = this.getByCid(model) || this.get(model); 604 | if (!model) return null; 605 | delete this._byId[model.id]; 606 | delete this._byCid[model.cid]; 607 | this.models.splice(this.indexOf(model), 1); 608 | this.length--; 609 | if (!options.silent) model.trigger('remove', model, this, options); 610 | this._removeReference(model); 611 | return model; 612 | }, 613 | 614 | // Internal method to remove a model's ties to a collection. 615 | _removeReference : function(model) { 616 | if (this == model.collection) { 617 | delete model.collection; 618 | } 619 | model.unbind('all', this._onModelEvent); 620 | }, 621 | 622 | // Internal method called every time a model in the set fires an event. 623 | // Sets need to update their indexes when models change ids. All other 624 | // events simply proxy through. "add" and "remove" events that originate 625 | // in other collections are ignored. 626 | _onModelEvent : function(ev, model, collection, options) { 627 | if ((ev == 'add' || ev == 'remove') && collection != this) return; 628 | if (ev == 'destroy') { 629 | this._remove(model, options); 630 | } 631 | if (model && ev === 'change:' + model.idAttribute) { 632 | delete this._byId[model.previous(model.idAttribute)]; 633 | this._byId[model.id] = model; 634 | } 635 | this.trigger.apply(this, arguments); 636 | } 637 | 638 | }); 639 | 640 | // Underscore methods that we want to implement on the Collection. 641 | var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect', 642 | 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 643 | 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', 644 | 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty', 'groupBy']; 645 | 646 | // Mix in each Underscore method as a proxy to `Collection#models`. 647 | _.each(methods, function(method) { 648 | Backbone.Collection.prototype[method] = function() { 649 | return _[method].apply(_, [this.models].concat(_.toArray(arguments))); 650 | }; 651 | }); 652 | 653 | // Backbone.Router 654 | // ------------------- 655 | 656 | // Routers map faux-URLs to actions, and fire events when routes are 657 | // matched. Creating a new one sets its `routes` hash, if not set statically. 658 | Backbone.Router = function(options) { 659 | options || (options = {}); 660 | if (options.routes) this.routes = options.routes; 661 | this._bindRoutes(); 662 | this.initialize.apply(this, arguments); 663 | }; 664 | 665 | // Cached regular expressions for matching named param parts and splatted 666 | // parts of route strings. 667 | var namedParam = /:([\w\d]+)/g; 668 | var splatParam = /\*([\w\d]+)/g; 669 | var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; 670 | 671 | // Set up all inheritable **Backbone.Router** properties and methods. 672 | _.extend(Backbone.Router.prototype, Backbone.Events, { 673 | 674 | // Initialize is an empty function by default. Override it with your own 675 | // initialization logic. 676 | initialize : function(){}, 677 | 678 | // Manually bind a single named route to a callback. For example: 679 | // 680 | // this.route('search/:query/p:num', 'search', function(query, num) { 681 | // ... 682 | // }); 683 | // 684 | route : function(route, name, callback) { 685 | Backbone.history || (Backbone.history = new Backbone.History); 686 | if (!_.isRegExp(route)) route = this._routeToRegExp(route); 687 | Backbone.history.route(route, _.bind(function(fragment) { 688 | var args = this._extractParameters(route, fragment); 689 | callback.apply(this, args); 690 | this.trigger.apply(this, ['route:' + name].concat(args)); 691 | }, this)); 692 | }, 693 | 694 | // Simple proxy to `Backbone.history` to save a fragment into the history. 695 | navigate : function(fragment, triggerRoute) { 696 | Backbone.history.navigate(fragment, triggerRoute); 697 | }, 698 | 699 | // Bind all defined routes to `Backbone.history`. We have to reverse the 700 | // order of the routes here to support behavior where the most general 701 | // routes can be defined at the bottom of the route map. 702 | _bindRoutes : function() { 703 | if (!this.routes) return; 704 | var routes = []; 705 | for (var route in this.routes) { 706 | routes.unshift([route, this.routes[route]]); 707 | } 708 | for (var i = 0, l = routes.length; i < l; i++) { 709 | this.route(routes[i][0], routes[i][1], this[routes[i][1]]); 710 | } 711 | }, 712 | 713 | // Convert a route string into a regular expression, suitable for matching 714 | // against the current location hash. 715 | _routeToRegExp : function(route) { 716 | route = route.replace(escapeRegExp, "\\$&") 717 | .replace(namedParam, "([^\/]*)") 718 | .replace(splatParam, "(.*?)"); 719 | return new RegExp('^' + route + '$'); 720 | }, 721 | 722 | // Given a route, and a URL fragment that it matches, return the array of 723 | // extracted parameters. 724 | _extractParameters : function(route, fragment) { 725 | return route.exec(fragment).slice(1); 726 | } 727 | 728 | }); 729 | 730 | // Backbone.History 731 | // ---------------- 732 | 733 | // Handles cross-browser history management, based on URL fragments. If the 734 | // browser does not support `onhashchange`, falls back to polling. 735 | Backbone.History = function() { 736 | this.handlers = []; 737 | _.bindAll(this, 'checkUrl'); 738 | }; 739 | 740 | // Cached regex for cleaning hashes. 741 | var hashStrip = /^#*/; 742 | 743 | // Cached regex for detecting MSIE. 744 | var isExplorer = /msie [\w.]+/; 745 | 746 | // Has the history handling already been started? 747 | var historyStarted = false; 748 | 749 | // Set up all inheritable **Backbone.History** properties and methods. 750 | _.extend(Backbone.History.prototype, { 751 | 752 | // The default interval to poll for hash changes, if necessary, is 753 | // twenty times a second. 754 | interval: 50, 755 | 756 | // Get the cross-browser normalized URL fragment, either from the URL, 757 | // the hash, or the override. 758 | getFragment : function(fragment, forcePushState) { 759 | if (fragment == null) { 760 | if (this._hasPushState || forcePushState) { 761 | fragment = window.location.pathname; 762 | var search = window.location.search; 763 | if (search) fragment += search; 764 | if (fragment.indexOf(this.options.root) == 0) fragment = fragment.substr(this.options.root.length); 765 | } else { 766 | fragment = window.location.hash; 767 | } 768 | } 769 | return decodeURIComponent(fragment.replace(hashStrip, '')); 770 | }, 771 | 772 | // Start the hash change handling, returning `true` if the current URL matches 773 | // an existing route, and `false` otherwise. 774 | start : function(options) { 775 | 776 | // Figure out the initial configuration. Do we need an iframe? 777 | // Is pushState desired ... is it available? 778 | if (historyStarted) throw new Error("Backbone.history has already been started"); 779 | this.options = _.extend({}, {root: '/'}, this.options, options); 780 | this._wantsPushState = !!this.options.pushState; 781 | this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); 782 | var fragment = this.getFragment(); 783 | var docMode = document.documentMode; 784 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); 785 | if (oldIE) { 786 | this.iframe = $('