From 0e330a6bae1ef35f8fef1bb93f5730fad15696f5 Mon Sep 17 00:00:00 2001 From: Colin Luo Date: Sun, 10 Nov 2013 09:13:03 +0800 Subject: [PATCH 001/107] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加自动化测试工具链接:[karma-runner](https://github.com/karma-runner/karma) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eeec76b..b880a6c 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ Frontend Knowledge Structure - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - 自动化测试 - - WebDriver + - WebDriver/[Karma Runner](https://github.com/karma-runner/karma) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) From 2c728f3d2cd1b91a60413f947ef4eac543809c45 Mon Sep 17 00:00:00 2001 From: XiNGRZ Date: Tue, 12 Nov 2013 17:31:18 +0800 Subject: [PATCH 002/107] Created english translation --- README.en.md | 245 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 245 insertions(+) create mode 100644 README.en.md diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..6295376 --- /dev/null +++ b/README.en.md @@ -0,0 +1,245 @@ +Frontend Knowledge Structure +======== + +## Original purpose + +Once upon a time, there's a graph of Frontend Knowledge Structure original posted by @jayli ... + +![Frontend Knowledge](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) + +A shortcoming of releasing the graph in form of picture is, as the technology develops, we can't make any +contribution to the graph without its source file -- That is why this GitHub repository comes. + +In this repository, every one could contribute to the project. The development of frontend profession will +also be written to the history by Git. + +Although the project would be maintained in plain text instead, I promise a small tool based on project DataV +would be developed for us to generate more funny graphs. + + +## Knowledge Structure of Frontend Development + +- Frontend Engineer + - Web browsers + - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) + - [Firefox](http://www.mozilla.org/en-US/) + - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) + - Languages + - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) + - [CoffeeScript](http://coffeescript.org/) + - [TypeScript](http://www.typescriptlang.org/) + - Slicing + - [HTML](http://www.w3.org/html/)/HTML5 + - [CSS](http://www.w3.org/Style/CSS/)/CSS3 + - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) + - Development tools + - IDE + - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) + - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) + - [WebStorm](http://www.jetbrains.com/webstorm/) + - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) + - Debugging + - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) + - [YSlow](http://developer.yahoo.com/yslow/) + - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) + - [Fiddler](http://www.fiddler2.com/fiddler2/) + - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) + - Versioning + - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) + - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) + - Code quality + - Coding style + - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) + - [CSSLint](http://csslint.net/) + - [Markup Validation Service](http://validator.w3.org/) + - Unit testing + - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) + - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) + - Auto-testing + - WebDriver/[Karma Runner](https://github.com/karma-runner/karma) + - Frontend libraries / frameworks + - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) + - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) + - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) + - [AngularJS](http://angularjs.org/) + - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) + - [Bootstrap](http://getbootstrap.com/) + - Frontend standards / specifications + - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) + - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) + - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) + - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) + - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) + - Performance + - [JSPerf](http://jsperf.com/) + - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) + - [PageSpeed](https://developers.google.com/speed/pagespeed/) + - [HTTPWatch](http://www.httpwatch.com/) + - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) + - [High-performance JavaScript](http://book.douban.com/subject/5362856/) + - Knownledge base + - Data structure + - OOP/AOP + - [Prototype chain](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/Scope chain + - [Closure](http://www.jibbering.com/faq/notes/closures/) + - Functional Programming + - [Design Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) + - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) + - Deployment flow + - Compressing and merging + - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) + - [Google Clousure Complier](https://developers.google.com/closure/compiler/) + - [UglifyJS](https://github.com/mishoo/UglifyJS) + - [CleanCSS](https://github.com/GoalSmashers/clean-css) + - Documentation generating + - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) + - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) + - Building + - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) + - [GYP](http://code.google.com/p/gyp/) + - [Grunt](http://gruntjs.com/) + - [Yeoman](http://yeoman.io/) + - Code organizing + - Modularizing libraries + - [CommonJS](http://www.commonjs.org/)/AMD + - YUI3 Modules + - Modularizing business logic + - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) + - File loaders + - [LABjs](http://labjs.com/) + - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) + - Modular preprocessor + - [Browserify](https://github.com/substack/node-browserify) + - Security + - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) + - ADsafe/Caja/Sandbox + - Mobile Web + - HTML5/CSS3 + - Responsive + - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) + - V5/[Sencha Touch](http://www.sencha.com/products/touch) + - [PhoneGap](http://phonegap.com/) + - [jQuery Mobile](http://jquerymobile.com/) + - Advanced technology communities/conferences + - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) + - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂(HTML5 Dreamworks)](http://www.html5dw.com) + - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) + - QCon/Velocity/SDCC + - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) + - [CSSConf](http://cssconf.com/) + - YDN/YUIConf + - Computer knowledge + - Compilation principle + - Network + - OS + - Algorithm principle + - Software Engineering/Software testing principle + - Soft skills + - Knowledge Management/Sharing + - Communication/Teamwork + - Requirements Management/PM + - Interaction Design/Availability/Accessibility + - Visualization + - SVG/Canvas/VML + - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) +- Backend Engineer + - Languages + - C/C++/Java/PHP/Ruby/Python/... + - Server + - [Nginx](http://nginx.org/en/) + - [Apache](http://httpd.apache.org/) + - Databases + - SQL + - MySQL/PostgreSQL/Oracle + - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) + - Data Caching + - [Redis](http://redis.io/) + - [Memcached](http://memcached.org/) + - File Cashing/Proxying + - [Varnish](https://www.varnish-cache.org/) + - [Squid](http://www.squid-cache.org/) + - OS + - Unix/Linux/OS X/Windows + - Data structure + +## Book Recommendations for Frontend-ers + +**The less and easier, the more suitable for starters** + +### CSS + +- [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ +- [精通CSS](http://book.douban.com/subject/4736167/)★★★ + +### JavaScript + +- [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ +- [JavaScript高级程序设计(第3版)](http://book.douban.com/subject/10546125/)★★ +- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ +- [高性能JavaScript](http://book.douban.com/subject/5362856/)★★★ +- [JavaScript语言精粹](http://book.douban.com/subject/3590768/)★★★ +- [JavaScript权威指南](http://book.douban.com/subject/10549733/)★★★ +- [编写可维护的JavaScript](http://book.douban.com/subject/21792530/)★★★ +- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ +- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ +- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ +- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ + +## Book Recommendations for Backend-ers + +### Linux management + +- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) +- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) +- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) +- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) +- [The Linux Command Line](http://book.douban.com/subject/6806862/) + +### Linux programming + +- [Linux程序设计](http://book.douban.com/subject/4831448/) +- [Linux系统编程](http://book.douban.com/subject/3907181/) +- [Unix环境高级编程](http://book.douban.com/subject/1788421/) +- [Unix编程艺术](http://book.douban.com/subject/1467587/) +- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) +- [程序员的自我修养](http://book.douban.com/subject/3652388/) +- [深入理解Linux内核](http://book.douban.com/subject/2287506/) +- [Unix网络编程](http://book.douban.com/subject/1500149/) +- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) + +### C/C++ +- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) +- [C和指针](http://book.douban.com/subject/3012360/) +- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) +- [C专家编程](http://book.douban.com/subject/2377310/) +- [C语言核心技术](http://book.douban.com/subject/2226913/) +- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) +- [征服C指针](http://book.douban.com/subject/21317828/) +- [C++编程思想](http://book.douban.com/subject/1094797/) +- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) + +## Contributors + +Thanks to Jayli who provided the original graph and contributors below. +Generated by `git-summary` at 2013/04/17. + +``` + + project : fks + repo age : 6 months + active : 23 days + commits : 46 + files : 3 + authors : + 31 Jackson Tian 67.4% + 3 fengxiaolong 6.5% + 3 吴晓兰 6.5% + 2 Johnny 4.3% + 2 Yinkan Li 4.3% + 1 李亚川 2.2% + 1 XiNGRZ 2.2% + 1 browsnet 2.2% + 1 monkadd 2.2% + 1 Evan You 2.2% + +``` From b966a5cf7db39e10cdf46d188e3d5657b759bde0 Mon Sep 17 00:00:00 2001 From: XiNGRZ Date: Tue, 12 Nov 2013 17:37:37 +0800 Subject: [PATCH 003/107] Update README.en.md --- README.en.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.en.md b/README.en.md index 6295376..d87cfc8 100644 --- a/README.en.md +++ b/README.en.md @@ -44,7 +44,7 @@ would be developed for us to generate more funny graphs. - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) - [Fiddler](http://www.fiddler2.com/fiddler2/) - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) - - Versioning + - Source Version Control - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) - Code quality From 9d8f7563bff3c6fa4e41d023fce30be9ec1c98b6 Mon Sep 17 00:00:00 2001 From: zhaqiang Date: Wed, 13 Nov 2013 21:53:53 +0800 Subject: [PATCH 004/107] Translated some Chinese version of books into their origianl English version and updated links to amazon.com --- README.en.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.en.md b/README.en.md index d87cfc8..89a144a 100644 --- a/README.en.md +++ b/README.en.md @@ -168,18 +168,18 @@ would be developed for us to generate more funny graphs. ### CSS -- [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ -- [精通CSS](http://book.douban.com/subject/4736167/)★★★ +- [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ +- [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ ### JavaScript -- [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ -- [JavaScript高级程序设计(第3版)](http://book.douban.com/subject/10546125/)★★ +- [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ +- [Professional JavaScript for Web Developsers (Third Edition)](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/)★★ - [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ -- [高性能JavaScript](http://book.douban.com/subject/5362856/)★★★ -- [JavaScript语言精粹](http://book.douban.com/subject/3590768/)★★★ -- [JavaScript权威指南](http://book.douban.com/subject/10549733/)★★★ -- [编写可维护的JavaScript](http://book.douban.com/subject/21792530/)★★★ +- [High Performance JavaScript](ihttp://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X/)★★★ +- [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/)★★★ +- [JavaScript: The Definitive Guide (Sixth Edition)](http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/)★★★ +- [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680/)★★★ - [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ - [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ From dbcc936cd930f30b77a09bf892c835b6abf82403 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Mon, 18 Nov 2013 15:22:39 +0800 Subject: [PATCH 005/107] =?UTF-8?q?=E8=B0=83=E6=95=B4=E8=8B=B1=E6=96=87?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E7=9A=84=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.en.md | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/README.en.md b/README.en.md index 89a144a..9eb0e8a 100644 --- a/README.en.md +++ b/README.en.md @@ -1,24 +1,15 @@ Frontend Knowledge Structure ======== - ## Original purpose - Once upon a time, there's a graph of Frontend Knowledge Structure original posted by @jayli ... ![Frontend Knowledge](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) -A shortcoming of releasing the graph in form of picture is, as the technology develops, we can't make any -contribution to the graph without its source file -- That is why this GitHub repository comes. - -In this repository, every one could contribute to the project. The development of frontend profession will -also be written to the history by Git. - -Although the project would be maintained in plain text instead, I promise a small tool based on project DataV -would be developed for us to generate more funny graphs. +A shortcoming of releasing the graph in form of picture is, as the technology develops, we can't make any contribution to the graph without its source file -- That is why this GitHub repository comes. In this repository, every one could contribute to the project. The development of frontend profession will also be written to the history by Git. +Although the project would be maintained in plain text instead, I promise a small tool based on project DataV would be developed for us to generate more funny graphs. ## Knowledge Structure of Frontend Development - - Frontend Engineer - Web browsers - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) @@ -163,16 +154,13 @@ would be developed for us to generate more funny graphs. - Data structure ## Book Recommendations for Frontend-ers - -**The less and easier, the more suitable for starters** +The ★ less and easier, the more suitable for starters ### CSS - - [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ - [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ ### JavaScript - - [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ - [Professional JavaScript for Web Developsers (Third Edition)](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/)★★ - [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ @@ -186,9 +174,7 @@ would be developed for us to generate more funny graphs. - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ ## Book Recommendations for Backend-ers - ### Linux management - - [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) - [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) - [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) @@ -196,7 +182,6 @@ would be developed for us to generate more funny graphs. - [The Linux Command Line](http://book.douban.com/subject/6806862/) ### Linux programming - - [Linux程序设计](http://book.douban.com/subject/4831448/) - [Linux系统编程](http://book.douban.com/subject/3907181/) - [Unix环境高级编程](http://book.douban.com/subject/1788421/) @@ -219,9 +204,7 @@ would be developed for us to generate more funny graphs. - [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) ## Contributors - -Thanks to Jayli who provided the original graph and contributors below. -Generated by `git-summary` at 2013/04/17. +Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2013/04/17. ``` From 28f02567c1ccf70a1dcc07be8c31fa1068247332 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 18 Nov 2013 20:27:26 +0800 Subject: [PATCH 006/107] =?UTF-8?q?=E8=A1=A5=E4=BA=86=E5=87=A0=E4=B8=AA?= =?UTF-8?q?=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b880a6c..5cfc208 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Frontend Knowledge Structure - [TypeScript](http://www.typescriptlang.org/) - 切页面 - [HTML](http://www.w3.org/html/)/HTML5 - - [CSS](http://www.w3.org/Style/CSS/)/CSS3 + - [CSS/CSS3](http://www.w3.org/Style/CSS/) - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) - 开发工具 - IDE @@ -47,13 +47,13 @@ Frontend Knowledge Structure - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - 自动化测试 - - WebDriver/[Karma Runner](https://github.com/karma-runner/karma) + - [WebDriver](http://www.cnblogs.com/huang0925/p/3155763.html)/[Karma Runner](https://github.com/karma-runner/karma) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - [AngularJS](http://angularjs.org/) - - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) + - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) - 前端标准/规范 - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) @@ -93,7 +93,7 @@ Frontend Knowledge Structure - 代码组织 - 类库模块化 - [CommonJS](http://www.commonjs.org/)/AMD - - YUI3模块 + - [YUI3模块](http://yuilibrary.com/projects/yui3/) - 业务逻辑模块化 - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) - 文件加载 From b48b64ff7036086db6c7dbd1cdcc444c3d7391c0 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Tue, 19 Nov 2013 09:53:18 +0800 Subject: [PATCH 007/107] Update README.md - Link to official site of webdriver - revert back layout (Batarang). Thanks to @JacksonTian --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5cfc208..0b7af63 100644 --- a/README.md +++ b/README.md @@ -47,13 +47,13 @@ Frontend Knowledge Structure - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - 自动化测试 - - [WebDriver](http://www.cnblogs.com/huang0925/p/3155763.html)/[Karma Runner](https://github.com/karma-runner/karma) + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - [AngularJS](http://angularjs.org/) - - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) + - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) - 前端标准/规范 - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) From a8417cce5d49f3dccf09b0627f763fa8536497f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E6=99=93=E5=85=B0?= Date: Thu, 21 Nov 2013 11:33:53 +0800 Subject: [PATCH 008/107] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对js的★的作用讲解修改了下注释.因为比如说编写可维护的JavaScript这本书难度其实不是很高,但是它比较适合在后面看,所以放在了比较中间的位置. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0b7af63..d00a433 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ Frontend Knowledge Structure - 数据结构 ## 前端书籍推荐 -★越少越简单,越适合入门 +★越少越简单,越适合入门,★多的要么是难度比较高,要么是比较适合在后面看,比如讲性能之类的书. ### CSS - [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ From e115810d9e69574fa5b2bb17af3a58bbe4b2e2fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E6=99=93=E5=85=B0?= Date: Thu, 21 Nov 2013 11:54:36 +0800 Subject: [PATCH 009/107] Update README.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此次提交的作用:增加了我看过的两本版本控制工具的书.因为我觉得前端其实也一定得会用版本控制工具.所以增加了两本这方面的书籍.尤其是在团队人多一点的时候,上到测试环境和正式环境流程比较复杂的时候. 另外.@朴灵大大.github可以编辑完两个文件一次commit吗?还是得一个文件编辑完后一次commit? --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 0b7af63..e202bf5 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,10 @@ Frontend Knowledge Structure - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ +### 版本控制工具 +- [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ +- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ + ## 后端书籍推荐 ### Linux管理 - [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) From 95e42a92e75ecc3007d2e065a666f4560397b323 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E6=99=93=E5=85=B0?= Date: Thu, 21 Nov 2013 12:00:51 +0800 Subject: [PATCH 010/107] Update README.en.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对应着中文版增加的git书籍. --- README.en.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.en.md b/README.en.md index 9eb0e8a..03bf358 100644 --- a/README.en.md +++ b/README.en.md @@ -172,6 +172,9 @@ The ★ less and easier, the more suitable for starters - [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ +### VCS +- [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ +- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ ## Book Recommendations for Backend-ers ### Linux management From bcb6a31af676827a435c81c85b490841f7757ebb Mon Sep 17 00:00:00 2001 From: Glowin Date: Mon, 25 Nov 2013 01:59:51 +0800 Subject: [PATCH 011/107] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20HTML5=20=E6=AD=A3?= =?UTF-8?q?=E5=BC=8F=E8=A7=84=E8=8C=83=E8=8D=89=E6=A1=88=E7=9A=84=E9=93=BE?= =?UTF-8?q?=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 21099f4..40b8ab0 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Frontend Knowledge Structure - [CoffeeScript](http://coffeescript.org/) - [TypeScript](http://www.typescriptlang.org/) - 切页面 - - [HTML](http://www.w3.org/html/)/HTML5 + - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS/CSS3](http://www.w3.org/Style/CSS/) - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) - 开发工具 From 1ca160a6489edee7ccf7c473fa54e1154104cd0b Mon Sep 17 00:00:00 2001 From: Glowin Date: Mon, 25 Nov 2013 02:03:11 +0800 Subject: [PATCH 012/107] =?UTF-8?q?=E8=8B=B1=E6=96=87=E7=89=88=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=20HTML5=20=E6=AD=A3=E5=BC=8F=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E8=8D=89=E6=A1=88=E7=9A=84=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.en.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.en.md b/README.en.md index 03bf358..f32b824 100644 --- a/README.en.md +++ b/README.en.md @@ -20,7 +20,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [CoffeeScript](http://coffeescript.org/) - [TypeScript](http://www.typescriptlang.org/) - Slicing - - [HTML](http://www.w3.org/html/)/HTML5 + - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS](http://www.w3.org/Style/CSS/)/CSS3 - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) - Development tools From e69eae0f1d82d2cd76ae4a3014b027ce199ec331 Mon Sep 17 00:00:00 2001 From: doabit Date: Mon, 25 Nov 2013 23:05:17 +0800 Subject: [PATCH 013/107] Add Semantic UI --- README.en.md | 1 + README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README.en.md b/README.en.md index f32b824..e038301 100644 --- a/README.en.md +++ b/README.en.md @@ -55,6 +55,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [AngularJS](http://angularjs.org/) - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) + - [Semantic UI](http://www.semantic-ui.com/) - Frontend standards / specifications - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) diff --git a/README.md b/README.md index 40b8ab0..c2f781a 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ Frontend Knowledge Structure - [AngularJS](http://angularjs.org/) - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) + - [Semantic UI](http://www.semantic-ui.com/) - 前端标准/规范 - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) From e6d3c155ad851c372efe3694746be6836f8eafab Mon Sep 17 00:00:00 2001 From: weiwenqing Date: Mon, 9 Dec 2013 10:40:43 +0800 Subject: [PATCH 014/107] =?UTF-8?q?=E3=80=8AInside=20the=20C++=20Object=20?= =?UTF-8?q?Model=E3=80=8B=E8=AE=B2=E4=BA=86c++=E5=86=85=E9=83=A8=E7=9A=84?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 本书不是讲C++相关的技术,而是讲C++的内部实现机制,如果想深入的理解C++,本书是非常好的书。对于很多C++技术,看了它的设计思想以及内部实现后,定会恍然大悟。 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c2f781a..057e887 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,7 @@ Frontend Knowledge Structure - [征服C指针](http://book.douban.com/subject/21317828/) - [C++编程思想](http://book.douban.com/subject/1094797/) - [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) +- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) ## 内容贡献者 除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2013-04-17: From 3f7a6809f53bd4847a6b952273ae0b8142acfb2b Mon Sep 17 00:00:00 2001 From: weiwenqing Date: Mon, 9 Dec 2013 10:59:53 +0800 Subject: [PATCH 015/107] =?UTF-8?q?=E3=80=8AInside=20the=20C++=20Object=20?= =?UTF-8?q?Model=E3=80=8Banalysis=20the=20implementation=20of=20C++?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.en.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.en.md b/README.en.md index e038301..bc67b42 100644 --- a/README.en.md +++ b/README.en.md @@ -206,6 +206,7 @@ The ★ less and easier, the more suitable for starters - [征服C指针](http://book.douban.com/subject/21317828/) - [C++编程思想](http://book.douban.com/subject/1094797/) - [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) +- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) ## Contributors Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2013/04/17. From a31ea2d1d520590e8baddfa27b6ab44aa1d50409 Mon Sep 17 00:00:00 2001 From: liyinkan Date: Mon, 9 Dec 2013 20:04:19 +0800 Subject: [PATCH 016/107] add Sahi in auto-testing tools add Sahi in auto-testing tools both copied link from cn to en for WebDriver --- README.en.md | 466 +++++++++++++++++++++++++------------------------- README.md | 468 +++++++++++++++++++++++++-------------------------- 2 files changed, 467 insertions(+), 467 deletions(-) diff --git a/README.en.md b/README.en.md index bc67b42..a207b88 100644 --- a/README.en.md +++ b/README.en.md @@ -1,233 +1,233 @@ -Frontend Knowledge Structure -======== -## Original purpose -Once upon a time, there's a graph of Frontend Knowledge Structure original posted by @jayli ... - -![Frontend Knowledge](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) - -A shortcoming of releasing the graph in form of picture is, as the technology develops, we can't make any contribution to the graph without its source file -- That is why this GitHub repository comes. In this repository, every one could contribute to the project. The development of frontend profession will also be written to the history by Git. - -Although the project would be maintained in plain text instead, I promise a small tool based on project DataV would be developed for us to generate more funny graphs. - -## Knowledge Structure of Frontend Development -- Frontend Engineer - - Web browsers - - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) - - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) - - Languages - - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - - [CoffeeScript](http://coffeescript.org/) - - [TypeScript](http://www.typescriptlang.org/) - - Slicing - - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - - [CSS](http://www.w3.org/Style/CSS/)/CSS3 - - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) - - Development tools - - IDE - - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - - [WebStorm](http://www.jetbrains.com/webstorm/) - - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - - Debugging - - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - - [YSlow](http://developer.yahoo.com/yslow/) - - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) - - [Fiddler](http://www.fiddler2.com/fiddler2/) - - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) - - Source Version Control - - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) - - Code quality - - Coding style - - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) - - [CSSLint](http://csslint.net/) - - [Markup Validation Service](http://validator.w3.org/) - - Unit testing - - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - - Auto-testing - - WebDriver/[Karma Runner](https://github.com/karma-runner/karma) - - Frontend libraries / frameworks - - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) - - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - - [AngularJS](http://angularjs.org/) - - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - - [Bootstrap](http://getbootstrap.com/) - - [Semantic UI](http://www.semantic-ui.com/) - - Frontend standards / specifications - - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) - - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) - - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) - - Performance - - [JSPerf](http://jsperf.com/) - - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) - - [PageSpeed](https://developers.google.com/speed/pagespeed/) - - [HTTPWatch](http://www.httpwatch.com/) - - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - - [High-performance JavaScript](http://book.douban.com/subject/5362856/) - - Knownledge base - - Data structure - - OOP/AOP - - [Prototype chain](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/Scope chain - - [Closure](http://www.jibbering.com/faq/notes/closures/) - - Functional Programming - - [Design Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) - - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) - - Deployment flow - - Compressing and merging - - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) - - [Google Clousure Complier](https://developers.google.com/closure/compiler/) - - [UglifyJS](https://github.com/mishoo/UglifyJS) - - [CleanCSS](https://github.com/GoalSmashers/clean-css) - - Documentation generating - - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) - - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) - - Building - - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - - [GYP](http://code.google.com/p/gyp/) - - [Grunt](http://gruntjs.com/) - - [Yeoman](http://yeoman.io/) - - Code organizing - - Modularizing libraries - - [CommonJS](http://www.commonjs.org/)/AMD - - YUI3 Modules - - Modularizing business logic - - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) - - File loaders - - [LABjs](http://labjs.com/) - - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) - - Modular preprocessor - - [Browserify](https://github.com/substack/node-browserify) - - Security - - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) - - ADsafe/Caja/Sandbox - - Mobile Web - - HTML5/CSS3 - - Responsive - - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) - - V5/[Sencha Touch](http://www.sencha.com/products/touch) - - [PhoneGap](http://phonegap.com/) - - [jQuery Mobile](http://jquerymobile.com/) - - Advanced technology communities/conferences - - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) - - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂(HTML5 Dreamworks)](http://www.html5dw.com) - - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) - - QCon/Velocity/SDCC - - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) - - [CSSConf](http://cssconf.com/) - - YDN/YUIConf - - Computer knowledge - - Compilation principle - - Network - - OS - - Algorithm principle - - Software Engineering/Software testing principle - - Soft skills - - Knowledge Management/Sharing - - Communication/Teamwork - - Requirements Management/PM - - Interaction Design/Availability/Accessibility - - Visualization - - SVG/Canvas/VML - - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) -- Backend Engineer - - Languages - - C/C++/Java/PHP/Ruby/Python/... - - Server - - [Nginx](http://nginx.org/en/) - - [Apache](http://httpd.apache.org/) - - Databases - - SQL - - MySQL/PostgreSQL/Oracle - - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - - Data Caching - - [Redis](http://redis.io/) - - [Memcached](http://memcached.org/) - - File Cashing/Proxying - - [Varnish](https://www.varnish-cache.org/) - - [Squid](http://www.squid-cache.org/) - - OS - - Unix/Linux/OS X/Windows - - Data structure - -## Book Recommendations for Frontend-ers -The ★ less and easier, the more suitable for starters - -### CSS -- [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ -- [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ - -### JavaScript -- [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ -- [Professional JavaScript for Web Developsers (Third Edition)](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/)★★ -- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ -- [High Performance JavaScript](ihttp://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X/)★★★ -- [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/)★★★ -- [JavaScript: The Definitive Guide (Sixth Edition)](http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/)★★★ -- [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680/)★★★ -- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ -- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ -- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ -- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ -### VCS -- [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ -- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ - -## Book Recommendations for Backend-ers -### Linux management -- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) -- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) -- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) -- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) -- [The Linux Command Line](http://book.douban.com/subject/6806862/) - -### Linux programming -- [Linux程序设计](http://book.douban.com/subject/4831448/) -- [Linux系统编程](http://book.douban.com/subject/3907181/) -- [Unix环境高级编程](http://book.douban.com/subject/1788421/) -- [Unix编程艺术](http://book.douban.com/subject/1467587/) -- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) -- [程序员的自我修养](http://book.douban.com/subject/3652388/) -- [深入理解Linux内核](http://book.douban.com/subject/2287506/) -- [Unix网络编程](http://book.douban.com/subject/1500149/) -- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) - -### C/C++ -- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) -- [C和指针](http://book.douban.com/subject/3012360/) -- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) -- [C专家编程](http://book.douban.com/subject/2377310/) -- [C语言核心技术](http://book.douban.com/subject/2226913/) -- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) -- [征服C指针](http://book.douban.com/subject/21317828/) -- [C++编程思想](http://book.douban.com/subject/1094797/) -- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) -- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) - -## Contributors -Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2013/04/17. - -``` - - project : fks - repo age : 6 months - active : 23 days - commits : 46 - files : 3 - authors : - 31 Jackson Tian 67.4% - 3 fengxiaolong 6.5% - 3 吴晓兰 6.5% - 2 Johnny 4.3% - 2 Yinkan Li 4.3% - 1 李亚川 2.2% - 1 XiNGRZ 2.2% - 1 browsnet 2.2% - 1 monkadd 2.2% - 1 Evan You 2.2% - -``` +Frontend Knowledge Structure +======== +## Original purpose +Once upon a time, there's a graph of Frontend Knowledge Structure original posted by @jayli ... + +![Frontend Knowledge](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) + +A shortcoming of releasing the graph in form of picture is, as the technology develops, we can't make any contribution to the graph without its source file -- That is why this GitHub repository comes. In this repository, every one could contribute to the project. The development of frontend profession will also be written to the history by Git. + +Although the project would be maintained in plain text instead, I promise a small tool based on project DataV would be developed for us to generate more funny graphs. + +## Knowledge Structure of Frontend Development +- Frontend Engineer + - Web browsers + - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) + - [Firefox](http://www.mozilla.org/en-US/) + - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) + - Languages + - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) + - [CoffeeScript](http://coffeescript.org/) + - [TypeScript](http://www.typescriptlang.org/) + - Slicing + - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) + - [CSS](http://www.w3.org/Style/CSS/)/CSS3 + - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) + - Development tools + - IDE + - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) + - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) + - [WebStorm](http://www.jetbrains.com/webstorm/) + - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) + - Debugging + - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) + - [YSlow](http://developer.yahoo.com/yslow/) + - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) + - [Fiddler](http://www.fiddler2.com/fiddler2/) + - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) + - Source Version Control + - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) + - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) + - Code quality + - Coding style + - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) + - [CSSLint](http://csslint.net/) + - [Markup Validation Service](http://validator.w3.org/) + - Unit testing + - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) + - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) + - Auto-testing + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) + - Frontend libraries / frameworks + - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) + - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) + - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) + - [AngularJS](http://angularjs.org/) + - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) + - [Bootstrap](http://getbootstrap.com/) + - [Semantic UI](http://www.semantic-ui.com/) + - Frontend standards / specifications + - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) + - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) + - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) + - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) + - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) + - Performance + - [JSPerf](http://jsperf.com/) + - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) + - [PageSpeed](https://developers.google.com/speed/pagespeed/) + - [HTTPWatch](http://www.httpwatch.com/) + - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) + - [High-performance JavaScript](http://book.douban.com/subject/5362856/) + - Knownledge base + - Data structure + - OOP/AOP + - [Prototype chain](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/Scope chain + - [Closure](http://www.jibbering.com/faq/notes/closures/) + - Functional Programming + - [Design Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) + - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) + - Deployment flow + - Compressing and merging + - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) + - [Google Clousure Complier](https://developers.google.com/closure/compiler/) + - [UglifyJS](https://github.com/mishoo/UglifyJS) + - [CleanCSS](https://github.com/GoalSmashers/clean-css) + - Documentation generating + - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) + - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) + - Building + - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) + - [GYP](http://code.google.com/p/gyp/) + - [Grunt](http://gruntjs.com/) + - [Yeoman](http://yeoman.io/) + - Code organizing + - Modularizing libraries + - [CommonJS](http://www.commonjs.org/)/AMD + - YUI3 Modules + - Modularizing business logic + - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) + - File loaders + - [LABjs](http://labjs.com/) + - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) + - Modular preprocessor + - [Browserify](https://github.com/substack/node-browserify) + - Security + - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) + - ADsafe/Caja/Sandbox + - Mobile Web + - HTML5/CSS3 + - Responsive + - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) + - V5/[Sencha Touch](http://www.sencha.com/products/touch) + - [PhoneGap](http://phonegap.com/) + - [jQuery Mobile](http://jquerymobile.com/) + - Advanced technology communities/conferences + - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) + - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂(HTML5 Dreamworks)](http://www.html5dw.com) + - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) + - QCon/Velocity/SDCC + - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) + - [CSSConf](http://cssconf.com/) + - YDN/YUIConf + - Computer knowledge + - Compilation principle + - Network + - OS + - Algorithm principle + - Software Engineering/Software testing principle + - Soft skills + - Knowledge Management/Sharing + - Communication/Teamwork + - Requirements Management/PM + - Interaction Design/Availability/Accessibility + - Visualization + - SVG/Canvas/VML + - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) +- Backend Engineer + - Languages + - C/C++/Java/PHP/Ruby/Python/... + - Server + - [Nginx](http://nginx.org/en/) + - [Apache](http://httpd.apache.org/) + - Databases + - SQL + - MySQL/PostgreSQL/Oracle + - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) + - Data Caching + - [Redis](http://redis.io/) + - [Memcached](http://memcached.org/) + - File Cashing/Proxying + - [Varnish](https://www.varnish-cache.org/) + - [Squid](http://www.squid-cache.org/) + - OS + - Unix/Linux/OS X/Windows + - Data structure + +## Book Recommendations for Frontend-ers +The ★ less and easier, the more suitable for starters + +### CSS +- [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ +- [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ + +### JavaScript +- [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ +- [Professional JavaScript for Web Developsers (Third Edition)](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/)★★ +- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ +- [High Performance JavaScript](ihttp://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X/)★★★ +- [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/)★★★ +- [JavaScript: The Definitive Guide (Sixth Edition)](http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/)★★★ +- [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680/)★★★ +- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ +- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ +- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ +- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ +### VCS +- [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ +- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ + +## Book Recommendations for Backend-ers +### Linux management +- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) +- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) +- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) +- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) +- [The Linux Command Line](http://book.douban.com/subject/6806862/) + +### Linux programming +- [Linux程序设计](http://book.douban.com/subject/4831448/) +- [Linux系统编程](http://book.douban.com/subject/3907181/) +- [Unix环境高级编程](http://book.douban.com/subject/1788421/) +- [Unix编程艺术](http://book.douban.com/subject/1467587/) +- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) +- [程序员的自我修养](http://book.douban.com/subject/3652388/) +- [深入理解Linux内核](http://book.douban.com/subject/2287506/) +- [Unix网络编程](http://book.douban.com/subject/1500149/) +- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) + +### C/C++ +- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) +- [C和指针](http://book.douban.com/subject/3012360/) +- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) +- [C专家编程](http://book.douban.com/subject/2377310/) +- [C语言核心技术](http://book.douban.com/subject/2226913/) +- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) +- [征服C指针](http://book.douban.com/subject/21317828/) +- [C++编程思想](http://book.douban.com/subject/1094797/) +- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) +- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) + +## Contributors +Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2013/04/17. + +``` + + project : fks + repo age : 6 months + active : 23 days + commits : 46 + files : 3 + authors : + 31 Jackson Tian 67.4% + 3 fengxiaolong 6.5% + 3 吴晓兰 6.5% + 2 Johnny 4.3% + 2 Yinkan Li 4.3% + 1 李亚川 2.2% + 1 XiNGRZ 2.2% + 1 browsnet 2.2% + 1 monkadd 2.2% + 1 Evan You 2.2% + +``` diff --git a/README.md b/README.md index 057e887..fcee6e3 100644 --- a/README.md +++ b/README.md @@ -1,234 +1,234 @@ -Frontend Knowledge Structure -======== -## 项目起源 -还记得@jayli 的这幅前端知识结构图么。 - -![前端知识结构](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) - -图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个github项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 - -尽管会变成文字的方式来维护这些内容,但是我承诺写一个小工具帮大家生成更好玩的图形(基于DataV项目)。 - -## 前端开发知识结构 -- 前端工程师 - - 浏览器 - - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) - - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) - - 编程语言 - - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - - [CoffeeScript](http://coffeescript.org/) - - [TypeScript](http://www.typescriptlang.org/) - - 切页面 - - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - - [CSS/CSS3](http://www.w3.org/Style/CSS/) - - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) - - 开发工具 - - IDE - - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - - [WebStorm](http://www.jetbrains.com/webstorm/) - - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - - 调试工具 - - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - - [YSlow](http://developer.yahoo.com/yslow/) - - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) - - [Fiddler](http://www.fiddler2.com/fiddler2/) - - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) - - 版本管理 - - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) - - 代码质量 - - Coding style - - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) - - [CSSLint](http://csslint.net/) - - [Markup Validation Service](http://validator.w3.org/) - - 单元测试 - - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - - 自动化测试 - - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma) - - 前端库/框架 - - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) - - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - - [AngularJS](http://angularjs.org/) - - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - - [Bootstrap](http://getbootstrap.com/) - - [Semantic UI](http://www.semantic-ui.com/) - - 前端标准/规范 - - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) - - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) - - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) - - 性能 - - [JSPerf](http://jsperf.com/) - - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) - - [PageSpeed](https://developers.google.com/speed/pagespeed/) - - [HTTPWatch](http://www.httpwatch.com/) - - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - - [高性能JavaScript](http://book.douban.com/subject/5362856/) - - 编程知识储备 - - 数据结构 - - OOP/AOP - - [原型链](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/作用域链 - - [闭包](http://www.jibbering.com/faq/notes/closures/) - - 函数式编程 - - [设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) - - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) - - 部署流程 - - 压缩合并 - - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) - - [Google Clousure Complier](https://developers.google.com/closure/compiler/) - - [UglifyJS](https://github.com/mishoo/UglifyJS) - - [CleanCSS](https://github.com/GoalSmashers/clean-css) - - 文档输出 - - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) - - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) - - 项目构建工具 - - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - - [GYP](http://code.google.com/p/gyp/) - - [Grunt](http://gruntjs.com/) - - [Yeoman](http://yeoman.io/) - - 代码组织 - - 类库模块化 - - [CommonJS](http://www.commonjs.org/)/AMD - - [YUI3模块](http://yuilibrary.com/projects/yui3/) - - 业务逻辑模块化 - - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) - - 文件加载 - - [LABjs](http://labjs.com/) - - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) - - 模块化预处理器 - - [Browserify](https://github.com/substack/node-browserify) - - 安全 - - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) - - ADsafe/Caja/Sandbox - - 移动Web - - HTML5/CSS3 - - 响应式设计 - - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) - - V5/[Sencha Touch](http://www.sencha.com/products/touch) - - [PhoneGap](http://phonegap.com/) - - [jQuery Mobile](http://jquerymobile.com/) - - 前沿技术社区/会议 - - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) - - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂](http://www.html5dw.com) - - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) - - QCon/Velocity/SDCC - - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) - - [CSSConf](http://cssconf.com/) - - YDN/YUIConf - - 计算机知识储备 - - 编译原理 - - 计算机网络 - - 操作系统 - - 算法原理 - - 软件工程/软件测试原理 - - 软技能 - - 知识管理/总结分享 - - 沟通技巧/团队协作 - - 需求管理/PM - - 交互设计/可用性/可访问性知识 - - 可视化 - - SVG/Canvas/VML - - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) -- 后端工程师 - - 编程语言 - - C/C++/Java/PHP/Ruby/Python/... - - 服务器 - - [Nginx](http://nginx.org/en/) - - [Apache](http://httpd.apache.org/) - - 数据库 - - SQL - - MySQL/PostgreSQL/Oracle - - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - - 数据缓存 - - [Redis](http://redis.io/) - - [Memcached](http://memcached.org/) - - 文件缓存/代理 - - [Varnish](https://www.varnish-cache.org/) - - [Squid](http://www.squid-cache.org/) - - 操作系统 - - Unix/Linux/OS X/Windows - - 数据结构 - -## 前端书籍推荐 -★越少越简单,越适合入门,★多的要么是难度比较高,要么是比较适合在后面看,比如讲性能之类的书. - -### CSS -- [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ -- [精通CSS](http://book.douban.com/subject/4736167/)★★★ - -### JavaScript -- [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ -- [JavaScript高级程序设计(第3版)](http://book.douban.com/subject/10546125/)★★ -- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ -- [高性能JavaScript](http://book.douban.com/subject/5362856/)★★★ -- [JavaScript语言精粹](http://book.douban.com/subject/3590768/)★★★ -- [JavaScript权威指南](http://book.douban.com/subject/10549733/)★★★ -- [编写可维护的JavaScript](http://book.douban.com/subject/21792530/)★★★ -- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ -- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ -- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ -- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - -### 版本控制工具 -- [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ -- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ - -## 后端书籍推荐 -### Linux管理 -- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) -- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) -- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) -- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) -- [The Linux Command Line](http://book.douban.com/subject/6806862/) - -### Linux编程 -- [Linux程序设计](http://book.douban.com/subject/4831448/) -- [Linux系统编程](http://book.douban.com/subject/3907181/) -- [Unix环境高级编程](http://book.douban.com/subject/1788421/) -- [Unix编程艺术](http://book.douban.com/subject/1467587/) -- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) -- [程序员的自我修养](http://book.douban.com/subject/3652388/) -- [深入理解Linux内核](http://book.douban.com/subject/2287506/) -- [Unix网络编程](http://book.douban.com/subject/1500149/) -- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) - -### C/C++ -- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) -- [C和指针](http://book.douban.com/subject/3012360/) -- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) -- [C专家编程](http://book.douban.com/subject/2377310/) -- [C语言核心技术](http://book.douban.com/subject/2226913/) -- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) -- [征服C指针](http://book.douban.com/subject/21317828/) -- [C++编程思想](http://book.douban.com/subject/1094797/) -- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) -- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) - -## 内容贡献者 -除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2013-04-17: - -``` - - project : fks - repo age : 6 months - active : 23 days - commits : 46 - files : 3 - authors : - 31 Jackson Tian 67.4% - 3 fengxiaolong 6.5% - 3 吴晓兰 6.5% - 2 Johnny 4.3% - 2 Yinkan Li 4.3% - 1 李亚川 2.2% - 1 XiNGRZ 2.2% - 1 browsnet 2.2% - 1 monkadd 2.2% - 1 Evan You 2.2% - -``` +Frontend Knowledge Structure +======== +## 项目起源 +还记得@jayli 的这幅前端知识结构图么。 + +![前端知识结构](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) + +图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个github项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 + +尽管会变成文字的方式来维护这些内容,但是我承诺写一个小工具帮大家生成更好玩的图形(基于DataV项目)。 + +## 前端开发知识结构 +- 前端工程师 + - 浏览器 + - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) + - [Firefox](http://www.mozilla.org/en-US/) + - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) + - 编程语言 + - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) + - [CoffeeScript](http://coffeescript.org/) + - [TypeScript](http://www.typescriptlang.org/) + - 切页面 + - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) + - [CSS/CSS3](http://www.w3.org/Style/CSS/) + - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) + - 开发工具 + - IDE + - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) + - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) + - [WebStorm](http://www.jetbrains.com/webstorm/) + - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) + - 调试工具 + - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) + - [YSlow](http://developer.yahoo.com/yslow/) + - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) + - [Fiddler](http://www.fiddler2.com/fiddler2/) + - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) + - 版本管理 + - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) + - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) + - 代码质量 + - Coding style + - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) + - [CSSLint](http://csslint.net/) + - [Markup Validation Service](http://validator.w3.org/) + - 单元测试 + - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) + - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) + - 自动化测试 + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) + - 前端库/框架 + - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) + - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) + - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) + - [AngularJS](http://angularjs.org/) + - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) + - [Bootstrap](http://getbootstrap.com/) + - [Semantic UI](http://www.semantic-ui.com/) + - 前端标准/规范 + - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) + - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) + - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) + - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) + - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) + - 性能 + - [JSPerf](http://jsperf.com/) + - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) + - [PageSpeed](https://developers.google.com/speed/pagespeed/) + - [HTTPWatch](http://www.httpwatch.com/) + - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) + - [高性能JavaScript](http://book.douban.com/subject/5362856/) + - 编程知识储备 + - 数据结构 + - OOP/AOP + - [原型链](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/作用域链 + - [闭包](http://www.jibbering.com/faq/notes/closures/) + - 函数式编程 + - [设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) + - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) + - 部署流程 + - 压缩合并 + - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) + - [Google Clousure Complier](https://developers.google.com/closure/compiler/) + - [UglifyJS](https://github.com/mishoo/UglifyJS) + - [CleanCSS](https://github.com/GoalSmashers/clean-css) + - 文档输出 + - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) + - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) + - 项目构建工具 + - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) + - [GYP](http://code.google.com/p/gyp/) + - [Grunt](http://gruntjs.com/) + - [Yeoman](http://yeoman.io/) + - 代码组织 + - 类库模块化 + - [CommonJS](http://www.commonjs.org/)/AMD + - [YUI3模块](http://yuilibrary.com/projects/yui3/) + - 业务逻辑模块化 + - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) + - 文件加载 + - [LABjs](http://labjs.com/) + - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) + - 模块化预处理器 + - [Browserify](https://github.com/substack/node-browserify) + - 安全 + - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) + - ADsafe/Caja/Sandbox + - 移动Web + - HTML5/CSS3 + - 响应式设计 + - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) + - V5/[Sencha Touch](http://www.sencha.com/products/touch) + - [PhoneGap](http://phonegap.com/) + - [jQuery Mobile](http://jquerymobile.com/) + - 前沿技术社区/会议 + - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) + - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂](http://www.html5dw.com) + - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) + - QCon/Velocity/SDCC + - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) + - [CSSConf](http://cssconf.com/) + - YDN/YUIConf + - 计算机知识储备 + - 编译原理 + - 计算机网络 + - 操作系统 + - 算法原理 + - 软件工程/软件测试原理 + - 软技能 + - 知识管理/总结分享 + - 沟通技巧/团队协作 + - 需求管理/PM + - 交互设计/可用性/可访问性知识 + - 可视化 + - SVG/Canvas/VML + - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) +- 后端工程师 + - 编程语言 + - C/C++/Java/PHP/Ruby/Python/... + - 服务器 + - [Nginx](http://nginx.org/en/) + - [Apache](http://httpd.apache.org/) + - 数据库 + - SQL + - MySQL/PostgreSQL/Oracle + - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) + - 数据缓存 + - [Redis](http://redis.io/) + - [Memcached](http://memcached.org/) + - 文件缓存/代理 + - [Varnish](https://www.varnish-cache.org/) + - [Squid](http://www.squid-cache.org/) + - 操作系统 + - Unix/Linux/OS X/Windows + - 数据结构 + +## 前端书籍推荐 +★越少越简单,越适合入门,★多的要么是难度比较高,要么是比较适合在后面看,比如讲性能之类的书. + +### CSS +- [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ +- [精通CSS](http://book.douban.com/subject/4736167/)★★★ + +### JavaScript +- [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ +- [JavaScript高级程序设计(第3版)](http://book.douban.com/subject/10546125/)★★ +- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ +- [高性能JavaScript](http://book.douban.com/subject/5362856/)★★★ +- [JavaScript语言精粹](http://book.douban.com/subject/3590768/)★★★ +- [JavaScript权威指南](http://book.douban.com/subject/10549733/)★★★ +- [编写可维护的JavaScript](http://book.douban.com/subject/21792530/)★★★ +- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ +- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ +- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ +- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ + +### 版本控制工具 +- [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ +- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ + +## 后端书籍推荐 +### Linux管理 +- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) +- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) +- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) +- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) +- [The Linux Command Line](http://book.douban.com/subject/6806862/) + +### Linux编程 +- [Linux程序设计](http://book.douban.com/subject/4831448/) +- [Linux系统编程](http://book.douban.com/subject/3907181/) +- [Unix环境高级编程](http://book.douban.com/subject/1788421/) +- [Unix编程艺术](http://book.douban.com/subject/1467587/) +- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) +- [程序员的自我修养](http://book.douban.com/subject/3652388/) +- [深入理解Linux内核](http://book.douban.com/subject/2287506/) +- [Unix网络编程](http://book.douban.com/subject/1500149/) +- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) + +### C/C++ +- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) +- [C和指针](http://book.douban.com/subject/3012360/) +- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) +- [C专家编程](http://book.douban.com/subject/2377310/) +- [C语言核心技术](http://book.douban.com/subject/2226913/) +- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) +- [征服C指针](http://book.douban.com/subject/21317828/) +- [C++编程思想](http://book.douban.com/subject/1094797/) +- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) +- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) + +## 内容贡献者 +除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2013-04-17: + +``` + + project : fks + repo age : 6 months + active : 23 days + commits : 46 + files : 3 + authors : + 31 Jackson Tian 67.4% + 3 fengxiaolong 6.5% + 3 吴晓兰 6.5% + 2 Johnny 4.3% + 2 Yinkan Li 4.3% + 1 李亚川 2.2% + 1 XiNGRZ 2.2% + 1 browsnet 2.2% + 1 monkadd 2.2% + 1 Evan You 2.2% + +``` From deba2f269ad35d76bff4ad637f557f0a54e28cbf Mon Sep 17 00:00:00 2001 From: liyinkan Date: Mon, 9 Dec 2013 20:06:40 +0800 Subject: [PATCH 017/107] Revert "add Sahi in auto-testing tools" This reverts commit a31ea2d1d520590e8baddfa27b6ab44aa1d50409. --- README.en.md | 466 +++++++++++++++++++++++++------------------------- README.md | 468 +++++++++++++++++++++++++-------------------------- 2 files changed, 467 insertions(+), 467 deletions(-) diff --git a/README.en.md b/README.en.md index a207b88..bc67b42 100644 --- a/README.en.md +++ b/README.en.md @@ -1,233 +1,233 @@ -Frontend Knowledge Structure -======== -## Original purpose -Once upon a time, there's a graph of Frontend Knowledge Structure original posted by @jayli ... - -![Frontend Knowledge](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) - -A shortcoming of releasing the graph in form of picture is, as the technology develops, we can't make any contribution to the graph without its source file -- That is why this GitHub repository comes. In this repository, every one could contribute to the project. The development of frontend profession will also be written to the history by Git. - -Although the project would be maintained in plain text instead, I promise a small tool based on project DataV would be developed for us to generate more funny graphs. - -## Knowledge Structure of Frontend Development -- Frontend Engineer - - Web browsers - - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) - - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) - - Languages - - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - - [CoffeeScript](http://coffeescript.org/) - - [TypeScript](http://www.typescriptlang.org/) - - Slicing - - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - - [CSS](http://www.w3.org/Style/CSS/)/CSS3 - - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) - - Development tools - - IDE - - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - - [WebStorm](http://www.jetbrains.com/webstorm/) - - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - - Debugging - - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - - [YSlow](http://developer.yahoo.com/yslow/) - - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) - - [Fiddler](http://www.fiddler2.com/fiddler2/) - - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) - - Source Version Control - - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) - - Code quality - - Coding style - - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) - - [CSSLint](http://csslint.net/) - - [Markup Validation Service](http://validator.w3.org/) - - Unit testing - - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - - Auto-testing - - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - - Frontend libraries / frameworks - - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) - - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - - [AngularJS](http://angularjs.org/) - - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - - [Bootstrap](http://getbootstrap.com/) - - [Semantic UI](http://www.semantic-ui.com/) - - Frontend standards / specifications - - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) - - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) - - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) - - Performance - - [JSPerf](http://jsperf.com/) - - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) - - [PageSpeed](https://developers.google.com/speed/pagespeed/) - - [HTTPWatch](http://www.httpwatch.com/) - - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - - [High-performance JavaScript](http://book.douban.com/subject/5362856/) - - Knownledge base - - Data structure - - OOP/AOP - - [Prototype chain](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/Scope chain - - [Closure](http://www.jibbering.com/faq/notes/closures/) - - Functional Programming - - [Design Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) - - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) - - Deployment flow - - Compressing and merging - - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) - - [Google Clousure Complier](https://developers.google.com/closure/compiler/) - - [UglifyJS](https://github.com/mishoo/UglifyJS) - - [CleanCSS](https://github.com/GoalSmashers/clean-css) - - Documentation generating - - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) - - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) - - Building - - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - - [GYP](http://code.google.com/p/gyp/) - - [Grunt](http://gruntjs.com/) - - [Yeoman](http://yeoman.io/) - - Code organizing - - Modularizing libraries - - [CommonJS](http://www.commonjs.org/)/AMD - - YUI3 Modules - - Modularizing business logic - - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) - - File loaders - - [LABjs](http://labjs.com/) - - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) - - Modular preprocessor - - [Browserify](https://github.com/substack/node-browserify) - - Security - - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) - - ADsafe/Caja/Sandbox - - Mobile Web - - HTML5/CSS3 - - Responsive - - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) - - V5/[Sencha Touch](http://www.sencha.com/products/touch) - - [PhoneGap](http://phonegap.com/) - - [jQuery Mobile](http://jquerymobile.com/) - - Advanced technology communities/conferences - - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) - - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂(HTML5 Dreamworks)](http://www.html5dw.com) - - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) - - QCon/Velocity/SDCC - - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) - - [CSSConf](http://cssconf.com/) - - YDN/YUIConf - - Computer knowledge - - Compilation principle - - Network - - OS - - Algorithm principle - - Software Engineering/Software testing principle - - Soft skills - - Knowledge Management/Sharing - - Communication/Teamwork - - Requirements Management/PM - - Interaction Design/Availability/Accessibility - - Visualization - - SVG/Canvas/VML - - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) -- Backend Engineer - - Languages - - C/C++/Java/PHP/Ruby/Python/... - - Server - - [Nginx](http://nginx.org/en/) - - [Apache](http://httpd.apache.org/) - - Databases - - SQL - - MySQL/PostgreSQL/Oracle - - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - - Data Caching - - [Redis](http://redis.io/) - - [Memcached](http://memcached.org/) - - File Cashing/Proxying - - [Varnish](https://www.varnish-cache.org/) - - [Squid](http://www.squid-cache.org/) - - OS - - Unix/Linux/OS X/Windows - - Data structure - -## Book Recommendations for Frontend-ers -The ★ less and easier, the more suitable for starters - -### CSS -- [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ -- [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ - -### JavaScript -- [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ -- [Professional JavaScript for Web Developsers (Third Edition)](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/)★★ -- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ -- [High Performance JavaScript](ihttp://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X/)★★★ -- [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/)★★★ -- [JavaScript: The Definitive Guide (Sixth Edition)](http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/)★★★ -- [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680/)★★★ -- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ -- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ -- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ -- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ -### VCS -- [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ -- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ - -## Book Recommendations for Backend-ers -### Linux management -- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) -- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) -- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) -- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) -- [The Linux Command Line](http://book.douban.com/subject/6806862/) - -### Linux programming -- [Linux程序设计](http://book.douban.com/subject/4831448/) -- [Linux系统编程](http://book.douban.com/subject/3907181/) -- [Unix环境高级编程](http://book.douban.com/subject/1788421/) -- [Unix编程艺术](http://book.douban.com/subject/1467587/) -- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) -- [程序员的自我修养](http://book.douban.com/subject/3652388/) -- [深入理解Linux内核](http://book.douban.com/subject/2287506/) -- [Unix网络编程](http://book.douban.com/subject/1500149/) -- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) - -### C/C++ -- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) -- [C和指针](http://book.douban.com/subject/3012360/) -- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) -- [C专家编程](http://book.douban.com/subject/2377310/) -- [C语言核心技术](http://book.douban.com/subject/2226913/) -- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) -- [征服C指针](http://book.douban.com/subject/21317828/) -- [C++编程思想](http://book.douban.com/subject/1094797/) -- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) -- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) - -## Contributors -Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2013/04/17. - -``` - - project : fks - repo age : 6 months - active : 23 days - commits : 46 - files : 3 - authors : - 31 Jackson Tian 67.4% - 3 fengxiaolong 6.5% - 3 吴晓兰 6.5% - 2 Johnny 4.3% - 2 Yinkan Li 4.3% - 1 李亚川 2.2% - 1 XiNGRZ 2.2% - 1 browsnet 2.2% - 1 monkadd 2.2% - 1 Evan You 2.2% - -``` +Frontend Knowledge Structure +======== +## Original purpose +Once upon a time, there's a graph of Frontend Knowledge Structure original posted by @jayli ... + +![Frontend Knowledge](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) + +A shortcoming of releasing the graph in form of picture is, as the technology develops, we can't make any contribution to the graph without its source file -- That is why this GitHub repository comes. In this repository, every one could contribute to the project. The development of frontend profession will also be written to the history by Git. + +Although the project would be maintained in plain text instead, I promise a small tool based on project DataV would be developed for us to generate more funny graphs. + +## Knowledge Structure of Frontend Development +- Frontend Engineer + - Web browsers + - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) + - [Firefox](http://www.mozilla.org/en-US/) + - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) + - Languages + - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) + - [CoffeeScript](http://coffeescript.org/) + - [TypeScript](http://www.typescriptlang.org/) + - Slicing + - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) + - [CSS](http://www.w3.org/Style/CSS/)/CSS3 + - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) + - Development tools + - IDE + - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) + - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) + - [WebStorm](http://www.jetbrains.com/webstorm/) + - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) + - Debugging + - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) + - [YSlow](http://developer.yahoo.com/yslow/) + - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) + - [Fiddler](http://www.fiddler2.com/fiddler2/) + - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) + - Source Version Control + - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) + - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) + - Code quality + - Coding style + - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) + - [CSSLint](http://csslint.net/) + - [Markup Validation Service](http://validator.w3.org/) + - Unit testing + - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) + - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) + - Auto-testing + - WebDriver/[Karma Runner](https://github.com/karma-runner/karma) + - Frontend libraries / frameworks + - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) + - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) + - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) + - [AngularJS](http://angularjs.org/) + - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) + - [Bootstrap](http://getbootstrap.com/) + - [Semantic UI](http://www.semantic-ui.com/) + - Frontend standards / specifications + - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) + - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) + - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) + - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) + - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) + - Performance + - [JSPerf](http://jsperf.com/) + - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) + - [PageSpeed](https://developers.google.com/speed/pagespeed/) + - [HTTPWatch](http://www.httpwatch.com/) + - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) + - [High-performance JavaScript](http://book.douban.com/subject/5362856/) + - Knownledge base + - Data structure + - OOP/AOP + - [Prototype chain](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/Scope chain + - [Closure](http://www.jibbering.com/faq/notes/closures/) + - Functional Programming + - [Design Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) + - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) + - Deployment flow + - Compressing and merging + - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) + - [Google Clousure Complier](https://developers.google.com/closure/compiler/) + - [UglifyJS](https://github.com/mishoo/UglifyJS) + - [CleanCSS](https://github.com/GoalSmashers/clean-css) + - Documentation generating + - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) + - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) + - Building + - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) + - [GYP](http://code.google.com/p/gyp/) + - [Grunt](http://gruntjs.com/) + - [Yeoman](http://yeoman.io/) + - Code organizing + - Modularizing libraries + - [CommonJS](http://www.commonjs.org/)/AMD + - YUI3 Modules + - Modularizing business logic + - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) + - File loaders + - [LABjs](http://labjs.com/) + - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) + - Modular preprocessor + - [Browserify](https://github.com/substack/node-browserify) + - Security + - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) + - ADsafe/Caja/Sandbox + - Mobile Web + - HTML5/CSS3 + - Responsive + - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) + - V5/[Sencha Touch](http://www.sencha.com/products/touch) + - [PhoneGap](http://phonegap.com/) + - [jQuery Mobile](http://jquerymobile.com/) + - Advanced technology communities/conferences + - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) + - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂(HTML5 Dreamworks)](http://www.html5dw.com) + - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) + - QCon/Velocity/SDCC + - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) + - [CSSConf](http://cssconf.com/) + - YDN/YUIConf + - Computer knowledge + - Compilation principle + - Network + - OS + - Algorithm principle + - Software Engineering/Software testing principle + - Soft skills + - Knowledge Management/Sharing + - Communication/Teamwork + - Requirements Management/PM + - Interaction Design/Availability/Accessibility + - Visualization + - SVG/Canvas/VML + - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) +- Backend Engineer + - Languages + - C/C++/Java/PHP/Ruby/Python/... + - Server + - [Nginx](http://nginx.org/en/) + - [Apache](http://httpd.apache.org/) + - Databases + - SQL + - MySQL/PostgreSQL/Oracle + - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) + - Data Caching + - [Redis](http://redis.io/) + - [Memcached](http://memcached.org/) + - File Cashing/Proxying + - [Varnish](https://www.varnish-cache.org/) + - [Squid](http://www.squid-cache.org/) + - OS + - Unix/Linux/OS X/Windows + - Data structure + +## Book Recommendations for Frontend-ers +The ★ less and easier, the more suitable for starters + +### CSS +- [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ +- [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ + +### JavaScript +- [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ +- [Professional JavaScript for Web Developsers (Third Edition)](http://www.amazon.com/Professional-JavaScript-Developers-Nicholas-Zakas/dp/1118026691/)★★ +- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ +- [High Performance JavaScript](ihttp://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X/)★★★ +- [JavaScript: The Good Parts](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/)★★★ +- [JavaScript: The Definitive Guide (Sixth Edition)](http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527/)★★★ +- [Maintainable JavaScript](http://www.amazon.com/Maintainable-JavaScript-Nicholas-C-Zakas/dp/1449327680/)★★★ +- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ +- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ +- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ +- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ +### VCS +- [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ +- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ + +## Book Recommendations for Backend-ers +### Linux management +- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) +- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) +- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) +- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) +- [The Linux Command Line](http://book.douban.com/subject/6806862/) + +### Linux programming +- [Linux程序设计](http://book.douban.com/subject/4831448/) +- [Linux系统编程](http://book.douban.com/subject/3907181/) +- [Unix环境高级编程](http://book.douban.com/subject/1788421/) +- [Unix编程艺术](http://book.douban.com/subject/1467587/) +- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) +- [程序员的自我修养](http://book.douban.com/subject/3652388/) +- [深入理解Linux内核](http://book.douban.com/subject/2287506/) +- [Unix网络编程](http://book.douban.com/subject/1500149/) +- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) + +### C/C++ +- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) +- [C和指针](http://book.douban.com/subject/3012360/) +- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) +- [C专家编程](http://book.douban.com/subject/2377310/) +- [C语言核心技术](http://book.douban.com/subject/2226913/) +- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) +- [征服C指针](http://book.douban.com/subject/21317828/) +- [C++编程思想](http://book.douban.com/subject/1094797/) +- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) +- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) + +## Contributors +Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2013/04/17. + +``` + + project : fks + repo age : 6 months + active : 23 days + commits : 46 + files : 3 + authors : + 31 Jackson Tian 67.4% + 3 fengxiaolong 6.5% + 3 吴晓兰 6.5% + 2 Johnny 4.3% + 2 Yinkan Li 4.3% + 1 李亚川 2.2% + 1 XiNGRZ 2.2% + 1 browsnet 2.2% + 1 monkadd 2.2% + 1 Evan You 2.2% + +``` diff --git a/README.md b/README.md index fcee6e3..057e887 100644 --- a/README.md +++ b/README.md @@ -1,234 +1,234 @@ -Frontend Knowledge Structure -======== -## 项目起源 -还记得@jayli 的这幅前端知识结构图么。 - -![前端知识结构](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) - -图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个github项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 - -尽管会变成文字的方式来维护这些内容,但是我承诺写一个小工具帮大家生成更好玩的图形(基于DataV项目)。 - -## 前端开发知识结构 -- 前端工程师 - - 浏览器 - - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) - - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) - - 编程语言 - - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - - [CoffeeScript](http://coffeescript.org/) - - [TypeScript](http://www.typescriptlang.org/) - - 切页面 - - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - - [CSS/CSS3](http://www.w3.org/Style/CSS/) - - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) - - 开发工具 - - IDE - - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - - [WebStorm](http://www.jetbrains.com/webstorm/) - - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - - 调试工具 - - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - - [YSlow](http://developer.yahoo.com/yslow/) - - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) - - [Fiddler](http://www.fiddler2.com/fiddler2/) - - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) - - 版本管理 - - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) - - 代码质量 - - Coding style - - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) - - [CSSLint](http://csslint.net/) - - [Markup Validation Service](http://validator.w3.org/) - - 单元测试 - - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - - 自动化测试 - - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - - 前端库/框架 - - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) - - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - - [AngularJS](http://angularjs.org/) - - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - - [Bootstrap](http://getbootstrap.com/) - - [Semantic UI](http://www.semantic-ui.com/) - - 前端标准/规范 - - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) - - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) - - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) - - 性能 - - [JSPerf](http://jsperf.com/) - - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) - - [PageSpeed](https://developers.google.com/speed/pagespeed/) - - [HTTPWatch](http://www.httpwatch.com/) - - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - - [高性能JavaScript](http://book.douban.com/subject/5362856/) - - 编程知识储备 - - 数据结构 - - OOP/AOP - - [原型链](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/作用域链 - - [闭包](http://www.jibbering.com/faq/notes/closures/) - - 函数式编程 - - [设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) - - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) - - 部署流程 - - 压缩合并 - - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) - - [Google Clousure Complier](https://developers.google.com/closure/compiler/) - - [UglifyJS](https://github.com/mishoo/UglifyJS) - - [CleanCSS](https://github.com/GoalSmashers/clean-css) - - 文档输出 - - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) - - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) - - 项目构建工具 - - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - - [GYP](http://code.google.com/p/gyp/) - - [Grunt](http://gruntjs.com/) - - [Yeoman](http://yeoman.io/) - - 代码组织 - - 类库模块化 - - [CommonJS](http://www.commonjs.org/)/AMD - - [YUI3模块](http://yuilibrary.com/projects/yui3/) - - 业务逻辑模块化 - - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) - - 文件加载 - - [LABjs](http://labjs.com/) - - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) - - 模块化预处理器 - - [Browserify](https://github.com/substack/node-browserify) - - 安全 - - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) - - ADsafe/Caja/Sandbox - - 移动Web - - HTML5/CSS3 - - 响应式设计 - - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) - - V5/[Sencha Touch](http://www.sencha.com/products/touch) - - [PhoneGap](http://phonegap.com/) - - [jQuery Mobile](http://jquerymobile.com/) - - 前沿技术社区/会议 - - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) - - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂](http://www.html5dw.com) - - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) - - QCon/Velocity/SDCC - - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) - - [CSSConf](http://cssconf.com/) - - YDN/YUIConf - - 计算机知识储备 - - 编译原理 - - 计算机网络 - - 操作系统 - - 算法原理 - - 软件工程/软件测试原理 - - 软技能 - - 知识管理/总结分享 - - 沟通技巧/团队协作 - - 需求管理/PM - - 交互设计/可用性/可访问性知识 - - 可视化 - - SVG/Canvas/VML - - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) -- 后端工程师 - - 编程语言 - - C/C++/Java/PHP/Ruby/Python/... - - 服务器 - - [Nginx](http://nginx.org/en/) - - [Apache](http://httpd.apache.org/) - - 数据库 - - SQL - - MySQL/PostgreSQL/Oracle - - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - - 数据缓存 - - [Redis](http://redis.io/) - - [Memcached](http://memcached.org/) - - 文件缓存/代理 - - [Varnish](https://www.varnish-cache.org/) - - [Squid](http://www.squid-cache.org/) - - 操作系统 - - Unix/Linux/OS X/Windows - - 数据结构 - -## 前端书籍推荐 -★越少越简单,越适合入门,★多的要么是难度比较高,要么是比较适合在后面看,比如讲性能之类的书. - -### CSS -- [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ -- [精通CSS](http://book.douban.com/subject/4736167/)★★★ - -### JavaScript -- [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ -- [JavaScript高级程序设计(第3版)](http://book.douban.com/subject/10546125/)★★ -- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ -- [高性能JavaScript](http://book.douban.com/subject/5362856/)★★★ -- [JavaScript语言精粹](http://book.douban.com/subject/3590768/)★★★ -- [JavaScript权威指南](http://book.douban.com/subject/10549733/)★★★ -- [编写可维护的JavaScript](http://book.douban.com/subject/21792530/)★★★ -- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ -- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ -- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ -- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - -### 版本控制工具 -- [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ -- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ - -## 后端书籍推荐 -### Linux管理 -- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) -- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) -- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) -- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) -- [The Linux Command Line](http://book.douban.com/subject/6806862/) - -### Linux编程 -- [Linux程序设计](http://book.douban.com/subject/4831448/) -- [Linux系统编程](http://book.douban.com/subject/3907181/) -- [Unix环境高级编程](http://book.douban.com/subject/1788421/) -- [Unix编程艺术](http://book.douban.com/subject/1467587/) -- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) -- [程序员的自我修养](http://book.douban.com/subject/3652388/) -- [深入理解Linux内核](http://book.douban.com/subject/2287506/) -- [Unix网络编程](http://book.douban.com/subject/1500149/) -- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) - -### C/C++ -- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) -- [C和指针](http://book.douban.com/subject/3012360/) -- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) -- [C专家编程](http://book.douban.com/subject/2377310/) -- [C语言核心技术](http://book.douban.com/subject/2226913/) -- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) -- [征服C指针](http://book.douban.com/subject/21317828/) -- [C++编程思想](http://book.douban.com/subject/1094797/) -- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) -- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) - -## 内容贡献者 -除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2013-04-17: - -``` - - project : fks - repo age : 6 months - active : 23 days - commits : 46 - files : 3 - authors : - 31 Jackson Tian 67.4% - 3 fengxiaolong 6.5% - 3 吴晓兰 6.5% - 2 Johnny 4.3% - 2 Yinkan Li 4.3% - 1 李亚川 2.2% - 1 XiNGRZ 2.2% - 1 browsnet 2.2% - 1 monkadd 2.2% - 1 Evan You 2.2% - -``` +Frontend Knowledge Structure +======== +## 项目起源 +还记得@jayli 的这幅前端知识结构图么。 + +![前端知识结构](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) + +图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个github项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 + +尽管会变成文字的方式来维护这些内容,但是我承诺写一个小工具帮大家生成更好玩的图形(基于DataV项目)。 + +## 前端开发知识结构 +- 前端工程师 + - 浏览器 + - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) + - [Firefox](http://www.mozilla.org/en-US/) + - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) + - 编程语言 + - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) + - [CoffeeScript](http://coffeescript.org/) + - [TypeScript](http://www.typescriptlang.org/) + - 切页面 + - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) + - [CSS/CSS3](http://www.w3.org/Style/CSS/) + - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) + - 开发工具 + - IDE + - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) + - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) + - [WebStorm](http://www.jetbrains.com/webstorm/) + - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) + - 调试工具 + - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) + - [YSlow](http://developer.yahoo.com/yslow/) + - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) + - [Fiddler](http://www.fiddler2.com/fiddler2/) + - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) + - 版本管理 + - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) + - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) + - 代码质量 + - Coding style + - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) + - [CSSLint](http://csslint.net/) + - [Markup Validation Service](http://validator.w3.org/) + - 单元测试 + - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) + - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) + - 自动化测试 + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma) + - 前端库/框架 + - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) + - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) + - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) + - [AngularJS](http://angularjs.org/) + - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) + - [Bootstrap](http://getbootstrap.com/) + - [Semantic UI](http://www.semantic-ui.com/) + - 前端标准/规范 + - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) + - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) + - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) + - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) + - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) + - 性能 + - [JSPerf](http://jsperf.com/) + - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) + - [PageSpeed](https://developers.google.com/speed/pagespeed/) + - [HTTPWatch](http://www.httpwatch.com/) + - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) + - [高性能JavaScript](http://book.douban.com/subject/5362856/) + - 编程知识储备 + - 数据结构 + - OOP/AOP + - [原型链](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/作用域链 + - [闭包](http://www.jibbering.com/faq/notes/closures/) + - 函数式编程 + - [设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) + - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) + - 部署流程 + - 压缩合并 + - [YUI Compressor](http://developer.yahoo.com/yui/compressor/) + - [Google Clousure Complier](https://developers.google.com/closure/compiler/) + - [UglifyJS](https://github.com/mishoo/UglifyJS) + - [CleanCSS](https://github.com/GoalSmashers/clean-css) + - 文档输出 + - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) + - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) + - 项目构建工具 + - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) + - [GYP](http://code.google.com/p/gyp/) + - [Grunt](http://gruntjs.com/) + - [Yeoman](http://yeoman.io/) + - 代码组织 + - 类库模块化 + - [CommonJS](http://www.commonjs.org/)/AMD + - [YUI3模块](http://yuilibrary.com/projects/yui3/) + - 业务逻辑模块化 + - [bower](https://github.com/twitter/bower)/[component](https://github.com/component/component) + - 文件加载 + - [LABjs](http://labjs.com/) + - [SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/) + - 模块化预处理器 + - [Browserify](https://github.com/substack/node-browserify) + - 安全 + - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) + - ADsafe/Caja/Sandbox + - 移动Web + - HTML5/CSS3 + - 响应式设计 + - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) + - V5/[Sencha Touch](http://www.sencha.com/products/touch) + - [PhoneGap](http://phonegap.com/) + - [jQuery Mobile](http://jquerymobile.com/) + - 前沿技术社区/会议 + - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) + - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂](http://www.html5dw.com) + - [JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn) + - QCon/Velocity/SDCC + - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) + - [CSSConf](http://cssconf.com/) + - YDN/YUIConf + - 计算机知识储备 + - 编译原理 + - 计算机网络 + - 操作系统 + - 算法原理 + - 软件工程/软件测试原理 + - 软技能 + - 知识管理/总结分享 + - 沟通技巧/团队协作 + - 需求管理/PM + - 交互设计/可用性/可访问性知识 + - 可视化 + - SVG/Canvas/VML + - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) +- 后端工程师 + - 编程语言 + - C/C++/Java/PHP/Ruby/Python/... + - 服务器 + - [Nginx](http://nginx.org/en/) + - [Apache](http://httpd.apache.org/) + - 数据库 + - SQL + - MySQL/PostgreSQL/Oracle + - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) + - 数据缓存 + - [Redis](http://redis.io/) + - [Memcached](http://memcached.org/) + - 文件缓存/代理 + - [Varnish](https://www.varnish-cache.org/) + - [Squid](http://www.squid-cache.org/) + - 操作系统 + - Unix/Linux/OS X/Windows + - 数据结构 + +## 前端书籍推荐 +★越少越简单,越适合入门,★多的要么是难度比较高,要么是比较适合在后面看,比如讲性能之类的书. + +### CSS +- [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ +- [精通CSS](http://book.douban.com/subject/4736167/)★★★ + +### JavaScript +- [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ +- [JavaScript高级程序设计(第3版)](http://book.douban.com/subject/10546125/)★★ +- [锋利的jQuery](http://book.douban.com/subject/10792216/)★★ +- [高性能JavaScript](http://book.douban.com/subject/5362856/)★★★ +- [JavaScript语言精粹](http://book.douban.com/subject/3590768/)★★★ +- [JavaScript权威指南](http://book.douban.com/subject/10549733/)★★★ +- [编写可维护的JavaScript](http://book.douban.com/subject/21792530/)★★★ +- [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ +- [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ +- [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ +- [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ + +### 版本控制工具 +- [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ +- [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ + +## 后端书籍推荐 +### Linux管理 +- [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) +- [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) +- [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) +- [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) +- [The Linux Command Line](http://book.douban.com/subject/6806862/) + +### Linux编程 +- [Linux程序设计](http://book.douban.com/subject/4831448/) +- [Linux系统编程](http://book.douban.com/subject/3907181/) +- [Unix环境高级编程](http://book.douban.com/subject/1788421/) +- [Unix编程艺术](http://book.douban.com/subject/1467587/) +- [The Linux Programming Interface](http://book.douban.com/subject/4292217/) +- [程序员的自我修养](http://book.douban.com/subject/3652388/) +- [深入理解Linux内核](http://book.douban.com/subject/2287506/) +- [Unix网络编程](http://book.douban.com/subject/1500149/) +- [TCP/IP高级编程](http://book.douban.com/subject/1088054/) + +### C/C++ +- [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) +- [C和指针](http://book.douban.com/subject/3012360/) +- [C陷阱与缺陷](http://book.douban.com/subject/2778632/) +- [C专家编程](http://book.douban.com/subject/2377310/) +- [C语言核心技术](http://book.douban.com/subject/2226913/) +- [彻底搞定C指针](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CDEQFjAA&url=http%3A%2F%2Fblogimg.chinaunix.net%2Fblog%2Fupfile2%2F110210170023.pdf&ei=P95mUfrmNKKriALS04HAAw&usg=AFQjCNEzB88PnpfL0fRgJDkP3O9TlBPswA&sig2=isyd4ktsByNBMa5M9EPhRQ&bvm=bv.45107431,d.cGE&cad=rjt) +- [征服C指针](http://book.douban.com/subject/21317828/) +- [C++编程思想](http://book.douban.com/subject/1094797/) +- [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) +- [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) + +## 内容贡献者 +除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2013-04-17: + +``` + + project : fks + repo age : 6 months + active : 23 days + commits : 46 + files : 3 + authors : + 31 Jackson Tian 67.4% + 3 fengxiaolong 6.5% + 3 吴晓兰 6.5% + 2 Johnny 4.3% + 2 Yinkan Li 4.3% + 1 李亚川 2.2% + 1 XiNGRZ 2.2% + 1 browsnet 2.2% + 1 monkadd 2.2% + 1 Evan You 2.2% + +``` From ca2a485becc95d442653e7071ab248b656c9ff13 Mon Sep 17 00:00:00 2001 From: liyinkan Date: Mon, 9 Dec 2013 20:11:11 +0800 Subject: [PATCH 018/107] add Sahi in auto-testing tools --- README.en.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index bc67b42..719c18f 100644 --- a/README.en.md +++ b/README.en.md @@ -47,7 +47,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - Auto-testing - - WebDriver/[Karma Runner](https://github.com/karma-runner/karma) + - WebDriver/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - Frontend libraries / frameworks - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) diff --git a/README.md b/README.md index 057e887..10b5ba9 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ Frontend Knowledge Structure - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - 自动化测试 - - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma) + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) From d0a53192a57450fc2c5341fc384427e450dfdf7a Mon Sep 17 00:00:00 2001 From: liyinkan Date: Mon, 9 Dec 2013 20:11:45 +0800 Subject: [PATCH 019/107] copy link from CN to EN for WebDriver in auto-testing tools --- README.en.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.en.md b/README.en.md index 719c18f..00cd15a 100644 --- a/README.en.md +++ b/README.en.md @@ -47,7 +47,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - Auto-testing - - WebDriver/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - Frontend libraries / frameworks - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) From c0f0eaefb7af51ae7ef582e02a6f2c44e92fd217 Mon Sep 17 00:00:00 2001 From: liyinkan Date: Mon, 9 Dec 2013 20:42:29 +0800 Subject: [PATCH 020/107] add KISSY in Lib --- README.en.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index 00cd15a..16e1178 100644 --- a/README.en.md +++ b/README.en.md @@ -50,7 +50,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - Frontend libraries / frameworks - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) + - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - [AngularJS](http://angularjs.org/) - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) diff --git a/README.md b/README.md index 10b5ba9..3887354 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Frontend Knowledge Structure - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs) + - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - [AngularJS](http://angularjs.org/) - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) From d5aae74b59a699f84aea127885502a8d65dc819f Mon Sep 17 00:00:00 2001 From: Copypeng Date: Tue, 24 Dec 2013 10:27:29 +0800 Subject: [PATCH 021/107] =?UTF-8?q?IDE=E6=B7=BB=E5=8A=A0brackets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3887354..d2bfc0e 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Frontend Knowledge Structure - 开发工具 - IDE - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) + - [Backets](http://brackets.io/) - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) From da5fd09f27651ae2843d9b689998e10520785244 Mon Sep 17 00:00:00 2001 From: Copypeng Date: Tue, 24 Dec 2013 10:30:46 +0800 Subject: [PATCH 022/107] add the Brackets editor. --- README.en.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.en.md b/README.en.md index 16e1178..8d15ea2 100644 --- a/README.en.md +++ b/README.en.md @@ -26,6 +26,7 @@ Although the project would be maintained in plain text instead, I promise a smal - Development tools - IDE - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) + - [Brackets](http://brackets.io/) - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) From caf681903d6fd43bf104624d30896d7bb1de4001 Mon Sep 17 00:00:00 2001 From: linkgod Date: Tue, 24 Dec 2013 14:53:09 +0800 Subject: [PATCH 023/107] Add some graphic frameworks --- README.en.md | 3 ++- README.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index 8d15ea2..5eed223 100644 --- a/README.en.md +++ b/README.en.md @@ -134,7 +134,8 @@ Although the project would be maintained in plain text instead, I promise a smal - Interaction Design/Availability/Accessibility - Visualization - SVG/Canvas/VML - - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) + - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) + - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) - Backend Engineer - Languages - C/C++/Java/PHP/Ruby/Python/... diff --git a/README.md b/README.md index d2bfc0e..d719e6d 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,8 @@ Frontend Knowledge Structure - 交互设计/可用性/可访问性知识 - 可视化 - SVG/Canvas/VML - - [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[DataV](http://datavlab.org/datavjs/) + - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) + - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) - 后端工程师 - 编程语言 - C/C++/Java/PHP/Ruby/Python/... From 9866cb88045b88dc991e543a486cb013d16e3a57 Mon Sep 17 00:00:00 2001 From: chriscai Date: Fri, 3 Jan 2014 08:51:53 +0800 Subject: [PATCH 024/107] =?UTF-8?q?=E8=A1=A5=E5=85=85IDE:brackets=EF=BC=8C?= =?UTF-8?q?=E8=A1=A5=E5=85=85=E5=BA=93:zepto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d719e6d..bca2b3e 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ Frontend Knowledge Structure - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) + - [Brackets](http://brackets.io) - 调试工具 - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) @@ -51,6 +52,7 @@ Frontend Knowledge Structure - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) + - [Zepto](http://zeptojs.com/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - [AngularJS](http://angularjs.org/) From b160feeee3badaa4d3b8f1079868df24cad70fab Mon Sep 17 00:00:00 2001 From: chriscai Date: Fri, 3 Jan 2014 08:56:08 +0800 Subject: [PATCH 025/107] =?UTF-8?q?=E8=A1=A5=E5=85=85=E4=B8=A4=E6=9C=AC?= =?UTF-8?q?=E4=B9=A6CSS=E7=A6=85=E6=84=8F=E8=8A=B1=E5=9B=AD=EF=BC=8C?= =?UTF-8?q?=E5=9F=BA=E4=BA=8EMVC=E7=9A=84=E5=AF=8C=E5=BA=94=E7=94=A8?= =?UTF-8?q?=E5=BC=80=E5=8F=91=EF=BC=8C=E5=88=A0=E9=99=A4=E4=BA=86=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E4=BA=86Zepto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bca2b3e..0a0ef9b 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,6 @@ Frontend Knowledge Structure - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - - [Zepto](http://zeptojs.com/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) - [Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/) - [AngularJS](http://angularjs.org/) @@ -164,6 +163,7 @@ Frontend Knowledge Structure ### CSS - [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ - [精通CSS](http://book.douban.com/subject/4736167/)★★★ +- [CSS禅意花园](http://book.douban.com/subject/2052176/)★★★ ### JavaScript - [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ @@ -177,6 +177,7 @@ Frontend Knowledge Structure - [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ +- [基于MVC的JavaScript Web富应用开发](http://book.douban.com/subject/10733304/)★★★ ### 版本控制工具 - [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ From 9c90f93e895d81307e4fce9e2a4200e1cb37f82a Mon Sep 17 00:00:00 2001 From: chriscai Date: Fri, 3 Jan 2014 11:09:21 +0800 Subject: [PATCH 026/107] add content ide & books add ide>brackets.io book>css zengarden,javascript web application --- README.en.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.en.md b/README.en.md index 5eed223..f4b933c 100644 --- a/README.en.md +++ b/README.en.md @@ -30,6 +30,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) + - [Brackets](http://brackets.io) - Debugging - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) @@ -162,6 +163,7 @@ The ★ less and easier, the more suitable for starters ### CSS - [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ - [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ +- [The Zen of CSS Design: Visual Enlightenment for the Web](http://www.amazon.com/The-Zen-CSS-Design-Enlightenment/dp/0321303474/)★★★ ### JavaScript - [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ @@ -175,6 +177,7 @@ The ★ less and easier, the more suitable for starters - [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ +- [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X)★★★★ ### VCS - [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ - [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ From 6db7ec544e366b620a9f1e0ecc445f75fbb11560 Mon Sep 17 00:00:00 2001 From: Mickey Date: Fri, 3 Jan 2014 16:42:56 +0800 Subject: [PATCH 027/107] update content --- README.en.md | 4 ++++ README.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/README.en.md b/README.en.md index 5eed223..a1be8d8 100644 --- a/README.en.md +++ b/README.en.md @@ -49,6 +49,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - Auto-testing - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) + - [phantomjs](http://phantomjs.org/) - Frontend libraries / frameworks - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) @@ -92,6 +93,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [GYP](http://code.google.com/p/gyp/) - [Grunt](http://gruntjs.com/) - [Yeoman](http://yeoman.io/) + - [FIS](http://fis.baidu.com/) - Code organizing - Modularizing libraries - [CommonJS](http://www.commonjs.org/)/AMD @@ -121,6 +123,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) - [CSSConf](http://cssconf.com/) - YDN/YUIConf + - HybridApp - Computer knowledge - Compilation principle - Network @@ -142,6 +145,7 @@ Although the project would be maintained in plain text instead, I promise a smal - Server - [Nginx](http://nginx.org/en/) - [Apache](http://httpd.apache.org/) + - [Nodejs](http://nodejs.org/) - Databases - SQL - MySQL/PostgreSQL/Oracle diff --git a/README.md b/README.md index d719e6d..3cccd3a 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ Frontend Knowledge Structure - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - 自动化测试 - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) + - [phantomjs](http://phantomjs.org/) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) @@ -92,6 +93,7 @@ Frontend Knowledge Structure - [GYP](http://code.google.com/p/gyp/) - [Grunt](http://gruntjs.com/) - [Yeoman](http://yeoman.io/) + - [FIS](http://fis.baidu.com/) - 代码组织 - 类库模块化 - [CommonJS](http://www.commonjs.org/)/AMD @@ -121,6 +123,7 @@ Frontend Knowledge Structure - [JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/) - [CSSConf](http://cssconf.com/) - YDN/YUIConf + - HybridApp - 计算机知识储备 - 编译原理 - 计算机网络 @@ -142,6 +145,7 @@ Frontend Knowledge Structure - 服务器 - [Nginx](http://nginx.org/en/) - [Apache](http://httpd.apache.org/) + - [Nodejs](http://nodejs.org/) - 数据库 - SQL - MySQL/PostgreSQL/Oracle From 8e41a6b48ab317d70e88a8e5865c749e249838c1 Mon Sep 17 00:00:00 2001 From: Mickey- Date: Fri, 3 Jan 2014 16:53:02 +0800 Subject: [PATCH 028/107] add contributor --- README.en.md | 1 + README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README.en.md b/README.en.md index a1be8d8..a4d515b 100644 --- a/README.en.md +++ b/README.en.md @@ -235,5 +235,6 @@ Thanks to Jayli who provided the original graph and contributors below. Generate 1 browsnet 2.2% 1 monkadd 2.2% 1 Evan You 2.2% + 1 Mickey- 2.2% ``` diff --git a/README.md b/README.md index 3cccd3a..d063f26 100644 --- a/README.md +++ b/README.md @@ -236,5 +236,6 @@ Frontend Knowledge Structure 1 browsnet 2.2% 1 monkadd 2.2% 1 Evan You 2.2% + 1 左岸 2.2% ``` From dc0bcdfb9924be1f6b82364477fa0db287c98a78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B7=A6=E5=B2=B8?= Date: Fri, 3 Jan 2014 17:37:18 +0800 Subject: [PATCH 029/107] Update README.md --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index d063f26..8434a19 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,6 @@ Frontend Knowledge Structure - 服务器 - [Nginx](http://nginx.org/en/) - [Apache](http://httpd.apache.org/) - - [Nodejs](http://nodejs.org/) - 数据库 - SQL - MySQL/PostgreSQL/Oracle @@ -236,6 +235,5 @@ Frontend Knowledge Structure 1 browsnet 2.2% 1 monkadd 2.2% 1 Evan You 2.2% - 1 左岸 2.2% ``` From 5d6ecf55c6a56435405f63b2dc31677090bfa433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B7=A6=E5=B2=B8?= Date: Fri, 3 Jan 2014 17:42:16 +0800 Subject: [PATCH 030/107] Update README.en.md --- README.en.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.en.md b/README.en.md index a4d515b..2ce62dd 100644 --- a/README.en.md +++ b/README.en.md @@ -145,7 +145,6 @@ Although the project would be maintained in plain text instead, I promise a smal - Server - [Nginx](http://nginx.org/en/) - [Apache](http://httpd.apache.org/) - - [Nodejs](http://nodejs.org/) - Databases - SQL - MySQL/PostgreSQL/Oracle @@ -235,6 +234,5 @@ Thanks to Jayli who provided the original graph and contributors below. Generate 1 browsnet 2.2% 1 monkadd 2.2% 1 Evan You 2.2% - 1 Mickey- 2.2% ``` From 9c4fede46b27da4a3e26395e20811883dad674ae Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Fri, 3 Jan 2014 18:26:53 +0800 Subject: [PATCH 031/107] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=AD=E8=8B=B1?= =?UTF-8?q?=E6=96=87=E4=B9=8B=E9=97=B4=E7=9A=84=E5=B7=AE=E5=BC=82=E3=80=81?= =?UTF-8?q?=E9=87=8D=E6=96=B0=E7=94=9F=E6=88=90contributors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + README.en.md | 52 +++++++++++++++++++++++++++++++++++----------------- README.md | 49 +++++++++++++++++++++++++++++++++---------------- 3 files changed, 69 insertions(+), 33 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1c25560 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +parallel.html diff --git a/README.en.md b/README.en.md index 155bb2b..8912c9e 100644 --- a/README.en.md +++ b/README.en.md @@ -181,7 +181,8 @@ The ★ less and easier, the more suitable for starters - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X)★★★★ -### VCS + +### CVS - [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ - [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ @@ -217,25 +218,42 @@ The ★ less and easier, the more suitable for starters - [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) ## Contributors -Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2013/04/17. +Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2014/01/03. ``` project : fks - repo age : 6 months - active : 23 days - commits : 46 - files : 3 - authors : - 31 Jackson Tian 67.4% - 3 fengxiaolong 6.5% - 3 吴晓兰 6.5% - 2 Johnny 4.3% - 2 Yinkan Li 4.3% - 1 李亚川 2.2% - 1 XiNGRZ 2.2% - 1 browsnet 2.2% - 1 monkadd 2.2% - 1 Evan You 2.2% + repo age : 1 year, 3 months + active : 53 days + commits : 108 + files : 4 + authors : + 56 Jackson Tian 51.9% + 9 吴晓兰 8.3% + 5 liyinkan 4.6% + 3 chriscai 2.8% + 3 fengxiaolong 2.8% + 3 XiNGRZ 2.8% + 2 monkadd 1.9% + 2 Johnny 1.9% + 2 weiwenqing 1.9% + 2 Yinkan Li 1.9% + 2 Copypeng 1.9% + 2 左岸 1.9% + 2 Jakukyo Friel 1.9% + 2 Glowin 1.9% + 1 李亚川 0.9% + 1 Evan You 0.9% + 1 Mickey 0.9% + 1 Mickey- 0.9% + 1 Qi Junyuan 0.9% + 1 browsnet 0.9% + 1 doabit 0.9% + 1 guoxiangyang 0.9% + 1 linkgod 0.9% + 1 popomore 0.9% + 1 vipzhicheng 0.9% + 1 zhaqiang 0.9% + 1 Colin Luo 0.9% ``` diff --git a/README.md b/README.md index 65f72bf..89708b8 100644 --- a/README.md +++ b/README.md @@ -218,25 +218,42 @@ Frontend Knowledge Structure - [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) ## 内容贡献者 -除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2013-04-17: +除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2014-01-03: ``` project : fks - repo age : 6 months - active : 23 days - commits : 46 - files : 3 - authors : - 31 Jackson Tian 67.4% - 3 fengxiaolong 6.5% - 3 吴晓兰 6.5% - 2 Johnny 4.3% - 2 Yinkan Li 4.3% - 1 李亚川 2.2% - 1 XiNGRZ 2.2% - 1 browsnet 2.2% - 1 monkadd 2.2% - 1 Evan You 2.2% + repo age : 1 year, 3 months + active : 53 days + commits : 108 + files : 4 + authors : + 56 Jackson Tian 51.9% + 9 吴晓兰 8.3% + 5 liyinkan 4.6% + 3 chriscai 2.8% + 3 fengxiaolong 2.8% + 3 XiNGRZ 2.8% + 2 monkadd 1.9% + 2 Johnny 1.9% + 2 weiwenqing 1.9% + 2 Yinkan Li 1.9% + 2 Copypeng 1.9% + 2 左岸 1.9% + 2 Jakukyo Friel 1.9% + 2 Glowin 1.9% + 1 李亚川 0.9% + 1 Evan You 0.9% + 1 Mickey 0.9% + 1 Mickey- 0.9% + 1 Qi Junyuan 0.9% + 1 browsnet 0.9% + 1 doabit 0.9% + 1 guoxiangyang 0.9% + 1 linkgod 0.9% + 1 popomore 0.9% + 1 vipzhicheng 0.9% + 1 zhaqiang 0.9% + 1 Colin Luo 0.9% ``` From 9c00b66e8a91fa36b6a7ee368f1a66a49d496005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=9D=E6=A1=82=E9=91=AB?= Date: Sun, 5 Jan 2014 18:01:41 +0800 Subject: [PATCH 032/107] add mod.js --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 89708b8..905cde2 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,7 @@ Frontend Knowledge Structure - [Grunt](http://gruntjs.com/) - [Yeoman](http://yeoman.io/) - [FIS](http://fis.baidu.com/) + - [Mod](https://github.com/modulejs/modjs) - 代码组织 - 类库模块化 - [CommonJS](http://www.commonjs.org/)/AMD From e31a5e3578c5cc4ef5b84a35ebf90595df666f57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=9D=E6=A1=82=E9=91=AB?= Date: Mon, 6 Jan 2014 20:58:35 +0800 Subject: [PATCH 033/107] add mod.js --- README.en.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.en.md b/README.en.md index 8912c9e..e8e82e3 100644 --- a/README.en.md +++ b/README.en.md @@ -95,6 +95,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Grunt](http://gruntjs.com/) - [Yeoman](http://yeoman.io/) - [FIS](http://fis.baidu.com/) + - [Mod](https://github.com/modulejs/modjs) - Code organizing - Modularizing libraries - [CommonJS](http://www.commonjs.org/)/AMD From 50d5637bc7919d865d9703367ffda2ff5aaa2977 Mon Sep 17 00:00:00 2001 From: Leigh Zhu Date: Thu, 9 Jan 2014 16:24:35 +0800 Subject: [PATCH 034/107] fix ie links' lang && fix ie 10 link error && add ie 11 --- README.en.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index 8912c9e..3689f59 100644 --- a/README.en.md +++ b/README.en.md @@ -12,7 +12,7 @@ Although the project would be maintained in plain text instead, I promise a smal ## Knowledge Structure of Frontend Development - Frontend Engineer - Web browsers - - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) + - IE6/[7](http://www.microsoft.com/en-US/download/details.aspx?id=2)/[8](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/en-US/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/en-US/internet-explorer/ie-11-worldwide-languages) - [Firefox](http://www.mozilla.org/en-US/) - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) - Languages diff --git a/README.md b/README.md index 89708b8..0b4d549 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Frontend Knowledge Structure ## 前端开发知识结构 - 前端工程师 - 浏览器 - - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-cn/windows-8/internet-explorer) + - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-CN/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/zh-CN/internet-explorer/ie-11-worldwide-languages) - [Firefox](http://www.mozilla.org/en-US/) - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) - 编程语言 From 783fae80618d430e3df15048fd7eab9e48bf231a Mon Sep 17 00:00:00 2001 From: songsiqi Date: Fri, 10 Jan 2014 14:34:19 +0800 Subject: [PATCH 035/107] add the book javascript pattern --- README.en.md | 1 + README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README.en.md b/README.en.md index 8912c9e..4e97aa8 100644 --- a/README.en.md +++ b/README.en.md @@ -179,6 +179,7 @@ The ★ less and easier, the more suitable for starters - [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ - [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ +- [JavaScript Patterns](http://www.amazon.cn/JavaScript-Patterns-Stefanov-Stoyan/dp/0596806752)★★★ - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X)★★★★ diff --git a/README.md b/README.md index 89708b8..8c4f64a 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ Frontend Knowledge Structure - [JAVASCRIPT语言精髓与编程实践](http://book.douban.com/subject/3012828/)★★★ - [Effective Javascript](http://www.amazon.com/Effective-JavaScript-Specific-Software-Development/dp/0321812182)★★★ - [Secrets of the JavaScript Ninja](http://book.douban.com/subject/3176860/)★★★ +- [JavaScript模式](http://book.douban.com/subject/11506062/)★★★ - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - [基于MVC的JavaScript Web富应用开发](http://book.douban.com/subject/10733304/)★★★ From e69c678812e485b212fe93f19514528070744afb Mon Sep 17 00:00:00 2001 From: Colin Luo Date: Sat, 18 Jan 2014 11:45:58 +0800 Subject: [PATCH 036/107] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=BC=80=E5=8F=91?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=EF=BC=88=20brackets=EF=BC=89=E7=9A=84?= =?UTF-8?q?=E9=93=BE=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 拼写错误(brackets错误的拼写成了backets),而且与最后一个重复 --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 89708b8..18995df 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,6 @@ Frontend Knowledge Structure - 开发工具 - IDE - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - - [Backets](http://brackets.io/) - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) From 8503eacd9c377d0a5f728f49026cf1d9d6672053 Mon Sep 17 00:00:00 2001 From: Colin Luo Date: Mon, 20 Jan 2014 09:51:48 +0800 Subject: [PATCH 037/107] Delete brackets link from development tools It was repeated; --- README.en.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.en.md b/README.en.md index 1dda1d1..b9faf0f 100644 --- a/README.en.md +++ b/README.en.md @@ -26,7 +26,6 @@ Although the project would be maintained in plain text instead, I promise a smal - Development tools - IDE - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - - [Brackets](http://brackets.io/) - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) From bd0b5b3faf14bd719e5b424fa5b6227fcd2b2de0 Mon Sep 17 00:00:00 2001 From: Yinkan Li Date: Wed, 22 Jan 2014 14:42:11 +0800 Subject: [PATCH 038/107] Added CSS books (More Eric Meyer on CSS) Added CSS books (More Eric Meyer on CSS) --- README.en.md | 1 + README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README.en.md b/README.en.md index b9faf0f..d60f887 100644 --- a/README.en.md +++ b/README.en.md @@ -164,6 +164,7 @@ Although the project would be maintained in plain text instead, I promise a smal The ★ less and easier, the more suitable for starters ### CSS +- [More Eric Meyer on CSS](http://www.amazon.com/More-Eric-Meyer-Voices-Matter/dp/0735714258/)★★★ - [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ - [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ - [The Zen of CSS Design: Visual Enlightenment for the Web](http://www.amazon.com/The-Zen-CSS-Design-Enlightenment/dp/0321303474/)★★★ diff --git a/README.md b/README.md index 6d0edbb..c62ef37 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ Frontend Knowledge Structure ★越少越简单,越适合入门,★多的要么是难度比较高,要么是比较适合在后面看,比如讲性能之类的书. ### CSS +- [Eric Meyer 谈 CSS(卷二)](http://www.amazon.cn/Eric-Meyer-谈-CSS-迈耶/dp/B00170M84I/)★★★ - [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ - [精通CSS](http://book.douban.com/subject/4736167/)★★★ - [CSS禅意花园](http://book.douban.com/subject/2052176/)★★★ From c63212961cf9c700deadb49142bdd85c80eb47d2 Mon Sep 17 00:00:00 2001 From: Colin Luo Date: Sat, 8 Feb 2014 22:17:13 +0800 Subject: [PATCH 039/107] Update README.md Add grunt doxmate link. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c62ef37..0e6929a 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ Frontend Knowledge Structure - [CleanCSS](https://github.com/GoalSmashers/clean-css) - 文档输出 - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) - - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) + - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate)/[Grunt-Doxmate](https://github.com/luozhihua/grunt-doxmate) - 项目构建工具 - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - [GYP](http://code.google.com/p/gyp/) From b5eaeba4690b1d3273a2de3ec8d3e18102707bb8 Mon Sep 17 00:00:00 2001 From: Colin Luo Date: Sat, 8 Feb 2014 22:19:35 +0800 Subject: [PATCH 040/107] Update README.en.md Add grunt doxmate link. --- README.en.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.en.md b/README.en.md index d60f887..e5e10a8 100644 --- a/README.en.md +++ b/README.en.md @@ -87,7 +87,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [CleanCSS](https://github.com/GoalSmashers/clean-css) - Documentation generating - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) - - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate) + - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate)/[Grunt-Doxmate](https://github.com/luozhihua/grunt-doxmate) - Building - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - [GYP](http://code.google.com/p/gyp/) From 080d935020bb8ef160478afb64bfbe17d1510116 Mon Sep 17 00:00:00 2001 From: "zackyang@outlook.com" Date: Sat, 29 Mar 2014 16:59:36 +0800 Subject: [PATCH 041/107] Remove book named "The Zen of CSS Design". --- README.en.md | 1 - README.md | 1 - 2 files changed, 2 deletions(-) diff --git a/README.en.md b/README.en.md index e5e10a8..5096395 100644 --- a/README.en.md +++ b/README.en.md @@ -167,7 +167,6 @@ The ★ less and easier, the more suitable for starters - [More Eric Meyer on CSS](http://www.amazon.com/More-Eric-Meyer-Voices-Matter/dp/0735714258/)★★★ - [CSS: The Definitive Guide (3rd Edition)](http://www.amazon.com/CSS-Definitive-Eric-A-Meyer/dp/0596527330/)★★ - [CSS Mastery: Advanced Web Standards Solutions](http://www.amazon.com/CSS-Mastery-Advanced-Standards-Solutions/dp/1430223979/)★★★ -- [The Zen of CSS Design: Visual Enlightenment for the Web](http://www.amazon.com/The-Zen-CSS-Design-Enlightenment/dp/0321303474/)★★★ ### JavaScript - [DOM Scripting: Web Design with JavaScript and the Document Object Model](http://www.amazon.com/DOM-Scripting-Design-JavaScript-Document/dp/1430233893/)★ diff --git a/README.md b/README.md index 0e6929a..21ea83f 100644 --- a/README.md +++ b/README.md @@ -167,7 +167,6 @@ Frontend Knowledge Structure - [Eric Meyer 谈 CSS(卷二)](http://www.amazon.cn/Eric-Meyer-谈-CSS-迈耶/dp/B00170M84I/)★★★ - [CSS权威指南 (第3版)](http://book.douban.com/subject/2308234/)★★ - [精通CSS](http://book.douban.com/subject/4736167/)★★★ -- [CSS禅意花园](http://book.douban.com/subject/2052176/)★★★ ### JavaScript - [JavaScript DOM编程艺术 (第2版)](http://book.douban.com/subject/6038371/)★ From 9b90e5414c01b1d465abc6f69ee53e58470812fd Mon Sep 17 00:00:00 2001 From: Benjy Cui Date: Sun, 30 Mar 2014 10:57:05 +0800 Subject: [PATCH 042/107] Add jscs to coding style. --- README.en.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index 5096395..75dc66b 100644 --- a/README.en.md +++ b/README.en.md @@ -41,7 +41,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) - Code quality - Coding style - - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) + - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs) - [CSSLint](http://csslint.net/) - [Markup Validation Service](http://validator.w3.org/) - Unit testing diff --git a/README.md b/README.md index 21ea83f..357dd6a 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Frontend Knowledge Structure - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) - 代码质量 - Coding style - - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) + - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs) - [CSSLint](http://csslint.net/) - [Markup Validation Service](http://validator.w3.org/) - 单元测试 From 4ead4ab457c09e2f7082d7e22f5f5afadc293dc8 Mon Sep 17 00:00:00 2001 From: Kaijun Chen Date: Wed, 9 Apr 2014 18:56:37 +0200 Subject: [PATCH 043/107] add Front-end Developer Interview Questions --- README.en.md | 3 +++ README.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/README.en.md b/README.en.md index 5096395..f45b8d6 100644 --- a/README.en.md +++ b/README.en.md @@ -218,6 +218,9 @@ The ★ less and easier, the more suitable for starters - [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) - [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) +## Front-end Developer Interview +- [Front-end Developer Interview Questions](https://github.com/darcyclarke/Front-end-Developer-Interview-Questions) + ## Contributors Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2014/01/03. diff --git a/README.md b/README.md index 21ea83f..f375790 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,9 @@ Frontend Knowledge Structure - [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) - [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) +## 前端工作面试 +- [前端工作面试问题](https://github.com/darcyclarke/Front-end-Developer-Interview-Questions) + ## 内容贡献者 除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2014-01-03: From f82908faa137bac6c5a6f86ebde661818c7dfae8 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 19:02:16 +0800 Subject: [PATCH 044/107] Minor fixes. --- .gitignore | 1 + README.en.md | 6 ++++-- README.md | 6 ++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 1c25560..cc5864d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ parallel.html +*~ diff --git a/README.en.md b/README.en.md index 5096395..4599c5a 100644 --- a/README.en.md +++ b/README.en.md @@ -14,8 +14,10 @@ Although the project would be maintained in plain text instead, I promise a smal - Web browsers - IE6/[7](http://www.microsoft.com/en-US/download/details.aspx?id=2)/[8](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/en-US/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/en-US/internet-explorer/ie-11-worldwide-languages) - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) - - Languages + - [Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) + - [Safari](http://www.apple.com/safari/) + - [Opera](http://www.opera.com/) + - Programming Languages - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - [CoffeeScript](http://coffeescript.org/) - [TypeScript](http://www.typescriptlang.org/) diff --git a/README.md b/README.md index 21ea83f..1faaae5 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Frontend Knowledge Structure ![前端知识结构](https://raw.github.com/JacksonTian/fks/master/figures/fks.jpg) -图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个github项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 +图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个GitHub项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 尽管会变成文字的方式来维护这些内容,但是我承诺写一个小工具帮大家生成更好玩的图形(基于DataV项目)。 @@ -14,7 +14,9 @@ Frontend Knowledge Structure - 浏览器 - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-CN/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/zh-CN/internet-explorer/ie-11-worldwide-languages) - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Safari](http://www.apple.com/safari/)/[Opera](http://www.opera.com/) + - [Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) + - [Safari](http://www.apple.com/safari/) + - [Opera](http://www.opera.com/) - 编程语言 - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - [CoffeeScript](http://coffeescript.org/) From 235602842866c7b8311676cd259fb1eb69477401 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 19:04:43 +0800 Subject: [PATCH 045/107] Add GIMP. --- README.en.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index 4599c5a..a1b849e 100644 --- a/README.en.md +++ b/README.en.md @@ -24,7 +24,7 @@ Although the project would be maintained in plain text instead, I promise a smal - Slicing - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS](http://www.w3.org/Style/CSS/)/CSS3 - - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) + - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/) - Development tools - IDE - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) diff --git a/README.md b/README.md index 1faaae5..bf246c4 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Frontend Knowledge Structure - 切页面 - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS/CSS3](http://www.w3.org/Style/CSS/) - - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html) + - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/) - 开发工具 - IDE - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) From b9ed0ada57a1c392c9074ec5bff9fc36175ff76d Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 19:12:04 +0800 Subject: [PATCH 046/107] Add some editors and IDEs. --- README.en.md | 6 +++++- README.md | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README.en.md b/README.en.md index a1b849e..737fab2 100644 --- a/README.en.md +++ b/README.en.md @@ -26,12 +26,16 @@ Although the project would be maintained in plain text instead, I promise a smal - [CSS](http://www.w3.org/Style/CSS/)/CSS3 - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/) - Development tools - - IDE + - Editors and IDEs - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - [Brackets](http://brackets.io) + - [Komodo IDE / Edit](http://www.activestate.com/komodo-edit) + - [Eclipse](http://www.eclipse.org/) + - [Visual Studio](http://www.visualstudio.com/) + - [NetBeans](https://netbeans.org/) - Debugging - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) diff --git a/README.md b/README.md index bf246c4..d11ed11 100644 --- a/README.md +++ b/README.md @@ -26,12 +26,16 @@ Frontend Knowledge Structure - [CSS/CSS3](http://www.w3.org/Style/CSS/) - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/) - 开发工具 - - IDE + - 编辑器和IDE - [VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/) - [Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/) - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - [Brackets](http://brackets.io) + - [Komodo IDE / Edit](http://www.activestate.com/komodo-edit) + - [Eclipse](http://www.eclipse.org/) + - [Visual Studio](http://www.visualstudio.com/) + - [NetBeans](https://netbeans.org/) - 调试工具 - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) From 7247a8b43990e1a069aeeec002535dbafe5d0dc5 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 19:16:12 +0800 Subject: [PATCH 047/107] Add some debugging tools. --- README.en.md | 3 +++ README.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/README.en.md b/README.en.md index 737fab2..47e04ef 100644 --- a/README.en.md +++ b/README.en.md @@ -42,6 +42,9 @@ Although the project would be maintained in plain text instead, I promise a smal - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) - [Fiddler](http://www.fiddler2.com/fiddler2/) - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) + - [Dragonfly](http://www.opera.com/dragonfly/) + - [DebugBar](http://www.debugbar.com/) + - [Venkman](https://developer.mozilla.org/en-US/docs/Venkman) - Source Version Control - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) diff --git a/README.md b/README.md index d11ed11..6913be6 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,9 @@ Frontend Knowledge Structure - [IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage) - [Fiddler](http://www.fiddler2.com/fiddler2/) - [Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/) + - [Dragonfly](http://www.opera.com/dragonfly/) + - [DebugBar](http://www.debugbar.com/) + - [Venkman](https://developer.mozilla.org/en-US/docs/Venkman) - 版本管理 - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) From b0ee04f4f4477cf4be03dfe737ee8e05a9af7a80 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 19:20:55 +0800 Subject: [PATCH 048/107] Add some tools/websites about VCS/SCM. --- README.en.md | 6 +++--- README.md | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.en.md b/README.en.md index 47e04ef..f0c2851 100644 --- a/README.en.md +++ b/README.en.md @@ -45,9 +45,9 @@ Although the project would be maintained in plain text instead, I promise a smal - [Dragonfly](http://www.opera.com/dragonfly/) - [DebugBar](http://www.debugbar.com/) - [Venkman](https://developer.mozilla.org/en-US/docs/Venkman) - - Source Version Control - - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) + - Revision Control + - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/)/[Mercurial](http://mercurial.selenic.com/) + - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/) - Code quality - Coding style - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) diff --git a/README.md b/README.md index 6913be6..f868ac6 100644 --- a/README.md +++ b/README.md @@ -46,8 +46,8 @@ Frontend Knowledge Structure - [DebugBar](http://www.debugbar.com/) - [Venkman](https://developer.mozilla.org/en-US/docs/Venkman) - 版本管理 - - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/) + - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/)/[Mercurial](http://mercurial.selenic.com/) + - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/) - 代码质量 - Coding style - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/) From 121d3f2bfd45ce90a7fd32cc572a3b2a488b332c Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 19:35:40 +0800 Subject: [PATCH 049/107] Trivial fixes. --- README.en.md | 21 +++++++++++---------- README.md | 15 ++++++++------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/README.en.md b/README.en.md index f0c2851..29b26fb 100644 --- a/README.en.md +++ b/README.en.md @@ -80,12 +80,12 @@ Although the project would be maintained in plain text instead, I promise a smal - [HTTPWatch](http://www.httpwatch.com/) - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - [High-performance JavaScript](http://book.douban.com/subject/5362856/) - - Knownledge base - - Data structure + - General programming knowledge + - [Data structure](http://en.wikipedia.org/wiki/Data_structure) - OOP/AOP - [Prototype chain](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/Scope chain - [Closure](http://www.jibbering.com/faq/notes/closures/) - - Functional Programming + - [Programming paradigms](http://en.wikipedia.org/wiki/Programming_paradigm) - [Design Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) - Deployment flow @@ -120,7 +120,7 @@ Although the project would be maintained in plain text instead, I promise a smal - ADsafe/Caja/Sandbox - Mobile Web - HTML5/CSS3 - - Responsive + - [Responsive web design](http://en.wikipedia.org/wiki/Responsive_web_design) - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) - V5/[Sencha Touch](http://www.sencha.com/products/touch) - [PhoneGap](http://phonegap.com/) @@ -134,10 +134,10 @@ Although the project would be maintained in plain text instead, I promise a smal - [CSSConf](http://cssconf.com/) - YDN/YUIConf - HybridApp - - Computer knowledge + - Computer science - Compilation principle - - Network - - OS + - [Computer network](http://en.wikipedia.org/wiki/Computer_network) + - [OS](http://en.wikipedia.org/wiki/Operating_system) - Algorithm principle - Software Engineering/Software testing principle - Soft skills @@ -150,14 +150,15 @@ Although the project would be maintained in plain text instead, I promise a smal - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) - Backend Engineer - - Languages + - Programming languages - C/C++/Java/PHP/Ruby/Python/... - - Server + - Web server - [Nginx](http://nginx.org/en/) - [Apache](http://httpd.apache.org/) + - [Lighttpd](http://www.lighttpd.net/) - Databases - SQL - - MySQL/PostgreSQL/Oracle + - [MySQL](http://www.mysql.com/)/[PostgreSQL](http://www.postgresql.org/)/[Oracle](http://www.oracle.com/us/products/database/overview/index.html) - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - Data Caching - [Redis](http://redis.io/) diff --git a/README.md b/README.md index f868ac6..9569ca7 100644 --- a/README.md +++ b/README.md @@ -81,11 +81,11 @@ Frontend Knowledge Structure - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - [高性能JavaScript](http://book.douban.com/subject/5362856/) - 编程知识储备 - - 数据结构 + - [数据结构](http://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84) - OOP/AOP - [原型链](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/作用域链 - [闭包](http://www.jibbering.com/faq/notes/closures/) - - 函数式编程 + - [编程范型](http://zh.wikipedia.org/wiki/%E7%BC%96%E7%A8%8B%E8%8C%83%E5%9E%8B) - [设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/) - [Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html) - 部署流程 @@ -120,7 +120,7 @@ Frontend Knowledge Structure - ADsafe/Caja/Sandbox - 移动Web - HTML5/CSS3 - - 响应式设计 + - [响应式网页设计](http://zh.wikipedia.org/wiki/%E5%93%8D%E5%BA%94%E5%BC%8F%E7%BD%91%E9%A1%B5%E8%AE%BE%E8%AE%A1) - [Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll) - V5/[Sencha Touch](http://www.sencha.com/products/touch) - [PhoneGap](http://phonegap.com/) @@ -136,8 +136,8 @@ Frontend Knowledge Structure - HybridApp - 计算机知识储备 - 编译原理 - - 计算机网络 - - 操作系统 + - [计算机网络](http://zh.wikipedia.org/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C) + - [操作系统](http://zh.wikipedia.org/wiki/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F) - 算法原理 - 软件工程/软件测试原理 - 软技能 @@ -152,12 +152,13 @@ Frontend Knowledge Structure - 后端工程师 - 编程语言 - C/C++/Java/PHP/Ruby/Python/... - - 服务器 + - 网页服务器 - [Nginx](http://nginx.org/en/) - [Apache](http://httpd.apache.org/) + - [Lighttpd](http://www.lighttpd.net/) - 数据库 - SQL - - MySQL/PostgreSQL/Oracle + - [MySQL](http://www.mysql.com/)/[PostgreSQL](http://www.postgresql.org/)/[Oracle](http://www.oracle.com/us/products/database/overview/index.html) - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - 数据缓存 - [Redis](http://redis.io/) From ec1ebb27381e574f9dd17ebb34150b50460ed6a1 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 19:50:19 +0800 Subject: [PATCH 050/107] Add some books. --- README.en.md | 15 ++++++++++++--- README.md | 6 ++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/README.en.md b/README.en.md index 29b26fb..362eb10 100644 --- a/README.en.md +++ b/README.en.md @@ -198,23 +198,27 @@ The ★ less and easier, the more suitable for starters - [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ ## Book Recommendations for Backend-ers -### Linux management +### Linux administration - [Linux 系统管理技术手册](http://book.douban.com/subject/3042029/) - [鸟哥的 Linux 私房菜](http://book.douban.com/subject/4889838/) - [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) - [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) -- [The Linux Command Line](http://book.douban.com/subject/6806862/) +- [The Linux Command Line](http://linuxcommand.org/tlcl.php) +- [Linux Network Administrator's Guide](http://oreilly.com/openbook/linag2/book/index.html) ### Linux programming - [Linux程序设计](http://book.douban.com/subject/4831448/) - [Linux系统编程](http://book.douban.com/subject/3907181/) - [Unix环境高级编程](http://book.douban.com/subject/1788421/) -- [Unix编程艺术](http://book.douban.com/subject/1467587/) +- [The Art of UNIX Programming](http://www.catb.org/esr/writings/taoup/) - [The Linux Programming Interface](http://book.douban.com/subject/4292217/) - [程序员的自我修养](http://book.douban.com/subject/3652388/) - [深入理解Linux内核](http://book.douban.com/subject/2287506/) - [Unix网络编程](http://book.douban.com/subject/1500149/) - [TCP/IP高级编程](http://book.douban.com/subject/1088054/) +- [Linux Kernel in a Nutshell](http://www.kroah.com/lkn/) +- [Linux Device Drivers](http://lwn.net/Kernel/LDD3/) +- [Advanced Linux Programming](http://www.advancedlinuxprogramming.com/) ### C/C++ - [Linux C编程一站式学习](http://book.douban.com/subject/4141733/) @@ -227,6 +231,11 @@ The ★ less and easier, the more suitable for starters - [C++编程思想](http://book.douban.com/subject/1094797/) - [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) - [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) +- [A Tour of C++](http://www.stroustrup.com/Tour.html) +- [The C++ Programming Language](http://en.wikipedia.org/wiki/The_C%2B%2B_Programming_Language) +- [The C++ Standard Library - A Tutorial and Reference](http://www.cppstdlib.com/) +- [The C++ Standard (INCITS/ISO/IEC 14882-2011)](http://webstore.ansi.org/RecordDetail.aspx?sku=INCITS%2fISO%2fIEC+14882-2012) +- [Overview of the New C++](http://www.artima.com/shop/overview_of_the_new_cpp) ## Contributors Thanks to Jayli who provided the original graph and contributors below. Generated by `git-summary` at 2014/01/03. diff --git a/README.md b/README.md index 9569ca7..37dac67 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,7 @@ Frontend Knowledge Structure - [Linux 101 Hacks](http://www.thegeekstuff.com/linux-101-hacks-free-ebook-non-english/) - [UNIX Shell Scripting](http://book.douban.com/subject/3519360/) - [The Linux Command Line](http://book.douban.com/subject/6806862/) +- [Linux Network Administrator's Guide](http://oreilly.com/openbook/linag2/book/index.html) ### Linux编程 - [Linux程序设计](http://book.douban.com/subject/4831448/) @@ -227,6 +228,11 @@ Frontend Knowledge Structure - [C++编程思想](http://book.douban.com/subject/1094797/) - [高质量程序设计指南---C/C++语言](http://book.douban.com/subject/2116929/) - [Inside the C++ Object Model](http://book.douban.com/subject/1484262/) +- [A Tour of C++](http://www.stroustrup.com/Tour.html) +- [The C++ Programming Language](http://en.wikipedia.org/wiki/The_C%2B%2B_Programming_Language) +- [The C++ Standard Library - A Tutorial and Reference](http://www.cppstdlib.com/) +- [The C++ Standard (INCITS/ISO/IEC 14882-2011)](http://webstore.ansi.org/RecordDetail.aspx?sku=INCITS%2fISO%2fIEC+14882-2012) +- [Overview of the New C++](http://www.artima.com/shop/overview_of_the_new_cpp) ## 内容贡献者 除了感谢Jayli提供了知识结构图的原本来,还感谢以下的内容贡献者们,结果由`git-summary`生成于2014-01-03: From 43b472d678d4b8c79e6e29fa345e2da8e1f2cfa8 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Fri, 11 Apr 2014 20:18:20 +0800 Subject: [PATCH 051/107] Some minor addition. --- README.en.md | 16 +++++++++++----- README.md | 16 +++++++++++----- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/README.en.md b/README.en.md index 362eb10..12dcc2e 100644 --- a/README.en.md +++ b/README.en.md @@ -12,15 +12,16 @@ Although the project would be maintained in plain text instead, I promise a smal ## Knowledge Structure of Frontend Development - Frontend Engineer - Web browsers - - IE6/[7](http://www.microsoft.com/en-US/download/details.aspx?id=2)/[8](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/en-US/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/en-US/internet-explorer/ie-11-worldwide-languages) - - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) - - [Safari](http://www.apple.com/safari/) - - [Opera](http://www.opera.com/) + - IE6/[7](http://www.microsoft.com/en-US/download/details.aspx?id=2)/[8](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/en-US/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/en-US/internet-explorer/ie-11-worldwide-languages) (Trident) + - [Firefox](http://www.mozilla.org/en-US/) (Gecko) + - [Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) (Blink) + - [Safari](http://www.apple.com/safari/) (WebKit) + - [Opera](http://www.opera.com/) (Blink) - Programming Languages - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - [CoffeeScript](http://coffeescript.org/) - [TypeScript](http://www.typescriptlang.org/) + - [Dart](https://www.dartlang.org/) - Slicing - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS](http://www.w3.org/Style/CSS/)/CSS3 @@ -36,6 +37,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Eclipse](http://www.eclipse.org/) - [Visual Studio](http://www.visualstudio.com/) - [NetBeans](https://netbeans.org/) + - [Cloud9 IDE](http://c9.io/) - Debugging - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) @@ -56,6 +58,7 @@ Although the project would be maintained in plain text instead, I promise a smal - Unit testing - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) + - [Unit JS](http://unitjs.com/) - Auto-testing - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - [phantomjs](http://phantomjs.org/) @@ -67,6 +70,8 @@ Although the project would be maintained in plain text instead, I promise a smal - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) - [Semantic UI](http://www.semantic-ui.com/) + - [ASP.NET Ajax](http://www.asp.net/ajax) + - [Web Atoms](http://webatomsjs.neurospeech.com/) - Frontend standards / specifications - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) @@ -134,6 +139,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [CSSConf](http://cssconf.com/) - YDN/YUIConf - HybridApp + - [WHATWG](http://whatwg.org/) - Computer science - Compilation principle - [Computer network](http://en.wikipedia.org/wiki/Computer_network) diff --git a/README.md b/README.md index 37dac67..bb38fa3 100644 --- a/README.md +++ b/README.md @@ -12,15 +12,16 @@ Frontend Knowledge Structure ## 前端开发知识结构 - 前端工程师 - 浏览器 - - IE6/[7](http://www.microsoft.com/zh-cn/download/details.aspx?id=2)/[8](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/zh-CN/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/zh-CN/internet-explorer/ie-11-worldwide-languages) - - [Firefox](http://www.mozilla.org/en-US/) - - [Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) - - [Safari](http://www.apple.com/safari/) - - [Opera](http://www.opera.com/) + - IE6/[7](http://www.microsoft.com/en-US/download/details.aspx?id=2)/[8](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/en-US/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/en-US/internet-explorer/ie-11-worldwide-languages) (Trident) + - [Firefox](http://www.mozilla.org/en-US/) (Gecko) + - [Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) (Blink) + - [Safari](http://www.apple.com/safari/) (WebKit) + - [Opera](http://www.opera.com/) (Blink) - 编程语言 - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - [CoffeeScript](http://coffeescript.org/) - [TypeScript](http://www.typescriptlang.org/) + - [Dart](https://www.dartlang.org/) - 切页面 - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS/CSS3](http://www.w3.org/Style/CSS/) @@ -36,6 +37,7 @@ Frontend Knowledge Structure - [Eclipse](http://www.eclipse.org/) - [Visual Studio](http://www.visualstudio.com/) - [NetBeans](https://netbeans.org/) + - [Cloud9 IDE](http://c9.io/) - 调试工具 - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) @@ -56,6 +58,7 @@ Frontend Knowledge Structure - 单元测试 - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) + - [Unit JS](http://unitjs.com/) - 自动化测试 - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - [phantomjs](http://phantomjs.org/) @@ -67,6 +70,8 @@ Frontend Knowledge Structure - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) - [Semantic UI](http://www.semantic-ui.com/) + - [ASP.NET Ajax](http://www.asp.net/ajax) + - [Web Atoms](http://webatomsjs.neurospeech.com/) - 前端标准/规范 - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) @@ -134,6 +139,7 @@ Frontend Knowledge Structure - [CSSConf](http://cssconf.com/) - YDN/YUIConf - HybridApp + - [WHATWG](http://whatwg.org/) - 计算机知识储备 - 编译原理 - [计算机网络](http://zh.wikipedia.org/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C) From 12f1e21a55cf8f1b81883082e06a61dd160f0450 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Tue, 15 Apr 2014 16:20:59 +0800 Subject: [PATCH 052/107] More fixes. --- README.en.md | 3 +-- README.md | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/README.en.md b/README.en.md index 12dcc2e..6f76736 100644 --- a/README.en.md +++ b/README.en.md @@ -21,7 +21,6 @@ Although the project would be maintained in plain text instead, I promise a smal - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - [CoffeeScript](http://coffeescript.org/) - [TypeScript](http://www.typescriptlang.org/) - - [Dart](https://www.dartlang.org/) - Slicing - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS](http://www.w3.org/Style/CSS/)/CSS3 @@ -70,7 +69,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) - [Semantic UI](http://www.semantic-ui.com/) - - [ASP.NET Ajax](http://www.asp.net/ajax) + - [Juice UI](http://juiceui.com/) - [Web Atoms](http://webatomsjs.neurospeech.com/) - Frontend standards / specifications - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) diff --git a/README.md b/README.md index bb38fa3..2d399c9 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,6 @@ Frontend Knowledge Structure - [JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/) - [CoffeeScript](http://coffeescript.org/) - [TypeScript](http://www.typescriptlang.org/) - - [Dart](https://www.dartlang.org/) - 切页面 - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS/CSS3](http://www.w3.org/Style/CSS/) @@ -70,7 +69,7 @@ Frontend Knowledge Structure - [Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk) - [Bootstrap](http://getbootstrap.com/) - [Semantic UI](http://www.semantic-ui.com/) - - [ASP.NET Ajax](http://www.asp.net/ajax) + - [Juice UI](http://juiceui.com/) - [Web Atoms](http://webatomsjs.neurospeech.com/) - 前端标准/规范 - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) From 8ea36dc2c84034fe510a682608ccd6fecb50ea45 Mon Sep 17 00:00:00 2001 From: "Z.Mofei" <13761509829@163.com> Date: Fri, 20 Jun 2014 10:04:47 +0800 Subject: [PATCH 053/107] Update README.md change the JSDoc's url --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4556668..a4df9a1 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Frontend Knowledge Structure - [UglifyJS](https://github.com/mishoo/UglifyJS) - [CleanCSS](https://github.com/GoalSmashers/clean-css) - 文档输出 - - [JSDoc](http://code.google.com/p/jsdoc-toolkit/) + - [JSDoc](https://github.com/jsdoc3/jsdoc) - [Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate)/[Grunt-Doxmate](https://github.com/luozhihua/grunt-doxmate) - 项目构建工具 - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) From 53cc4d64b423432257b03840468a71d752dcfa9b Mon Sep 17 00:00:00 2001 From: "feichang.wyl" Date: Tue, 22 Jul 2014 10:46:52 +0800 Subject: [PATCH 054/107] add books for performance --- README.en.md | 4 ++++ README.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/README.en.md b/README.en.md index beea26d..f115cbb 100644 --- a/README.en.md +++ b/README.en.md @@ -198,6 +198,10 @@ The ★ less and easier, the more suitable for starters - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X)★★★★ +### 性能实践 +- [Web性能实践日志](http://book.douban.com/subject/25891125/)★★★ +- [Web性能权威指南](http://book.douban.com/subject/25856314/)★★★ + ### CVS - [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ - [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ diff --git a/README.md b/README.md index a4df9a1..c92214f 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,10 @@ Frontend Knowledge Structure - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - [基于MVC的JavaScript Web富应用开发](http://book.douban.com/subject/10733304/)★★★ +### 性能实践 +- [Web性能实践日志](http://book.douban.com/subject/25891125/)★★★ +- [Web性能权威指南](http://book.douban.com/subject/25856314/)★★★ + ### 版本控制工具 - [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ - [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ From 33e504ddeaa7f78d882f03efc79a5e25dd0b965b Mon Sep 17 00:00:00 2001 From: Tony77 <31647753@qq.com> Date: Thu, 21 Aug 2014 21:29:39 +0800 Subject: [PATCH 055/107] add WebGL --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c92214f..a7f0785 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ Frontend Knowledge Structure - SVG/Canvas/VML - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) + - WebGL(http://zh.wikipedia.org/wiki/WebGL):[Three.JS](http://threejs.org/) - 后端工程师 - 编程语言 - C/C++/Java/PHP/Ruby/Python/... From db6a5dfd24e5499a4765e64e009043c53af6c913 Mon Sep 17 00:00:00 2001 From: Tony77 <31647753@qq.com> Date: Thu, 21 Aug 2014 21:32:16 +0800 Subject: [PATCH 056/107] add WebGL --- README.en.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.en.md b/README.en.md index f115cbb..eed69ff 100644 --- a/README.en.md +++ b/README.en.md @@ -154,6 +154,7 @@ Although the project would be maintained in plain text instead, I promise a smal - SVG/Canvas/VML - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) + - WebGL(http://zh.wikipedia.org/wiki/WebGL):[Three.JS](http://threejs.org/) - Backend Engineer - Programming languages - C/C++/Java/PHP/Ruby/Python/... From 0beb924f06550006a3710b034eb4425a917c32be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9A=AE=E9=9B=A8?= <490769750@qq.com> Date: Thu, 9 Oct 2014 00:47:56 +0800 Subject: [PATCH 057/107] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a7f0785..ec67542 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ Frontend Knowledge Structure - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - [GYP](http://code.google.com/p/gyp/) - [Grunt](http://gruntjs.com/) + - [Gulp](http://gulpjs.com/) - [Yeoman](http://yeoman.io/) - [FIS](http://fis.baidu.com/) - [Mod](https://github.com/modulejs/modjs) From 06cbae034b5f389c13c6190c9ab6636fb62b3ac7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9A=AE=E9=9B=A8?= <490769750@qq.com> Date: Thu, 9 Oct 2014 00:48:42 +0800 Subject: [PATCH 058/107] Update README.en.md --- README.en.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.en.md b/README.en.md index eed69ff..2e6595c 100644 --- a/README.en.md +++ b/README.en.md @@ -105,6 +105,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/) - [GYP](http://code.google.com/p/gyp/) - [Grunt](http://gruntjs.com/) + - [Gulp](http://gulpjs.com/) - [Yeoman](http://yeoman.io/) - [FIS](http://fis.baidu.com/) - [Mod](https://github.com/modulejs/modjs) From 7fab57fce29e36ac3657656a3154c2a92148e526 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=8D=93=E6=81=BA?= Date: Sat, 11 Oct 2014 20:16:56 +0800 Subject: [PATCH 059/107] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=AF=AD=E4=B9=89?= =?UTF-8?q?=E7=BD=91=E3=80=81=E5=8F=AF=E7=94=A8=E6=80=A7=E4=B8=8ESEO?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index ec67542..be0f7a4 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,12 @@ Frontend Knowledge Structure - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) + - [Semantic Web](http://semanticweb.org/) + - [MicroData](http://schema.org) + - [RDFa](http://www.w3.org/TR/rdfa-core/) + - [Web Accessibility](http://www.w3.org/TR/WAI-WEBCONTENT/) + - [Role Attribute](http://www.w3.org/TR/role-attribute/) + - [WAI-ARIA](http://www.w3.org/TR/wai-aria/) - 性能 - [JSPerf](http://jsperf.com/) - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) @@ -84,6 +90,7 @@ Frontend Knowledge Structure - [HTTPWatch](http://www.httpwatch.com/) - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - [高性能JavaScript](http://book.douban.com/subject/5362856/) + - SEO - 编程知识储备 - [数据结构](http://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84) - OOP/AOP From ecd33f15116f5f3a10cad4ee7e22c45e6af844cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=8D=93=E6=81=BA?= Date: Sat, 11 Oct 2014 20:19:33 +0800 Subject: [PATCH 060/107] Add 'Semantic Web' , 'Web Accessibility' and 'SEO' --- README.en.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.en.md b/README.en.md index 2e6595c..e54132d 100644 --- a/README.en.md +++ b/README.en.md @@ -77,6 +77,12 @@ Although the project would be maintained in plain text instead, I promise a smal - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) + - [Semantic Web](http://semanticweb.org/) + - [MicroData](http://schema.org) + - [RDFa](http://www.w3.org/TR/rdfa-core/) + - [Web Accessibility](http://www.w3.org/TR/WAI-WEBCONTENT/) + - [Role Attribute](http://www.w3.org/TR/role-attribute/) + - [WAI-ARIA](http://www.w3.org/TR/wai-aria/) - Performance - [JSPerf](http://jsperf.com/) - [YSlow 35 rules](http://developer.yahoo.com/performance/rules.html) @@ -84,6 +90,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [HTTPWatch](http://www.httpwatch.com/) - [DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html) - [High-performance JavaScript](http://book.douban.com/subject/5362856/) + - SEO - General programming knowledge - [Data structure](http://en.wikipedia.org/wiki/Data_structure) - OOP/AOP From 43f1a6ee420c3bd2d044f2195cacf08e987e167a Mon Sep 17 00:00:00 2001 From: PaladinTyrion Date: Sun, 19 Oct 2014 02:50:07 +0800 Subject: [PATCH 061/107] add Pro Git to vcs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pro git这本书很好啊,基本常用的工作命令、工作方式,都提到了,而且也把git的设计模式大体勾勒了一下,选择更快上手git的话觉得pro git很不错。 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index be0f7a4..025b592 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,7 @@ Frontend Knowledge Structure ### 版本控制工具 - [版本控制之道 (git)](http://book.douban.com/subject/4813786/)★★ +- [Pro Git](http://iissnan.com/progit/)★★★ - [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ ## 后端书籍推荐 From c524b28e0478fe0c1728e70d28bd613936ca4483 Mon Sep 17 00:00:00 2001 From: PaladinTyrion Date: Mon, 20 Oct 2014 00:44:45 +0800 Subject: [PATCH 062/107] update VCS(Pro Git) && libraries/frameworks(polymer) --- README.en.md | 4 +++- README.md | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/README.en.md b/README.en.md index e54132d..6058e07 100644 --- a/README.en.md +++ b/README.en.md @@ -71,6 +71,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Semantic UI](http://www.semantic-ui.com/) - [Juice UI](http://juiceui.com/) - [Web Atoms](http://webatomsjs.neurospeech.com/) + - [Polymer](https://www.polymer-project.org/) - Frontend standards / specifications - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) @@ -207,12 +208,13 @@ The ★ less and easier, the more suitable for starters - [JavaScript设计模式](http://book.douban.com/subject/3329540/)★★★★ - [JavaScript Web Applications](http://www.amazon.com/JavaScript-Web-Applications-Alex-MacCaw/dp/144930351X)★★★★ -### 性能实践 +### Performance && Practice - [Web性能实践日志](http://book.douban.com/subject/25891125/)★★★ - [Web性能权威指南](http://book.douban.com/subject/25856314/)★★★ ### CVS - [Pragmatic Version Control Using Git](http://book.douban.com/subject/3105192/)★★ +- [Pro Git](http://git-scm.com/book)★★★ - [Git权威指南](http://book.douban.com/subject/6526452/)★★★★ ## Book Recommendations for Backend-ers diff --git a/README.md b/README.md index 025b592..9aec671 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ Frontend Knowledge Structure - [Semantic UI](http://www.semantic-ui.com/) - [Juice UI](http://juiceui.com/) - [Web Atoms](http://webatomsjs.neurospeech.com/) + - [Polymer](http://docs.polymerchina.org/) - 前端标准/规范 - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) From d2b9f0e9d0ca51bf7919889dea8d336368a1cd35 Mon Sep 17 00:00:00 2001 From: siberiawolf Date: Tue, 21 Oct 2014 10:15:15 +0800 Subject: [PATCH 063/107] =?UTF-8?q?=E6=B7=BB=E5=8A=A0JS=20=E5=8F=AF?= =?UTF-8?q?=E8=A7=86=E5=8C=96=E6=95=88=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend_knowledge/css/Hypertree.css | 3 + frontend_knowledge/css/base.css | 132 + frontend_knowledge/css/col1.png | Bin 0 -> 4217 bytes frontend_knowledge/css/col2.png | Bin 0 -> 4237 bytes frontend_knowledge/index.html | 53 + frontend_knowledge/js/jit.js | 17163 +++++++++++++++++++++++++ frontend_knowledge/js/script.js | 554 + 7 files changed, 17905 insertions(+) create mode 100644 frontend_knowledge/css/Hypertree.css create mode 100644 frontend_knowledge/css/base.css create mode 100644 frontend_knowledge/css/col1.png create mode 100644 frontend_knowledge/css/col2.png create mode 100644 frontend_knowledge/index.html create mode 100644 frontend_knowledge/js/jit.js create mode 100644 frontend_knowledge/js/script.js diff --git a/frontend_knowledge/css/Hypertree.css b/frontend_knowledge/css/Hypertree.css new file mode 100644 index 0000000..53ecca1 --- /dev/null +++ b/frontend_knowledge/css/Hypertree.css @@ -0,0 +1,3 @@ +#infovis-canvaswidget { + margin:25px 0 0 25px; +} \ No newline at end of file diff --git a/frontend_knowledge/css/base.css b/frontend_knowledge/css/base.css new file mode 100644 index 0000000..3e4cbd0 --- /dev/null +++ b/frontend_knowledge/css/base.css @@ -0,0 +1,132 @@ +html, body { + margin:0; + padding:0; + font-family: "Lucida Grande", Verdana; + font-size: 0.9em; + text-align: center; + background-color:#F2F2F2; +} + +input, select { + font-size:0.9em; +} + +table { + margin-top:-10px; + margin-left:7px; +} + +h4 { + font-size:1.1em; + text-decoration:none; + font-weight:normal; + color:#23A4FF; +} + +a { + color:#23A4FF; + text-decoration: none; +} + +#container { + width: 1000px; + height: 600px; + margin:0 auto; + position:relative; +} + +#left-container, +#right-container, +#center-container { + height:600px; + position:absolute; + top:0; +} + +#left-container, #right-container { + width:200px; + color:#686c70; + text-align: left; + overflow: auto; + background-color:#fff; + background-repeat:no-repeat; + border-bottom:1px solid #ddd; +} + +#left-container { + left:0; + background-image:url('https://github.com/col2.png'); + background-position:center right; + border-left:1px solid #ddd; + +} + +#right-container { + right:0; + background-image:url('https://github.com/col1.png'); + background-position:center left; + border-right:1px solid #ddd; +} + +#right-container h4{ + text-indent:8px; +} + +#center-container { + width:600px; + left:200px; + background-color:#1a1a1a; + color:#ccc; +} + +.text { + margin: 7px; +} + +#inner-details { + font-size:0.8em; + list-style:none; + margin:7px; +} + +#log { + position:absolute; + top:10px; + font-size:1.0em; + font-weight:bold; + color:#23A4FF; +} + + +#infovis { + position:relative; + width:600px; + height:600px; + margin:auto; + overflow:hidden; +} + +/*TOOLTIPS*/ +.tip { + color: #111; + width: 139px; + background-color: white; + border:1px solid #ccc; + -moz-box-shadow:#555 2px 2px 8px; + -webkit-box-shadow:#555 2px 2px 8px; + -o-box-shadow:#555 2px 2px 8px; + box-shadow:#555 2px 2px 8px; + opacity:0.9; + filter:alpha(opacity=90); + font-size:10px; + font-family:Verdana, Geneva, Arial, Helvetica, sans-serif; + padding:7px; +} + +#disqus_container{ + margin-top: 20px; +} +#disqus_container a{ + font-size: 22px; + color: red; +} \ No newline at end of file diff --git a/frontend_knowledge/css/col1.png b/frontend_knowledge/css/col1.png new file mode 100644 index 0000000000000000000000000000000000000000..7ab008fb23dc2592d232ad23341d7d5e53515b73 GIT binary patch literal 4217 zcmV-<5QguGP)LP3gCkm+V4lRf;|sN_|x}`OTe0}5caqpmHuS~Vm}1iuOG6n_l)TR z4@~0$hxsswY~w*F5q=TeTbT(${oBS@c{RVX0@LtEA^ZfMn9uul``>OKfCM(!-B)rk zbp)`or?f3)wqE?-n14&|AFRSk6{$ww$JpLP?Jdg|@&hE@<9drspEiQyY;6YsW*jJ7YB^ls?S=>*`F9d0!17!V4op&>-QARQUa$9 z!{^kCNON8q?kDVdI1HYjf_h!pAb+?0cIbILzX0{R3~c%P?6<>I-#5HL(c)+=OMXwW zJ)w6K;t6MhH5oJ{)v2^twQYfpDpy!4=LmaH!U@-FVe z@zB6M-mDc|If9$y@$KBukLyK2uKAP&fB&wn&sHMkr3;>}CjucJY4klX|4#cuvmy=w zEdt}_8PO-o{!pxkAt3;u_sKjlzXbC1^GK3NkUW_z*ko7!l!-CL1D?(SRuRZ2_FW?1 zG%h>qAVB`+TMCDYoZjuuN|nF-+$LC6^Yp=>_~zw{uRpt1!Ce?}LXf~GEW_O8w2kTy zwi#g=~$jQEdv^$ttdyp3FdpDj>2^@dp$LliY<7$`eclHzF0_-@lOOan1|6bVA z7^6>%#TWM9r&*dw4(F*8Kl}b;Z1^#@`rI1ZdRFkUl$Qt}8)%g;Ff380`6K%6d5XSZ z9$Jj)?%F;6aNz|8aDXE6i?j3hdpwHyS)aZ)b`8Kr8;^MN=~aC-ldtQon+FtB53twd zX#LU?J^%i@{V%@`x9!GOfc<NIW`MXr&$B;x|098dN;{I8g@wL~H*rz!yrt5bJx| zaZjMPy5N_;`E*as@2o*Lw^mIr@=I1L&$u3wu$2Xa@$xYd`K`kKllBR9V>gc~e#w3d zoW1%-hy5-m&ce=m^UX82dfR>VCqBjEn;zWt`@hIeLsjj~cWN78#uV^OH5L+Tm+ld400d$6CueA-Tj z_DoJbT!2J%$UhkNr{r%HbF`D6zbW^&!$G2Ky83Or^jeC=ok`Q{QHMLMXWy8-1R+DC zk8?Ho30X-Ko_^_?mLyVz+uEE0_~9<+jrYVPV<_qP6mJTE9Oq7{zwF6usqNhe)jTaz>utA zM*~y;iTU@n8+tU1GjUW(*9(F%UH^n5e|Xa0`Q^=<4oPv zgZ4i^Kk;moey!yio^mITv@18vF#Q-{Ny|z2D#8xKs9K^umZJHXdgRxbl7zg$_3#KVm`gQ+Y@!LtxjP zbZ$ne2$yDXjNCNt?|W|}GdF|IJ%^?@i}{BfN&~$ExUx6kyZ$w!!ZF_`yP-|Ck`J)> zOvycO+f(Nr`T2_UJ(r(P!6E6oPyzrfBlQJ3{#(>!Dbn{`O_nQ{-O%g&cWnNK z{k5C))E3xKdvG^xUvk{DVI02uo_tT&r2F0m^J7R);`yc7InvHf%Mb+#6BM2`StUz8 zVFfsNme!-WUdfN&d7?*P2W&K-_Me}hhvRUTEyc3^){p#r+ETIiaX{!r*m`>&{voMK z19gVEb~Q}XHbmdAvFG%ONsn1co7^WHz*OZm!GA5rvoRw-d34yjr1Q>w+-m*(9^{?m zzImvwliW*~j`@`P-IwEYws!t_bBkKW4w|2e82+J4avwL-&34wi z9L*g@cyQGfJAZ4Y8!P_gGB*kBUACpW4nQ2K?4ACxs1E~wi|f(3IF9s9uiu>Np{eU& zOh|ew((am6#|ym5Q#1$Li5Z3c(Dz#(?YOa4*4C?p)=mYyX69hKNjLWt^B?;D=jSK8 zr)++v%=>#qaxX;aU*tZfHyxE&W9UsBa}7i9tk6I0{O|AY_@~**tjoL9m=0?`s`DcE zlqpIDS;FHLSSRd!CUleJ>Xcx=l@-<%?Ii>LG|YEwC&g@g-O7zBEq++RyW5seXj~#Z zpx7+tyK=;y2KH;Xq4&6Kjesx8$bZrIOx?w)tGrpN2Q$!gf9U8 zg+~X+X4>>fxqRnzI+^z?SooaW^R?E(TSh_XFUmbt_WUnTQS<#Yy*WU+wnn7*1cX%nKOUC>k7mx^s2xzn?!<`;469e+r=&zjCaCoq5S zqs?GN;^5VzN^_jQ{KVelPlW)!J2S!bq3^%GzV-OxOyY(*7jE%&`LqMo?x*|& z?LO|xT>h84ksXp)srBU?0U+nJzNe`>ry@CWW+V@b-7=3G%zu}0Ixx8#JoyDmnAK2m zr#*0ev|Z0}2tAH+Wud?DXn*S6`ekCRkWnK}-#fOiPF$KJ_5|$}3Xa)B;J+?grn$IP zZw5TVDb8t6+Msg+w?A9c_OZw~0@{*C}J7quKl_NH*HOgA9=gQpI?%g}J)n+7|PnX!vR*YBj z<`&6V`J@&nNR&(^!U_%MGK3^x49{b7L5 zp3N+Clf!lu4w0u{KfCEKFVL`e1Fy<_58?ss)!6yT!|J=FgS4u56|x9l1NCizVM+tS zHKG26_DQS!gz#pj+Wc9(9nj`9Q_m zVXeWnA&ZB?OYbCPbT!%e-0h|L`B^@2NRqes3V{+hTZxS$v$ulq{f(KQwHn%|wjRG} z+|AgO`@NgUx<3IPVHQ3U$z4z6k0935otasJ^a`NB1YB!43%DZ+TZ3 zk0q*HCOJpg^L;VDhkdsK%@n;Or|+ASUquq1VZ;7}zDHrK?VWpm-_slFf$)9hKD*25 zpD_wAD z;}bym#{Ruyd+)qIFUQ8IDT>~lqrGFBXfKZW#$G%u{{Ab!b+PA43FsJ)z%W~w!TFT- zOwSeis;f;*GW@cEnsUH=M&d2K{)6^=OI=WUsTY6DNaHd8_WuImm$UUib>p{i*eSa9wSyt;?w)2@r8!KS`%FKOGi)sF7mIC>VoezOn1myFWpA`tJr-1x} zC++K-DH_K4HMzl;#@{vUqX&>zrtg7`E9!eQ5)a-zE%zY&Li(N_nf8MN;ZNB4iO_2| z`(eqS*7qoUTvy*~)bwb>ab52Bym*>RMI}~v;)emDEF6pErDIs(;jjU zxxYc6?fdsxkO#eOERQ1q?ca6Vuw3(5T=#dx4S7HI#f<{|oP`FM$5hninP z?m_0IF(2fIzQ+RXu|Rt)&>jo4#{%uKKzl6E9t*U`0`0Ltdn~EzKLG{+#U({)rgmPG P00000NkvXXu0mjf<`=N1 literal 0 HcmV?d00001 diff --git a/frontend_knowledge/css/col2.png b/frontend_knowledge/css/col2.png new file mode 100644 index 0000000000000000000000000000000000000000..c0d3891bac29b100167ac15ec50a615f1ae79d6f GIT binary patch literal 4237 zcmV;85OVK{P)Px#32;bRa{vGf6951U69E94oEQKA00(qQO+^RU1rHGt1$-PedH?_rA4x<(RCwC$ zUE6k}It(?A^Zy^*2F?RLL?d4y#1~24Jj}|ZEf`DMx>{PcZF9KvU)#1V%fdcyZd=^4 z|99KmvN*SGn{)e57tnrIW^nIxvd$=9L& zUM%qgXs?CF=0Rux?WuDqd4E3&r)cr@kI#ei_u2(Z?D~_$&Rt=08mr^N@`7UppEUP+ zV7~ll{6%<|v-0cu$dTHOF4h^){^2 zg=ar-oylx{{G$NETU{Qr{-~yJMf(}HRruQIaU3e{>$=ik3n0A7CDD@YBocgU>&e;5 zAuAEf=sA6_pk5EbfLhCoTQ619_i~)N@=*jio?E*uN~Ue%by6=sOd<;Ap`wiQ3<=hC zU6#e$-fkhGy$;Jbn*>>JCNKbG)A zbj^Y7*X__?Pw0meez;$k6#e7-`}KO0>}>zn{PKykg<7GbGX36bmvSg6dXrp{RujyJ z(2IIjPU5NefAeg{*g#&lT8vM_cHca=VsS@dG3*Hbw=rE*Xi3|LoMawIa6gwbgOz9L zDeQ5FI=IwV(^z7(`kkfOAFRze3-k)A z#C1E1X$J7+cU?G+UYs`8^}62B45YbhHG_b=y zcu1{{^%vSI2xWUgqq3hw z(_egI+&Ud{Z%v>t{>iTF6F%OM8p0Wry_^n*1uJ49RmGW_YFCn6*4)Cwsvtm(3U0#HpZwKu^HBdl%Q|=rs%yMTvR|32{ zrJ6n-cu5VqBUxAY+b~4gwenV4Z?qU=POONm=Pcd^A!R9K(xQ2F5^f}b~YlSIx2+zy84f+^H{~^dsb5CCe*IM z>6S)SP>tU1-mZRRgyzb$OEuc|y4J|AtFLnBoYrP-bX}oNcT^{>y0!F;e6}hubK7$} zy)AX|SsRYzQxMlP0&j7ghkib^K3xWAKUmpy#?d3Nb3%J`P}NTISc6kM@Q_FwFH)X^ zedP72SrCNmvWla)!q-Wi_?_5$I)^pWJ;)y<82RmD404LB8=3c4Zk5dVRi1;b5$y$b z%B%InFQ0?UjIvzPS>W9pZta*!SPej z-Ymed35oG9Bc^ML{JAc9Y+fd8JkV6H^&7?sn=;5u0d!-&$wc41mx>$g(2Ned^Phij zcxpnU(PAAe!5epD(^8U2Jk;$Nck}4k+nAFM(+_7eOsTE-_$@2mq92T(!Jf11C)rpx zF5r1Q9*}z@JbHQ)iUE6&zxS*pv0kz?PtScmy!mkPuQ1c!8SLC)j-EU|*3@^E0>A^U z{lZ){_9O2-=-inxmEl_uSAL@y{|APab&*z`M z?_Z|ZGn1=M?r)2J@+ejk)PH|}-*!ICJr$zw&T0s#o5u`2)<6H`r(3D-Sm{W1UE6(hU*=a4fCbz%Mx*dK`e zIZK{d^~o-K$8Q4j4Jwxy1CmG(dYX8E{dSwlq&!!-MY$m)`D^B6u0YuT$h#}wfvSdK zau3mOAxp{5$+?1#VRG*T2lmB^{>5i8N+%CyxUpw3g`aLzC;A0$OUga$e9M8LWMf^I z?4NJm+#3b^Ey#cUiMe?i9wMkzvai(P$IaBU`W`C3_44|c!ymO9C$=77|4V7^kNky4 z7cgIh+&c{|EA>i$(%pBt-ikuJd^w_D-RSFJ9K;1Y@sVs1azCNgcg-3r($DdEjFY|_ zIGWQ(Ogry$@`PR}|DIvkZ))_7vin%q9hYyo}6m z1Yo}ko3@+LL6v&0yBf6yvOeA@*a!000{;R79UK53PqdP{*d#L+_uRM)Y7>O(@1`2| zTOfZ2v;W@8+0pCVsk|^8)>Om36VsKHMek3KXf4Y!7v^iv#+Ew=Uku6Yobf(?FDJs& z6!t|Sf8A$Mp^xtw7w2Ev-8AG>++fB)&DJ(cL!9hNyt`jb!0k)H*3*L8h9 zpC@*{Rnd1!@<#Wfqz(Zs!%Gtn+^+`@Hk9`wvKgp`rcRB}y$9+~#uTVwK zBpCcdkl%GVH*#?qG??R3e@xs`DeSbl*r1hn7VXl8Z!v<&aT#kf} z)ni{gc?2`b5Z<254P43CO^B1WO>Dh+Z2sZz=sxMySztbTSjU2`*Gsmt|4!|OSZT1-7_5qy&m=xRpcxwRVE=vTEd8PY;FJldxV!&{==dR& zm@Vou)&QiBei!LB?XL&&OW=T9cz?P+TcX&pPn)iSF&L^pPl5$xwUE3nLxk46He@^c z+kIb(a_3Gk`;k09mJC4tq#;(3@X33=Uaux{FADu;$T5})KS1tL$s_sQ*L7_u_d*oE zM%`a=k;!o0wr#uIho<`u z??x0HB+Ir!f3X`#fEJCEg|)BT zNkq?1K;O1@8%qPm4Rbkq;aA=AKDG7OO9g?lE@#ID=H>1^o%Yr5ZR<@4vu<=4J8qxN zmL!7qDxlQ{{txi)A<9D7wEnrArp}2#4iF9-xwJidi=cvAf&VR*2mk)Q$E?MnS3rCD zd#Y}=ZqIEl%mtzX^U2$9<`zC0ARjVYt{pW?* zSYyuRbQ5&#Jn?01$mu*pW&ZuAdp9Tk-*{^a^?FwE|D%^Zt<$1ckKPNw|DG?KjN~M* z<~>&c0Mam@4blpe$i$p{kj>tD?P zJr6;jP17yQvg`XW=ljoq4duvgzn&{l0YjL+P_*Obsn18OH~v0gBMbvW!RVU^^Wg=s zcb~|=pHl@S+wC1AQgI${QXMy)zW>Mrw4@zk#Sgi!!yg*$n|by9ROF|%xv=x+@&a=G zbV2(&g071>lI<6u@8@z6Tg^b986MQZ0Q%`p#{?|F1KLl=1k>g5hTy6|n?PJ2ZFqx2 zY<|$btv4u{Q9%27tpU(}Fj@@c1JGWU*670u@b7151<+oZEm@HpK>K-pMbKWKuUO!o zj|Mt{_C{b}(w-}T0e7KuGH7oW9w7IChkt%lXw2l0$D8>A?dLTZf%#^2!Fk6e?38)w zpQWcNF6et)Z=ugx`!k)`_Jae?-@Kzm%EJuc857ifV-2a200000NkvXXu0mjfnc%hU literal 0 HcmV?d00001 diff --git a/frontend_knowledge/index.html b/frontend_knowledge/index.html new file mode 100644 index 0000000..3f98a57 --- /dev/null +++ b/frontend_knowledge/index.html @@ -0,0 +1,53 @@ + + + + +前端知识结构图 + + + + + + + + + + + + + +
+
+
+

+ 前端知识结构图 +

+ 这是一个前端知识结构图。

+ 点击一个节点,可以将这个节点移动到中央查看。

+ 此外中央节点的关系也可以从右侧的列表中查看。

+ +

+ 项目来源 +
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + + diff --git a/frontend_knowledge/js/jit.js b/frontend_knowledge/js/jit.js new file mode 100644 index 0000000..9bf6e9e --- /dev/null +++ b/frontend_knowledge/js/jit.js @@ -0,0 +1,17163 @@ +/* +Copyright (c) 2011 Sencha Inc. - Author: Nicolas Garcia Belmonte (http://philogb.github.com/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + */ + (function () { + +/* + File: Core.js + + */ + +/* + Object: $jit + + Defines the namespace for all library Classes and Objects. + This variable is the *only* global variable defined in the Toolkit. + There are also other interesting properties attached to this variable described below. + */ +window.$jit = function(w) { + w = w || window; + for(var k in $jit) { + if($jit[k].$extend) { + w[k] = $jit[k]; + } + } +}; + +$jit.version = '2.0.1'; +/* + Object: $jit.id + + Works just like *document.getElementById* + + Example: + (start code js) + var element = $jit.id('elementId'); + (end code) + +*/ + +/* + Object: $jit.util + + Contains utility functions. + + Some of the utility functions and the Class system were based in the MooTools Framework + . Copyright (c) 2006-2010 Valerio Proietti, . + MIT license . + + These methods are generally also implemented in DOM manipulation frameworks like JQuery, MooTools and Prototype. + I'd suggest you to use the functions from those libraries instead of using these, since their functions + are widely used and tested in many different platforms/browsers. Use these functions only if you have to. + + */ +var $ = function(d) { + return document.getElementById(d); +}; + +$.empty = function() { +}; + +/* + Method: extend + + Augment an object by appending another object's properties. + + Parameters: + + original - (object) The object to be extended. + extended - (object) An object which properties are going to be appended to the original object. + + Example: + (start code js) + $jit.util.extend({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 4 }); //{ 'a':1, 'b': 3, 'c': 4 } + (end code) +*/ +$.extend = function(original, extended) { + for ( var key in (extended || {})) + original[key] = extended[key]; + return original; +}; + +$.lambda = function(value) { + return (typeof value == 'function') ? value : function() { + return value; + }; +}; + +$.time = Date.now || function() { + return +new Date; +}; + +/* + Method: splat + + Returns an array wrapping *obj* if *obj* is not an array. Returns *obj* otherwise. + + Parameters: + + obj - (mixed) The object to be wrapped in an array. + + Example: + (start code js) + $jit.util.splat(3); //[3] + $jit.util.splat([3]); //[3] + (end code) +*/ +$.splat = function(obj) { + var type = $.type(obj); + return type ? ((type != 'array') ? [ obj ] : obj) : []; +}; + +$.type = function(elem) { + var type = $.type.s.call(elem).match(/^\[object\s(.*)\]$/)[1].toLowerCase(); + if(type != 'object') return type; + if(elem && elem.$$family) return elem.$$family; + return (elem && elem.nodeName && elem.nodeType == 1)? 'element' : type; +}; +$.type.s = Object.prototype.toString; + +/* + Method: each + + Iterates through an iterable applying *f*. + + Parameters: + + iterable - (array) The original array. + fn - (function) The function to apply to the array elements. + + Example: + (start code js) + $jit.util.each([3, 4, 5], function(n) { alert('number ' + n); }); + (end code) +*/ +$.each = function(iterable, fn) { + var type = $.type(iterable); + if (type == 'object') { + for ( var key in iterable) + fn(iterable[key], key); + } else { + for ( var i = 0, l = iterable.length; i < l; i++) + fn(iterable[i], i); + } +}; + +$.indexOf = function(array, item) { + if(Array.indexOf) return array.indexOf(item); + for(var i=0,l=array.length; i> 16, hex >> 8 & 0xff, hex & 0xff ]; + } +}; + +$.destroy = function(elem) { + $.clean(elem); + if (elem.parentNode) + elem.parentNode.removeChild(elem); + if (elem.clearAttributes) + elem.clearAttributes(); +}; + +$.clean = function(elem) { + for (var ch = elem.childNodes, i = 0, l = ch.length; i < l; i++) { + $.destroy(ch[i]); + } +}; + +/* + Method: addEvent + + Cross-browser add event listener. + + Parameters: + + obj - (obj) The Element to attach the listener to. + type - (string) The listener type. For example 'click', or 'mousemove'. + fn - (function) The callback function to be used when the event is fired. + + Example: + (start code js) + $jit.util.addEvent(elem, 'click', function(){ alert('hello'); }); + (end code) +*/ +$.addEvent = function(obj, type, fn) { + if (obj.addEventListener) + obj.addEventListener(type, fn, false); + else + obj.attachEvent('on' + type, fn); +}; + +$.addEvents = function(obj, typeObj) { + for(var type in typeObj) { + $.addEvent(obj, type, typeObj[type]); + } +}; + +$.hasClass = function(obj, klass) { + return (' ' + obj.className + ' ').indexOf(' ' + klass + ' ') > -1; +}; + +$.addClass = function(obj, klass) { + if (!$.hasClass(obj, klass)) + obj.className = (obj.className + " " + klass); +}; + +$.removeClass = function(obj, klass) { + obj.className = obj.className.replace(new RegExp( + '(^|\\s)' + klass + '(?:\\s|$)'), '$1'); +}; + +$.getPos = function(elem) { + var offset = getOffsets(elem); + var scroll = getScrolls(elem); + return { + x: offset.x - scroll.x, + y: offset.y - scroll.y + }; + + function getOffsets(elem) { + var position = { + x: 0, + y: 0 + }; + while (elem && !isBody(elem)) { + position.x += elem.offsetLeft; + position.y += elem.offsetTop; + elem = elem.offsetParent; + } + return position; + } + + function getScrolls(elem) { + var position = { + x: 0, + y: 0 + }; + while (elem && !isBody(elem)) { + position.x += elem.scrollLeft; + position.y += elem.scrollTop; + elem = elem.parentNode; + } + return position; + } + + function isBody(element) { + return (/^(?:body|html)$/i).test(element.tagName); + } +}; + +$.event = { + get: function(e, win) { + win = win || window; + return e || win.event; + }, + getWheel: function(e) { + return e.wheelDelta? e.wheelDelta / 120 : -(e.detail || 0) / 3; + }, + isRightClick: function(e) { + return (e.which == 3 || e.button == 2); + }, + getPos: function(e, win) { + // get mouse position + win = win || window; + e = e || win.event; + var doc = win.document; + doc = doc.documentElement || doc.body; + //TODO(nico): make touch event handling better + if(e.touches && e.touches.length) { + e = e.touches[0]; + } + var page = { + x: e.pageX || (e.clientX + doc.scrollLeft), + y: e.pageY || (e.clientY + doc.scrollTop) + }; + return page; + }, + stop: function(e) { + if (e.stopPropagation) e.stopPropagation(); + e.cancelBubble = true; + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + } +}; + +$jit.util = $jit.id = $; + +var Class = function(properties) { + properties = properties || {}; + var klass = function() { + for ( var key in this) { + if (typeof this[key] != 'function') + this[key] = $.unlink(this[key]); + } + this.constructor = klass; + if (Class.prototyping) + return this; + var instance = this.initialize ? this.initialize.apply(this, arguments) + : this; + //typize + this.$$family = 'class'; + return instance; + }; + + for ( var mutator in Class.Mutators) { + if (!properties[mutator]) + continue; + properties = Class.Mutators[mutator](properties, properties[mutator]); + delete properties[mutator]; + } + + $.extend(klass, this); + klass.constructor = Class; + klass.prototype = properties; + return klass; +}; + +Class.Mutators = { + + Implements: function(self, klasses) { + $.each($.splat(klasses), function(klass) { + Class.prototyping = klass; + var instance = (typeof klass == 'function') ? new klass : klass; + for ( var prop in instance) { + if (!(prop in self)) { + self[prop] = instance[prop]; + } + } + delete Class.prototyping; + }); + return self; + } + +}; + +$.extend(Class, { + + inherit: function(object, properties) { + for ( var key in properties) { + var override = properties[key]; + var previous = object[key]; + var type = $.type(override); + if (previous && type == 'function') { + if (override != previous) { + Class.override(object, key, override); + } + } else if (type == 'object') { + object[key] = $.merge(previous, override); + } else { + object[key] = override; + } + } + return object; + }, + + override: function(object, name, method) { + var parent = Class.prototyping; + if (parent && object[name] != parent[name]) + parent = null; + var override = function() { + var previous = this.parent; + this.parent = parent ? parent[name] : object[name]; + var value = method.apply(this, arguments); + this.parent = previous; + return value; + }; + object[name] = override; + } + +}); + +Class.prototype.implement = function() { + var proto = this.prototype; + $.each(Array.prototype.slice.call(arguments || []), function(properties) { + Class.inherit(proto, properties); + }); + return this; +}; + +$jit.Class = Class; + +/* + Object: $jit.json + + Provides JSON utility functions. + + Most of these functions are JSON-tree traversal and manipulation functions. +*/ +$jit.json = { + /* + Method: prune + + Clears all tree nodes having depth greater than maxLevel. + + Parameters: + + tree - (object) A JSON tree object. For more information please see . + maxLevel - (number) An integer specifying the maximum level allowed for this tree. All nodes having depth greater than max level will be deleted. + + */ + prune: function(tree, maxLevel) { + this.each(tree, function(elem, i) { + if (i == maxLevel && elem.children) { + delete elem.children; + elem.children = []; + } + }); + }, + /* + Method: getParent + + Returns the parent node of the node having _id_ as id. + + Parameters: + + tree - (object) A JSON tree object. See also . + id - (string) The _id_ of the child node whose parent will be returned. + + Returns: + + A tree JSON node if any, or false otherwise. + + */ + getParent: function(tree, id) { + if (tree.id == id) + return false; + var ch = tree.children; + if (ch && ch.length > 0) { + for ( var i = 0; i < ch.length; i++) { + if (ch[i].id == id) + return tree; + else { + var ans = this.getParent(ch[i], id); + if (ans) + return ans; + } + } + } + return false; + }, + /* + Method: getSubtree + + Returns the subtree that matches the given id. + + Parameters: + + tree - (object) A JSON tree object. See also . + id - (string) A node *unique* identifier. + + Returns: + + A subtree having a root node matching the given id. Returns null if no subtree matching the id is found. + + */ + getSubtree: function(tree, id) { + if (tree.id == id) + return tree; + for ( var i = 0, ch = tree.children; ch && i < ch.length; i++) { + var t = this.getSubtree(ch[i], id); + if (t != null) + return t; + } + return null; + }, + /* + Method: eachLevel + + Iterates on tree nodes with relative depth less or equal than a specified level. + + Parameters: + + tree - (object) A JSON tree or subtree. See also . + initLevel - (number) An integer specifying the initial relative level. Usually zero. + toLevel - (number) An integer specifying a top level. This method will iterate only through nodes with depth less than or equal this number. + action - (function) A function that receives a node and an integer specifying the actual level of the node. + + Example: + (start code js) + $jit.json.eachLevel(tree, 0, 3, function(node, depth) { + alert(node.name + ' ' + depth); + }); + (end code) + */ + eachLevel: function(tree, initLevel, toLevel, action) { + if (initLevel <= toLevel) { + action(tree, initLevel); + if(!tree.children) return; + for ( var i = 0, ch = tree.children; i < ch.length; i++) { + this.eachLevel(ch[i], initLevel + 1, toLevel, action); + } + } + }, + /* + Method: each + + A JSON tree iterator. + + Parameters: + + tree - (object) A JSON tree or subtree. See also . + action - (function) A function that receives a node. + + Example: + (start code js) + $jit.json.each(tree, function(node) { + alert(node.name); + }); + (end code) + + */ + each: function(tree, action) { + this.eachLevel(tree, 0, Number.MAX_VALUE, action); + } +}; + + +/* + An object containing multiple type of transformations. +*/ + +$jit.Trans = { + $extend: true, + + linear: function(p){ + return p; + } +}; + +var Trans = $jit.Trans; + +(function(){ + + var makeTrans = function(transition, params){ + params = $.splat(params); + return $.extend(transition, { + easeIn: function(pos){ + return transition(pos, params); + }, + easeOut: function(pos){ + return 1 - transition(1 - pos, params); + }, + easeInOut: function(pos){ + return (pos <= 0.5)? transition(2 * pos, params) / 2 : (2 - transition( + 2 * (1 - pos), params)) / 2; + } + }); + }; + + var transitions = { + + Pow: function(p, x){ + return Math.pow(p, x[0] || 6); + }, + + Expo: function(p){ + return Math.pow(2, 8 * (p - 1)); + }, + + Circ: function(p){ + return 1 - Math.sin(Math.acos(p)); + }, + + Sine: function(p){ + return 1 - Math.sin((1 - p) * Math.PI / 2); + }, + + Back: function(p, x){ + x = x[0] || 1.618; + return Math.pow(p, 2) * ((x + 1) * p - x); + }, + + Bounce: function(p){ + var value; + for ( var a = 0, b = 1; 1; a += b, b /= 2) { + if (p >= (7 - 4 * a) / 11) { + value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2); + break; + } + } + return value; + }, + + Elastic: function(p, x){ + return Math.pow(2, 10 * --p) + * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3); + } + + }; + + $.each(transitions, function(val, key){ + Trans[key] = makeTrans(val); + }); + + $.each( [ + 'Quad', 'Cubic', 'Quart', 'Quint' + ], function(elem, i){ + Trans[elem] = makeTrans(function(p){ + return Math.pow(p, [ + i + 2 + ]); + }); + }); + +})(); + +/* + A Class that can perform animations for generic objects. + + If you are looking for animation transitions please take a look at the object. + + Used by: + + + + Based on: + + The Animation class is based in the MooTools Framework . Copyright (c) 2006-2009 Valerio Proietti, . MIT license . + +*/ + +var Animation = new Class( { + + initialize: function(options){ + this.setOptions(options); + }, + + setOptions: function(options){ + var opt = { + duration: 2500, + fps: 40, + transition: Trans.Quart.easeInOut, + compute: $.empty, + complete: $.empty, + link: 'ignore' + }; + this.opt = $.merge(opt, options || {}); + return this; + }, + + step: function(){ + var time = $.time(), opt = this.opt; + if (time < this.time + opt.duration) { + var delta = opt.transition((time - this.time) / opt.duration); + opt.compute(delta); + } else { + this.timer = clearInterval(this.timer); + opt.compute(1); + opt.complete(); + } + }, + + start: function(){ + if (!this.check()) + return this; + this.time = 0; + this.startTimer(); + return this; + }, + + startTimer: function(){ + var that = this, fps = this.opt.fps; + if (this.timer) + return false; + this.time = $.time() - this.time; + this.timer = setInterval((function(){ + that.step(); + }), Math.round(1000 / fps)); + return true; + }, + + pause: function(){ + this.stopTimer(); + return this; + }, + + resume: function(){ + this.startTimer(); + return this; + }, + + stopTimer: function(){ + if (!this.timer) + return false; + this.time = $.time() - this.time; + this.timer = clearInterval(this.timer); + return true; + }, + + check: function(){ + if (!this.timer) + return true; + if (this.opt.link == 'cancel') { + this.stopTimer(); + return true; + } + return false; + } +}); + + +var Options = function() { + var args = arguments; + for(var i=0, l=args.length, ans={}; i options. + Other options included in the AreaChart are , , , and . + + Syntax: + + (start code js) + + Options.AreaChart = { + animate: true, + labelOffset: 3, + type: 'stacked', + selectOnHover: true, + showAggregates: true, + showLabels: true, + filterOnClick: false, + restoreOnRightClick: false + }; + + (end code) + + Example: + + (start code js) + + var areaChart = new $jit.AreaChart({ + animate: true, + type: 'stacked:gradient', + selectOnHover: true, + filterOnClick: true, + restoreOnRightClick: true + }); + + (end code) + + Parameters: + + animate - (boolean) Default's *true*. Whether to add animated transitions when filtering/restoring stacks. + labelOffset - (number) Default's *3*. Adds margin between the label and the default place where it should be drawn. + type - (string) Default's *'stacked'*. Stack style. Posible values are 'stacked', 'stacked:gradient' to add gradients. + selectOnHover - (boolean) Default's *true*. If true, it will add a mark to the hovered stack. + showAggregates - (boolean, function) Default's *true*. Display the values of the stacks. Can also be a function that returns *true* or *false* to display or filter some values. That same function can also return a string with the formatted value. + showLabels - (boolean, function) Default's *true*. Display the name of the slots. Can also be a function that returns *true* or *false* to display or not each label. + filterOnClick - (boolean) Default's *true*. Select the clicked stack by hiding all other stacks. + restoreOnRightClick - (boolean) Default's *true*. Show all stacks by right clicking. + +*/ + +Options.AreaChart = { + $extend: true, + + animate: true, + labelOffset: 3, // label offset + type: 'stacked', // gradient + Tips: { + enable: false, + onShow: $.empty, + onHide: $.empty + }, + Events: { + enable: false, + onClick: $.empty + }, + selectOnHover: true, + showAggregates: true, + showLabels: true, + filterOnClick: false, + restoreOnRightClick: false +}; + +/* + * File: Options.Margin.js + * +*/ + +/* + Object: Options.Margin + + Canvas drawing margins. + + Syntax: + + (start code js) + + Options.Margin = { + top: 0, + left: 0, + right: 0, + bottom: 0 + }; + + (end code) + + Example: + + (start code js) + + var viz = new $jit.Viz({ + Margin: { + right: 10, + bottom: 20 + } + }); + + (end code) + + Parameters: + + top - (number) Default's *0*. Top margin. + left - (number) Default's *0*. Left margin. + right - (number) Default's *0*. Right margin. + bottom - (number) Default's *0*. Bottom margin. + +*/ + +Options.Margin = { + $extend: false, + + top: 0, + left: 0, + right: 0, + bottom: 0 +}; + +/* + * File: Options.Canvas.js + * +*/ + +/* + Object: Options.Canvas + + These are Canvas general options, like where to append it in the DOM, its dimensions, background, + and other more advanced options. + + Syntax: + + (start code js) + + Options.Canvas = { + injectInto: 'id', + type: '2D', //'3D' + width: false, + height: false, + useCanvas: false, + withLabels: true, + background: false + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + injectInto: 'someContainerId', + width: 500, + height: 700 + }); + (end code) + + Parameters: + + injectInto - *required* (string|element) The id of the DOM container for the visualization. It can also be an Element provided that it has an id. + type - (string) Context type. Default's 2D but can be 3D for webGL enabled browsers. + width - (number) Default's to the *container's offsetWidth*. The width of the canvas. + height - (number) Default's to the *container's offsetHeight*. The height of the canvas. + useCanvas - (boolean|object) Default's *false*. You can pass another instance to be used by the visualization. + withLabels - (boolean) Default's *true*. Whether to use a label container for the visualization. + background - (boolean|object) Default's *false*. An object containing information about the rendering of a background canvas. +*/ + +Options.Canvas = { + $extend: true, + + injectInto: 'id', + type: '2D', + width: false, + height: false, + useCanvas: false, + withLabels: true, + background: false, + + Scene: { + Lighting: { + enable: false, + ambient: [1, 1, 1], + directional: { + direction: { x: -100, y: -100, z: -100 }, + color: [0.5, 0.3, 0.1] + } + } + } +}; + +/* + * File: Options.Tree.js + * +*/ + +/* + Object: Options.Tree + + Options related to (strict) Tree layout algorithms. These options are used by the visualization. + + Syntax: + + (start code js) + Options.Tree = { + orientation: "left", + subtreeOffset: 8, + siblingOffset: 5, + indent:10, + multitree: false, + align:"center" + }; + (end code) + + Example: + + (start code js) + var st = new $jit.ST({ + orientation: 'left', + subtreeOffset: 1, + siblingOFfset: 5, + multitree: true + }); + (end code) + + Parameters: + + subtreeOffset - (number) Default's 8. Separation offset between subtrees. + siblingOffset - (number) Default's 5. Separation offset between siblings. + orientation - (string) Default's 'left'. Tree orientation layout. Possible values are 'left', 'top', 'right', 'bottom'. + align - (string) Default's *center*. Whether the tree alignment is 'left', 'center' or 'right'. + indent - (number) Default's 10. Used when *align* is left or right and shows an indentation between parent and children. + multitree - (boolean) Default's *false*. Used with the node $orn data property for creating multitrees. + +*/ +Options.Tree = { + $extend: true, + + orientation: "left", + subtreeOffset: 8, + siblingOffset: 5, + indent:10, + multitree: false, + align:"center" +}; + + +/* + * File: Options.Node.js + * +*/ + +/* + Object: Options.Node + + Provides Node rendering options for Tree and Graph based visualizations. + + Syntax: + + (start code js) + Options.Node = { + overridable: false, + type: 'circle', + color: '#ccb', + alpha: 1, + dim: 3, + height: 20, + width: 90, + autoHeight: false, + autoWidth: false, + lineWidth: 1, + transform: true, + align: "center", + angularWidth:1, + span:1, + CanvasStyles: {} + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + Node: { + overridable: true, + width: 30, + autoHeight: true, + type: 'rectangle' + } + }); + (end code) + + Parameters: + + overridable - (boolean) Default's *false*. Determine whether or not general node properties can be overridden by a particular . + type - (string) Default's *circle*. Node's shape. Node built-in types include 'circle', 'rectangle', 'square', 'ellipse', 'triangle', 'star'. The default Node type might vary in each visualization. You can also implement (non built-in) custom Node types into your visualizations. + color - (string) Default's *#ccb*. Node color. + alpha - (number) Default's *1*. The Node's alpha value. *1* is for full opacity. + dim - (number) Default's *3*. An extra parameter used by 'circle', 'square', 'triangle' and 'star' node types. Depending on each shape, this parameter can set the radius of a circle, half the length of the side of a square, half the base and half the height of a triangle or the length of a side of a star (concave decagon). + height - (number) Default's *20*. Used by 'rectangle' and 'ellipse' node types. The height of the node shape. + width - (number) Default's *90*. Used by 'rectangle' and 'ellipse' node types. The width of the node shape. + autoHeight - (boolean) Default's *false*. Whether to set an auto height for the node depending on the content of the Node's label. + autoWidth - (boolean) Default's *false*. Whether to set an auto width for the node depending on the content of the Node's label. + lineWidth - (number) Default's *1*. Used only by some Node shapes. The line width of the strokes of a node. + transform - (boolean) Default's *true*. Only used by the visualization. Whether to scale the nodes according to the moebius transformation. + align - (string) Default's *center*. Possible values are 'center', 'left' or 'right'. Used only by the visualization, these parameters are used for aligning nodes when some of they dimensions vary. + angularWidth - (number) Default's *1*. Used in radial layouts (like or visualizations). The amount of relative 'space' set for a node. + span - (number) Default's *1*. Used in radial layouts (like or visualizations). The angle span amount set for a node. + CanvasStyles - (object) Default's an empty object (i.e. {}). Attach any other canvas specific property that you'd set to the canvas context before plotting a Node. + +*/ +Options.Node = { + $extend: false, + + overridable: false, + type: 'circle', + color: '#ccb', + alpha: 1, + dim: 3, + height: 20, + width: 90, + autoHeight: false, + autoWidth: false, + lineWidth: 1, + transform: true, + align: "center", + angularWidth:1, + span:1, + //Raw canvas styles to be + //applied to the context instance + //before plotting a node + CanvasStyles: {} +}; + + +/* + * File: Options.Edge.js + * +*/ + +/* + Object: Options.Edge + + Provides Edge rendering options for Tree and Graph based visualizations. + + Syntax: + + (start code js) + Options.Edge = { + overridable: false, + type: 'line', + color: '#ccb', + lineWidth: 1, + dim:15, + alpha: 1, + CanvasStyles: {} + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + Edge: { + overridable: true, + type: 'line', + color: '#fff', + CanvasStyles: { + shadowColor: '#ccc', + shadowBlur: 10 + } + } + }); + (end code) + + Parameters: + + overridable - (boolean) Default's *false*. Determine whether or not general edges properties can be overridden by a particular . + type - (string) Default's 'line'. Edge styles include 'line', 'hyperline', 'arrow'. The default Edge type might vary in each visualization. You can also implement custom Edge types. + color - (string) Default's '#ccb'. Edge color. + lineWidth - (number) Default's *1*. Line/Edge width. + alpha - (number) Default's *1*. The Edge's alpha value. *1* is for full opacity. + dim - (number) Default's *15*. An extra parameter used by other complex shapes such as quadratic, bezier or arrow, to determine the shape's diameter. + epsilon - (number) Default's *7*. Only used when using *enableForEdges* in . This dimension is used to create an area for the line where the contains method for the edge returns *true*. + CanvasStyles - (object) Default's an empty object (i.e. {}). Attach any other canvas specific property that you'd set to the canvas context before plotting an Edge. + + See also: + + If you want to know more about how to customize Node/Edge data per element, in the JSON or programmatically, take a look at this article. +*/ +Options.Edge = { + $extend: false, + + overridable: false, + type: 'line', + color: '#ccb', + lineWidth: 1, + dim:15, + alpha: 1, + epsilon: 7, + + //Raw canvas styles to be + //applied to the context instance + //before plotting an edge + CanvasStyles: {} +}; + + +/* + * File: Options.Fx.js + * +*/ + +/* + Object: Options.Fx + + Provides animation options like duration of the animations, frames per second and animation transitions. + + Syntax: + + (start code js) + Options.Fx = { + fps:40, + duration: 2500, + transition: $jit.Trans.Quart.easeInOut, + clearCanvas: true + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + duration: 1000, + fps: 35, + transition: $jit.Trans.linear + }); + (end code) + + Parameters: + + clearCanvas - (boolean) Default's *true*. Whether to clear the frame/canvas when the viz is plotted or animated. + duration - (number) Default's *2500*. Duration of the animation in milliseconds. + fps - (number) Default's *40*. Frames per second. + transition - (object) Default's *$jit.Trans.Quart.easeInOut*. The transition used for the animations. See below for a more detailed explanation. + + Object: $jit.Trans + + This object is used for specifying different animation transitions in all visualizations. + + There are many different type of animation transitions. + + linear: + + Displays a linear transition + + >Trans.linear + + (see Linear.png) + + Quad: + + Displays a Quadratic transition. + + >Trans.Quad.easeIn + >Trans.Quad.easeOut + >Trans.Quad.easeInOut + + (see Quad.png) + + Cubic: + + Displays a Cubic transition. + + >Trans.Cubic.easeIn + >Trans.Cubic.easeOut + >Trans.Cubic.easeInOut + + (see Cubic.png) + + Quart: + + Displays a Quartetic transition. + + >Trans.Quart.easeIn + >Trans.Quart.easeOut + >Trans.Quart.easeInOut + + (see Quart.png) + + Quint: + + Displays a Quintic transition. + + >Trans.Quint.easeIn + >Trans.Quint.easeOut + >Trans.Quint.easeInOut + + (see Quint.png) + + Expo: + + Displays an Exponential transition. + + >Trans.Expo.easeIn + >Trans.Expo.easeOut + >Trans.Expo.easeInOut + + (see Expo.png) + + Circ: + + Displays a Circular transition. + + >Trans.Circ.easeIn + >Trans.Circ.easeOut + >Trans.Circ.easeInOut + + (see Circ.png) + + Sine: + + Displays a Sineousidal transition. + + >Trans.Sine.easeIn + >Trans.Sine.easeOut + >Trans.Sine.easeInOut + + (see Sine.png) + + Back: + + >Trans.Back.easeIn + >Trans.Back.easeOut + >Trans.Back.easeInOut + + (see Back.png) + + Bounce: + + Bouncy transition. + + >Trans.Bounce.easeIn + >Trans.Bounce.easeOut + >Trans.Bounce.easeInOut + + (see Bounce.png) + + Elastic: + + Elastic curve. + + >Trans.Elastic.easeIn + >Trans.Elastic.easeOut + >Trans.Elastic.easeInOut + + (see Elastic.png) + + Based on: + + Easing and Transition animation methods are based in the MooTools Framework . Copyright (c) 2006-2010 Valerio Proietti, . MIT license . + + +*/ +Options.Fx = { + $extend: true, + + fps:40, + duration: 2500, + transition: $jit.Trans.Quart.easeInOut, + clearCanvas: true +}; + +/* + * File: Options.Label.js + * +*/ +/* + Object: Options.Label + + Provides styling for Labels such as font size, family, etc. Also sets Node labels as HTML, SVG or Native canvas elements. + + Syntax: + + (start code js) + Options.Label = { + overridable: false, + type: 'HTML', //'SVG', 'Native' + style: ' ', + size: 10, + family: 'sans-serif', + textAlign: 'center', + textBaseline: 'alphabetic', + color: '#fff' + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + Label: { + type: 'Native', + size: 11, + color: '#ccc' + } + }); + (end code) + + Parameters: + + overridable - (boolean) Default's *false*. Determine whether or not general label properties can be overridden by a particular . + type - (string) Default's *HTML*. The type for the labels. Can be 'HTML', 'SVG' or 'Native' canvas labels. + style - (string) Default's *empty string*. Can be 'italic' or 'bold'. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels. + size - (number) Default's *10*. The font's size. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels. + family - (string) Default's *sans-serif*. The font's family. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels. + color - (string) Default's *#fff*. The font's color. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels. +*/ +Options.Label = { + $extend: false, + + overridable: false, + type: 'HTML', //'SVG', 'Native' + style: ' ', + size: 10, + family: 'sans-serif', + textAlign: 'center', + textBaseline: 'alphabetic', + color: '#fff' +}; + + +/* + * File: Options.Tips.js + * + */ + +/* + Object: Options.Tips + + Tips options + + Syntax: + + (start code js) + Options.Tips = { + enable: false, + type: 'auto', + offsetX: 20, + offsetY: 20, + onShow: $.empty, + onHide: $.empty + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + Tips: { + enable: true, + type: 'Native', + offsetX: 10, + offsetY: 10, + onShow: function(tip, node) { + tip.innerHTML = node.name; + } + } + }); + (end code) + + Parameters: + + enable - (boolean) Default's *false*. If *true*, a tooltip will be shown when a node is hovered. The tooltip is a div DOM element having "tip" as CSS class. + type - (string) Default's *auto*. Defines where to attach the MouseEnter/Leave tooltip events. Possible values are 'Native' to attach them to the canvas or 'HTML' to attach them to DOM label elements (if defined). 'auto' sets this property to the value of 's *type* property. + offsetX - (number) Default's *20*. An offset added to the current tooltip x-position (which is the same as the current mouse position). Default's 20. + offsetY - (number) Default's *20*. An offset added to the current tooltip y-position (which is the same as the current mouse position). Default's 20. + onShow(tip, node) - This callack is used right before displaying a tooltip. The first formal parameter is the tip itself (which is a DivElement). The second parameter may be a for graph based visualizations or an object with label, value properties for charts. + onHide() - This callack is used when hiding a tooltip. + +*/ +Options.Tips = { + $extend: false, + + enable: false, + type: 'auto', + offsetX: 20, + offsetY: 20, + force: false, + onShow: $.empty, + onHide: $.empty +}; + + +/* + * File: Options.NodeStyles.js + * + */ + +/* + Object: Options.NodeStyles + + Apply different styles when a node is hovered or selected. + + Syntax: + + (start code js) + Options.NodeStyles = { + enable: false, + type: 'auto', + stylesHover: false, + stylesClick: false + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + NodeStyles: { + enable: true, + type: 'Native', + stylesHover: { + dim: 30, + color: '#fcc' + }, + duration: 600 + } + }); + (end code) + + Parameters: + + enable - (boolean) Default's *false*. Whether to enable this option. + type - (string) Default's *auto*. Use this to attach the hover/click events in the nodes or the nodes labels (if they have been defined as DOM elements: 'HTML' or 'SVG', see for more details). The default 'auto' value will set NodeStyles to the same type defined for . + stylesHover - (boolean|object) Default's *false*. An object with node styles just like the ones defined for or *false* otherwise. + stylesClick - (boolean|object) Default's *false*. An object with node styles just like the ones defined for or *false* otherwise. +*/ + +Options.NodeStyles = { + $extend: false, + + enable: false, + type: 'auto', + stylesHover: false, + stylesClick: false +}; + + +/* + * File: Options.Events.js + * +*/ + +/* + Object: Options.Events + + Configuration for adding mouse/touch event handlers to Nodes. + + Syntax: + + (start code js) + Options.Events = { + enable: false, + enableForEdges: false, + type: 'auto', + onClick: $.empty, + onRightClick: $.empty, + onMouseMove: $.empty, + onMouseEnter: $.empty, + onMouseLeave: $.empty, + onDragStart: $.empty, + onDragMove: $.empty, + onDragCancel: $.empty, + onDragEnd: $.empty, + onTouchStart: $.empty, + onTouchMove: $.empty, + onTouchEnd: $.empty, + onTouchCancel: $.empty, + onMouseWheel: $.empty + }; + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + Events: { + enable: true, + onClick: function(node, eventInfo, e) { + viz.doSomething(); + }, + onMouseEnter: function(node, eventInfo, e) { + viz.canvas.getElement().style.cursor = 'pointer'; + }, + onMouseLeave: function(node, eventInfo, e) { + viz.canvas.getElement().style.cursor = ''; + } + } + }); + (end code) + + Parameters: + + enable - (boolean) Default's *false*. Whether to enable the Event system. + enableForEdges - (boolean) Default's *false*. Whether to track events also in arcs. If *true* the same callbacks -described below- are used for nodes *and* edges. A simple duck type check for edges is to check for *node.nodeFrom*. + type - (string) Default's 'auto'. Whether to attach the events onto the HTML labels (via event delegation) or to use the custom 'Native' canvas Event System of the library. 'auto' is set when you let the *type* parameter decide this. + onClick(node, eventInfo, e) - Triggered when a user performs a click in the canvas. *node* is the clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onRightClick(node, eventInfo, e) - Triggered when a user performs a right click in the canvas. *node* is the right clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onMouseMove(node, eventInfo, e) - Triggered when the user moves the mouse. *node* is the under the cursor as it's moving over the canvas or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onMouseEnter(node, eventInfo, e) - Triggered when a user moves the mouse over a node. *node* is the that the mouse just entered. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onMouseLeave(node, eventInfo, e) - Triggered when the user mouse-outs a node. *node* is the 'mouse-outed'. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragStart(node, eventInfo, e) - Triggered when the user mouse-downs over a node. *node* is the being pressed. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragMove(node, eventInfo, e) - Triggered when a user, after pressing the mouse button over a node, moves the mouse around. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragEnd(node, eventInfo, e) - Triggered when a user finished dragging a node. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragCancel(node, eventInfo, e) - Triggered when the user releases the mouse button over a that wasn't dragged (i.e. the user didn't perform any mouse movement after pressing the mouse button). *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onTouchStart(node, eventInfo, e) - Behaves just like onDragStart. + onTouchMove(node, eventInfo, e) - Behaves just like onDragMove. + onTouchEnd(node, eventInfo, e) - Behaves just like onDragEnd. + onTouchCancel(node, eventInfo, e) - Behaves just like onDragCancel. + onMouseWheel(delta, e) - Triggered when the user uses the mouse scroll over the canvas. *delta* is 1 or -1 depending on the sense of the mouse scroll. +*/ + +Options.Events = { + $extend: false, + + enable: false, + enableForEdges: false, + type: 'auto', + onClick: $.empty, + onRightClick: $.empty, + onMouseMove: $.empty, + onMouseEnter: $.empty, + onMouseLeave: $.empty, + onDragStart: $.empty, + onDragMove: $.empty, + onDragCancel: $.empty, + onDragEnd: $.empty, + onTouchStart: $.empty, + onTouchMove: $.empty, + onTouchEnd: $.empty, + onMouseWheel: $.empty +}; + +/* + * File: Options.Navigation.js + * +*/ + +/* + Object: Options.Navigation + + Panning and zooming options for Graph/Tree based visualizations. These options are implemented + by all visualizations except charts (, and ). + + Syntax: + + (start code js) + + Options.Navigation = { + enable: false, + type: 'auto', + panning: false, //true, 'avoid nodes' + zooming: false + }; + + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + Navigation: { + enable: true, + panning: 'avoid nodes', + zooming: 20 + } + }); + (end code) + + Parameters: + + enable - (boolean) Default's *false*. Whether to enable Navigation capabilities. + type - (string) Default's 'auto'. Whether to attach the navigation events onto the HTML labels (via event delegation) or to use the custom 'Native' canvas Event System of the library. When 'auto' set when you let the *type* parameter decide this. + panning - (boolean|string) Default's *false*. Set this property to *true* if you want to add Drag and Drop panning support to the visualization. You can also set this parameter to 'avoid nodes' to enable DnD panning but disable it if the DnD is taking place over a node. This is useful when some other events like Drag & Drop for nodes are added to . + zooming - (boolean|number) Default's *false*. Set this property to a numeric value to turn mouse-scroll zooming on. The number will be proportional to the mouse-scroll sensitivity. + +*/ + +Options.Navigation = { + $extend: false, + + enable: false, + type: 'auto', + panning: false, //true | 'avoid nodes' + zooming: false +}; + +/* + * File: Options.Controller.js + * +*/ + +/* + Object: Options.Controller + + Provides controller methods. Controller methods are callback functions that get called at different stages + of the animation, computing or plotting of the visualization. + + Implemented by: + + All visualizations except charts (, and ). + + Syntax: + + (start code js) + + Options.Controller = { + onBeforeCompute: $.empty, + onAfterCompute: $.empty, + onCreateLabel: $.empty, + onPlaceLabel: $.empty, + onComplete: $.empty, + onBeforePlotLine:$.empty, + onAfterPlotLine: $.empty, + onBeforePlotNode:$.empty, + onAfterPlotNode: $.empty, + request: false + }; + + (end code) + + Example: + + (start code js) + var viz = new $jit.Viz({ + onBeforePlotNode: function(node) { + if(node.selected) { + node.setData('color', '#ffc'); + } else { + node.removeData('color'); + } + }, + onBeforePlotLine: function(adj) { + if(adj.nodeFrom.selected && adj.nodeTo.selected) { + adj.setData('color', '#ffc'); + } else { + adj.removeData('color'); + } + }, + onAfterCompute: function() { + alert("computed!"); + } + }); + (end code) + + Parameters: + + onBeforeCompute(node) - This method is called right before performing all computations and animations. The selected is passed as parameter. + onAfterCompute() - This method is triggered after all animations or computations ended. + onCreateLabel(domElement, node) - This method receives a new label DIV element as first parameter, and the corresponding as second parameter. This method will only be called once for each label. This method is useful when adding events or styles to the labels used by the JIT. + onPlaceLabel(domElement, node) - This method receives a label DIV element as first parameter and the corresponding as second parameter. This method is called each time a label has been placed in the visualization, for example at each step of an animation, and thus it allows you to update the labels properties, such as size or position. Note that onPlaceLabel will be triggered after updating the labels positions. That means that, for example, the left and top css properties are already updated to match the nodes positions. Width and height properties are not set however. + onBeforePlotNode(node) - This method is triggered right before plotting each . This method is useful for changing a node style right before plotting it. + onAfterPlotNode(node) - This method is triggered right after plotting each . + onBeforePlotLine(adj) - This method is triggered right before plotting a . This method is useful for adding some styles to a particular edge before being plotted. + onAfterPlotLine(adj) - This method is triggered right after plotting a . + + *Used in , and visualizations* + + request(nodeId, level, onComplete) - This method is used for buffering information into the visualization. When clicking on an empty node, the visualization will make a request for this node's subtrees, specifying a given level for this subtree (defined by _levelsToShow_). Once the request is completed, the onComplete callback should be called with the given result. This is useful to provide on-demand information into the visualizations withought having to load the entire information from start. The parameters used by this method are _nodeId_, which is the id of the root of the subtree to request, _level_ which is the depth of the subtree to be requested (0 would mean just the root node). _onComplete_ is an object having the callback method _onComplete.onComplete(json)_ that should be called once the json has been retrieved. + + */ +Options.Controller = { + $extend: true, + + onBeforeCompute: $.empty, + onAfterCompute: $.empty, + onCreateLabel: $.empty, + onPlaceLabel: $.empty, + onComplete: $.empty, + onBeforePlotLine:$.empty, + onAfterPlotLine: $.empty, + onBeforePlotNode:$.empty, + onAfterPlotNode: $.empty, + request: false +}; + + +/* + * File: Extras.js + * + * Provides Extras such as Tips and Style Effects. + * + * Description: + * + * Provides the and classes and functions. + * + */ + +/* + * Manager for mouse events (clicking and mouse moving). + * + * This class is used for registering objects implementing onClick + * and onMousemove methods. These methods are called when clicking or + * moving the mouse around the Canvas. + * For now, and are classes implementing these methods. + * + */ +var ExtrasInitializer = { + initialize: function(className, viz) { + this.viz = viz; + this.canvas = viz.canvas; + this.config = viz.config[className]; + this.nodeTypes = viz.fx.nodeTypes; + var type = this.config.type; + this.dom = type == 'auto'? (viz.config.Label.type != 'Native') : (type != 'Native'); + this.labelContainer = this.dom && viz.labels.getLabelContainer(); + this.isEnabled() && this.initializePost(); + }, + initializePost: $.empty, + setAsProperty: $.lambda(false), + isEnabled: function() { + return this.config.enable; + }, + isLabel: function(e, win, group) { + e = $.event.get(e, win); + var labelContainer = this.labelContainer, + target = e.target || e.srcElement, + related = e.relatedTarget; + if(group) { + return related && related == this.viz.canvas.getCtx().canvas + && !!target && this.isDescendantOf(target, labelContainer); + } else { + return this.isDescendantOf(target, labelContainer); + } + }, + isDescendantOf: function(elem, par) { + while(elem && elem.parentNode) { + if(elem.parentNode == par) + return elem; + elem = elem.parentNode; + } + return false; + } +}; + +var EventsInterface = { + onMouseUp: $.empty, + onMouseDown: $.empty, + onMouseMove: $.empty, + onMouseOver: $.empty, + onMouseOut: $.empty, + onMouseWheel: $.empty, + onTouchStart: $.empty, + onTouchMove: $.empty, + onTouchEnd: $.empty, + onTouchCancel: $.empty +}; + +var MouseEventsManager = new Class({ + initialize: function(viz) { + this.viz = viz; + this.canvas = viz.canvas; + this.node = false; + this.edge = false; + this.registeredObjects = []; + this.attachEvents(); + }, + + attachEvents: function() { + var htmlCanvas = this.canvas.getElement(), + that = this; + htmlCanvas.oncontextmenu = $.lambda(false); + $.addEvents(htmlCanvas, { + 'mouseup': function(e, win) { + var event = $.event.get(e, win); + that.handleEvent('MouseUp', e, win, + that.makeEventObject(e, win), + $.event.isRightClick(event)); + }, + 'mousedown': function(e, win) { + var event = $.event.get(e, win); + that.handleEvent('MouseDown', e, win, that.makeEventObject(e, win), + $.event.isRightClick(event)); + }, + 'mousemove': function(e, win) { + that.handleEvent('MouseMove', e, win, that.makeEventObject(e, win)); + }, + 'mouseover': function(e, win) { + that.handleEvent('MouseOver', e, win, that.makeEventObject(e, win)); + }, + 'mouseout': function(e, win) { + that.handleEvent('MouseOut', e, win, that.makeEventObject(e, win)); + }, + 'touchstart': function(e, win) { + that.handleEvent('TouchStart', e, win, that.makeEventObject(e, win)); + }, + 'touchmove': function(e, win) { + that.handleEvent('TouchMove', e, win, that.makeEventObject(e, win)); + }, + 'touchend': function(e, win) { + that.handleEvent('TouchEnd', e, win, that.makeEventObject(e, win)); + } + }); + //attach mousewheel event + var handleMouseWheel = function(e, win) { + var event = $.event.get(e, win); + var wheel = $.event.getWheel(event); + that.handleEvent('MouseWheel', e, win, wheel); + }; + //TODO(nico): this is a horrible check for non-gecko browsers! + if(!document.getBoxObjectFor && window.mozInnerScreenX == null) { + $.addEvent(htmlCanvas, 'mousewheel', handleMouseWheel); + } else { + htmlCanvas.addEventListener('DOMMouseScroll', handleMouseWheel, false); + } + }, + + register: function(obj) { + this.registeredObjects.push(obj); + }, + + handleEvent: function() { + var args = Array.prototype.slice.call(arguments), + type = args.shift(); + for(var i=0, regs=this.registeredObjects, l=regs.length; i and implemented + * by all main visualizations. + * + */ +var Extras = { + initializeExtras: function() { + var mem = new MouseEventsManager(this), that = this; + $.each(['NodeStyles', 'Tips', 'Navigation', 'Events'], function(k) { + var obj = new Extras.Classes[k](k, that); + if(obj.isEnabled()) { + mem.register(obj); + } + if(obj.setAsProperty()) { + that[k.toLowerCase()] = obj; + } + }); + } +}; + +Extras.Classes = {}; +/* + Class: Events + + This class defines an Event API to be accessed by the user. + The methods implemented are the ones defined in the object. +*/ + +Extras.Classes.Events = new Class({ + Implements: [ExtrasInitializer, EventsInterface], + + initializePost: function() { + this.fx = this.viz.fx; + this.ntypes = this.viz.fx.nodeTypes; + this.etypes = this.viz.fx.edgeTypes; + + this.hovered = false; + this.pressed = false; + this.touched = false; + + this.touchMoved = false; + this.moved = false; + + }, + + setAsProperty: $.lambda(true), + + onMouseUp: function(e, win, event, isRightClick) { + var evt = $.event.get(e, win); + if(!this.moved) { + if(isRightClick) { + this.config.onRightClick(this.hovered, event, evt); + } else { + this.config.onClick(this.pressed, event, evt); + } + } + if(this.pressed) { + if(this.moved) { + this.config.onDragEnd(this.pressed, event, evt); + } else { + this.config.onDragCancel(this.pressed, event, evt); + } + this.pressed = this.moved = false; + } + }, + + onMouseOut: function(e, win, event) { + //mouseout a label + var evt = $.event.get(e, win), label; + if(this.dom && (label = this.isLabel(e, win, true))) { + this.config.onMouseLeave(this.viz.graph.getNode(label.id), + event, evt); + this.hovered = false; + return; + } + //mouseout canvas + var rt = evt.relatedTarget, + canvasWidget = this.canvas.getElement(); + while(rt && rt.parentNode) { + if(canvasWidget == rt.parentNode) return; + rt = rt.parentNode; + } + if(this.hovered) { + this.config.onMouseLeave(this.hovered, + event, evt); + this.hovered = false; + } + }, + + onMouseOver: function(e, win, event) { + //mouseover a label + var evt = $.event.get(e, win), label; + if(this.dom && (label = this.isLabel(e, win, true))) { + this.hovered = this.viz.graph.getNode(label.id); + this.config.onMouseEnter(this.hovered, + event, evt); + } + }, + + onMouseMove: function(e, win, event) { + var label, evt = $.event.get(e, win); + if(this.pressed) { + this.moved = true; + this.config.onDragMove(this.pressed, event, evt); + return; + } + if(this.dom) { + this.config.onMouseMove(this.hovered, + event, evt); + } else { + if(this.hovered) { + var hn = this.hovered; + var geom = hn.nodeFrom? this.etypes[hn.getData('type')] : this.ntypes[hn.getData('type')]; + var contains = geom && geom.contains + && geom.contains.call(this.fx, hn, event.getPos()); + if(contains) { + this.config.onMouseMove(hn, event, evt); + return; + } else { + this.config.onMouseLeave(hn, event, evt); + this.hovered = false; + } + } + if(this.hovered = (event.getNode() || (this.config.enableForEdges && event.getEdge()))) { + this.config.onMouseEnter(this.hovered, event, evt); + } else { + this.config.onMouseMove(false, event, evt); + } + } + }, + + onMouseWheel: function(e, win, delta) { + this.config.onMouseWheel(delta, $.event.get(e, win)); + }, + + onMouseDown: function(e, win, event) { + var evt = $.event.get(e, win), label; + if(this.dom) { + if(label = this.isLabel(e, win)) { + this.pressed = this.viz.graph.getNode(label.id); + } + } else { + this.pressed = event.getNode() || (this.config.enableForEdges && event.getEdge()); + } + this.pressed && this.config.onDragStart(this.pressed, event, evt); + }, + + onTouchStart: function(e, win, event) { + var evt = $.event.get(e, win), label; + if(this.dom && (label = this.isLabel(e, win))) { + this.touched = this.viz.graph.getNode(label.id); + } else { + this.touched = event.getNode() || (this.config.enableForEdges && event.getEdge()); + } + this.touched && this.config.onTouchStart(this.touched, event, evt); + }, + + onTouchMove: function(e, win, event) { + var evt = $.event.get(e, win); + if(this.touched) { + this.touchMoved = true; + this.config.onTouchMove(this.touched, event, evt); + } + }, + + onTouchEnd: function(e, win, event) { + var evt = $.event.get(e, win); + if(this.touched) { + if(this.touchMoved) { + this.config.onTouchEnd(this.touched, event, evt); + } else { + this.config.onTouchCancel(this.touched, event, evt); + } + this.touched = this.touchMoved = false; + } + } +}); + +/* + Class: Tips + + A class containing tip related functions. This class is used internally. + + Used by: + + , , , , , , + + See also: + + +*/ + +Extras.Classes.Tips = new Class({ + Implements: [ExtrasInitializer, EventsInterface], + + initializePost: function() { + //add DOM tooltip + if(document.body) { + var tip = $('_tooltip') || document.createElement('div'); + tip.id = '_tooltip'; + tip.className = 'tip'; + $.extend(tip.style, { + position: 'absolute', + display: 'none', + zIndex: 13000 + }); + document.body.appendChild(tip); + this.tip = tip; + this.node = false; + } + }, + + setAsProperty: $.lambda(true), + + onMouseOut: function(e, win) { + //mouseout a label + var evt = $.event.get(e, win); + if(this.dom && this.isLabel(e, win, true)) { + this.hide(true); + return; + } + //mouseout canvas + var rt = e.relatedTarget, + canvasWidget = this.canvas.getElement(); + while(rt && rt.parentNode) { + if(canvasWidget == rt.parentNode) return; + rt = rt.parentNode; + } + this.hide(false); + }, + + onMouseOver: function(e, win) { + //mouseover a label + var label; + if(this.dom && (label = this.isLabel(e, win, false))) { + this.node = this.viz.graph.getNode(label.id); + this.config.onShow(this.tip, this.node, label); + } + }, + + onMouseMove: function(e, win, opt) { + if(this.dom && this.isLabel(e, win)) { + this.setTooltipPosition($.event.getPos(e, win)); + } + if(!this.dom) { + var node = opt.getNode(); + if(!node) { + this.hide(true); + return; + } + if(this.config.force || !this.node || this.node.id != node.id) { + this.node = node; + this.config.onShow(this.tip, node, opt.getContains()); + } + this.setTooltipPosition($.event.getPos(e, win)); + } + }, + + setTooltipPosition: function(pos) { + var tip = this.tip, + style = tip.style, + cont = this.config; + style.display = ''; + //get window dimensions + var win = { + 'height': document.body.clientHeight, + 'width': document.body.clientWidth + }; + //get tooltip dimensions + var obj = { + 'width': tip.offsetWidth, + 'height': tip.offsetHeight + }; + //set tooltip position + var x = cont.offsetX, y = cont.offsetY; + style.top = ((pos.y + y + obj.height > win.height)? + (pos.y - obj.height - y) : pos.y + y) + 'px'; + style.left = ((pos.x + obj.width + x > win.width)? + (pos.x - obj.width - x) : pos.x + x) + 'px'; + }, + + hide: function(triggerCallback) { + this.tip.style.display = 'none'; + triggerCallback && this.config.onHide(); + } +}); + +/* + Class: NodeStyles + + Change node styles when clicking or hovering a node. This class is used internally. + + Used by: + + , , , , , , + + See also: + + +*/ +Extras.Classes.NodeStyles = new Class({ + Implements: [ExtrasInitializer, EventsInterface], + + initializePost: function() { + this.fx = this.viz.fx; + this.types = this.viz.fx.nodeTypes; + this.nStyles = this.config; + this.nodeStylesOnHover = this.nStyles.stylesHover; + this.nodeStylesOnClick = this.nStyles.stylesClick; + this.hoveredNode = false; + this.fx.nodeFxAnimation = new Animation(); + + this.down = false; + this.move = false; + }, + + onMouseOut: function(e, win) { + this.down = this.move = false; + if(!this.hoveredNode) return; + //mouseout a label + if(this.dom && this.isLabel(e, win, true)) { + this.toggleStylesOnHover(this.hoveredNode, false); + } + //mouseout canvas + var rt = e.relatedTarget, + canvasWidget = this.canvas.getElement(); + while(rt && rt.parentNode) { + if(canvasWidget == rt.parentNode) return; + rt = rt.parentNode; + } + this.toggleStylesOnHover(this.hoveredNode, false); + this.hoveredNode = false; + }, + + onMouseOver: function(e, win) { + //mouseover a label + var label; + if(this.dom && (label = this.isLabel(e, win, true))) { + var node = this.viz.graph.getNode(label.id); + if(node.selected) return; + this.hoveredNode = node; + this.toggleStylesOnHover(this.hoveredNode, true); + } + }, + + onMouseDown: function(e, win, event, isRightClick) { + if(isRightClick) return; + var label; + if(this.dom && (label = this.isLabel(e, win))) { + this.down = this.viz.graph.getNode(label.id); + } else if(!this.dom) { + this.down = event.getNode(); + } + this.move = false; + }, + + onMouseUp: function(e, win, event, isRightClick) { + if(isRightClick) return; + if(!this.move) { + this.onClick(event.getNode()); + } + this.down = this.move = false; + }, + + getRestoredStyles: function(node, type) { + var restoredStyles = {}, + nStyles = this['nodeStylesOn' + type]; + for(var prop in nStyles) { + restoredStyles[prop] = node.styles['$' + prop]; + } + return restoredStyles; + }, + + toggleStylesOnHover: function(node, set) { + if(this.nodeStylesOnHover) { + this.toggleStylesOn('Hover', node, set); + } + }, + + toggleStylesOnClick: function(node, set) { + if(this.nodeStylesOnClick) { + this.toggleStylesOn('Click', node, set); + } + }, + + toggleStylesOn: function(type, node, set) { + var viz = this.viz; + var nStyles = this.nStyles; + if(set) { + var that = this; + if(!node.styles) { + node.styles = $.merge(node.data, {}); + } + for(var s in this['nodeStylesOn' + type]) { + var $s = '$' + s; + if(!($s in node.styles)) { + node.styles[$s] = node.getData(s); + } + } + viz.fx.nodeFx($.extend({ + 'elements': { + 'id': node.id, + 'properties': that['nodeStylesOn' + type] + }, + transition: Trans.Quart.easeOut, + duration:300, + fps:40 + }, this.config)); + } else { + var restoredStyles = this.getRestoredStyles(node, type); + viz.fx.nodeFx($.extend({ + 'elements': { + 'id': node.id, + 'properties': restoredStyles + }, + transition: Trans.Quart.easeOut, + duration:300, + fps:40 + }, this.config)); + } + }, + + onClick: function(node) { + if(!node) return; + var nStyles = this.nodeStylesOnClick; + if(!nStyles) return; + //if the node is selected then unselect it + if(node.selected) { + this.toggleStylesOnClick(node, false); + delete node.selected; + } else { + //unselect all selected nodes... + this.viz.graph.eachNode(function(n) { + if(n.selected) { + for(var s in nStyles) { + n.setData(s, n.styles['$' + s], 'end'); + } + delete n.selected; + } + }); + //select clicked node + this.toggleStylesOnClick(node, true); + node.selected = true; + delete node.hovered; + this.hoveredNode = false; + } + }, + + onMouseMove: function(e, win, event) { + //if mouse button is down and moving set move=true + if(this.down) this.move = true; + //already handled by mouseover/out + if(this.dom && this.isLabel(e, win)) return; + var nStyles = this.nodeStylesOnHover; + if(!nStyles) return; + + if(!this.dom) { + if(this.hoveredNode) { + var geom = this.types[this.hoveredNode.getData('type')]; + var contains = geom && geom.contains && geom.contains.call(this.fx, + this.hoveredNode, event.getPos()); + if(contains) return; + } + var node = event.getNode(); + //if no node is being hovered then just exit + if(!this.hoveredNode && !node) return; + //if the node is hovered then exit + if(node.hovered) return; + //select hovered node + if(node && !node.selected) { + //check if an animation is running and exit it + this.fx.nodeFxAnimation.stopTimer(); + //unselect all hovered nodes... + this.viz.graph.eachNode(function(n) { + if(n.hovered && !n.selected) { + for(var s in nStyles) { + n.setData(s, n.styles['$' + s], 'end'); + } + delete n.hovered; + } + }); + //select hovered node + node.hovered = true; + this.hoveredNode = node; + this.toggleStylesOnHover(node, true); + } else if(this.hoveredNode && !this.hoveredNode.selected) { + //check if an animation is running and exit it + this.fx.nodeFxAnimation.stopTimer(); + //unselect hovered node + this.toggleStylesOnHover(this.hoveredNode, false); + delete this.hoveredNode.hovered; + this.hoveredNode = false; + } + } + } +}); + +Extras.Classes.Navigation = new Class({ + Implements: [ExtrasInitializer, EventsInterface], + + initializePost: function() { + this.pos = false; + this.pressed = false; + }, + + onMouseWheel: function(e, win, scroll) { + if(!this.config.zooming) return; + $.event.stop($.event.get(e, win)); + var val = this.config.zooming / 1000, + ans = 1 + scroll * val; + this.canvas.scale(ans, ans); + }, + + onMouseDown: function(e, win, eventInfo) { + if(!this.config.panning) return; + if(this.config.panning == 'avoid nodes' && (this.dom? this.isLabel(e, win) : eventInfo.getNode())) return; + this.pressed = true; + this.pos = eventInfo.getPos(); + var canvas = this.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY; + this.pos.x *= sx; + this.pos.x += ox; + this.pos.y *= sy; + this.pos.y += oy; + }, + + onMouseMove: function(e, win, eventInfo) { + if(!this.config.panning) return; + if(!this.pressed) return; + if(this.config.panning == 'avoid nodes' && (this.dom? this.isLabel(e, win) : eventInfo.getNode())) return; + var thispos = this.pos, + currentPos = eventInfo.getPos(), + canvas = this.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY; + currentPos.x *= sx; + currentPos.y *= sy; + currentPos.x += ox; + currentPos.y += oy; + var x = currentPos.x - thispos.x, + y = currentPos.y - thispos.y; + this.pos = currentPos; + this.canvas.translate(x * 1/sx, y * 1/sy); + }, + + onMouseUp: function(e, win, eventInfo, isRightClick) { + if(!this.config.panning) return; + this.pressed = false; + } +}); + + +/* + * File: Canvas.js + * + */ + +/* + Class: Canvas + + A canvas widget used by all visualizations. The canvas object can be accessed by doing *viz.canvas*. If you want to + know more about options take a look at . + + A canvas widget is a set of DOM elements that wrap the native canvas DOM Element providing a consistent API and behavior + across all browsers. It can also include Elements to add DOM (SVG or HTML) label support to all visualizations. + + Example: + + Suppose we have this HTML + + (start code xml) +
+ (end code) + + Now we create a new Visualization + + (start code js) + var viz = new $jit.Viz({ + //Where to inject the canvas. Any div container will do. + 'injectInto':'infovis', + //width and height for canvas. + //Default's to the container offsetWidth and Height. + 'width': 900, + 'height':500 + }); + (end code) + + The generated HTML will look like this + + (start code xml) +
+
+ +
+
+
+
+ (end code) + + As you can see, the generated HTML consists of a canvas DOM Element of id *infovis-canvas* and a div label container + of id *infovis-label*, wrapped in a main div container of id *infovis-canvaswidget*. + */ + +var Canvas; +(function() { + //check for native canvas support + var canvasType = typeof HTMLCanvasElement, + supportsCanvas = (canvasType == 'object' || canvasType == 'function'); + //create element function + function $E(tag, props) { + var elem = document.createElement(tag); + for(var p in props) { + if(typeof props[p] == "object") { + $.extend(elem[p], props[p]); + } else { + elem[p] = props[p]; + } + } + if (tag == "canvas" && !supportsCanvas && G_vmlCanvasManager) { + elem = G_vmlCanvasManager.initElement(document.body.appendChild(elem)); + } + return elem; + } + //canvas widget which we will call just Canvas + $jit.Canvas = Canvas = new Class({ + canvases: [], + pos: false, + element: false, + labelContainer: false, + translateOffsetX: 0, + translateOffsetY: 0, + scaleOffsetX: 1, + scaleOffsetY: 1, + + initialize: function(viz, opt) { + this.viz = viz; + this.opt = this.config = opt; + var id = $.type(opt.injectInto) == 'string'? + opt.injectInto:opt.injectInto.id, + type = opt.type, + idLabel = id + "-label", + wrapper = $(id), + width = opt.width || wrapper.offsetWidth, + height = opt.height || wrapper.offsetHeight; + this.id = id; + //canvas options + var canvasOptions = { + injectInto: id, + width: width, + height: height + }; + //create main wrapper + this.element = $E('div', { + 'id': id + '-canvaswidget', + 'style': { + 'position': 'relative', + 'width': width + 'px', + 'height': height + 'px' + } + }); + //create label container + this.labelContainer = this.createLabelContainer(opt.Label.type, + idLabel, canvasOptions); + //create primary canvas + this.canvases.push(new Canvas.Base[type]({ + config: $.extend({idSuffix: '-canvas'}, canvasOptions), + plot: function(base) { + viz.fx.plot(); + }, + resize: function() { + viz.refresh(); + } + })); + //create secondary canvas + var back = opt.background; + if(back) { + var backCanvas = new Canvas.Background[back.type](viz, $.extend(back, canvasOptions)); + this.canvases.push(new Canvas.Base[type](backCanvas)); + } + //insert canvases + var len = this.canvases.length; + while(len--) { + this.element.appendChild(this.canvases[len].canvas); + if(len > 0) { + this.canvases[len].plot(); + } + } + this.element.appendChild(this.labelContainer); + wrapper.appendChild(this.element); + //Update canvas position when the page is scrolled. + var timer = null, that = this; + $.addEvent(window, 'scroll', function() { + clearTimeout(timer); + timer = setTimeout(function() { + that.getPos(true); //update canvas position + }, 500); + }); + }, + /* + Method: getCtx + + Returns the main canvas context object + + Example: + + (start code js) + var ctx = canvas.getCtx(); + //Now I can use the native canvas context + //and for example change some canvas styles + ctx.globalAlpha = 1; + (end code) + */ + getCtx: function(i) { + return this.canvases[i || 0].getCtx(); + }, + /* + Method: getConfig + + Returns the current Configuration for this Canvas Widget. + + Example: + + (start code js) + var config = canvas.getConfig(); + (end code) + */ + getConfig: function() { + return this.opt; + }, + /* + Method: getElement + + Returns the main Canvas DOM wrapper + + Example: + + (start code js) + var wrapper = canvas.getElement(); + //Returns
...
as element + (end code) + */ + getElement: function() { + return this.element; + }, + /* + Method: getSize + + Returns canvas dimensions. + + Returns: + + An object with *width* and *height* properties. + + Example: + (start code js) + canvas.getSize(); //returns { width: 900, height: 500 } + (end code) + */ + getSize: function(i) { + return this.canvases[i || 0].getSize(); + }, + /* + Method: resize + + Resizes the canvas. + + Parameters: + + width - New canvas width. + height - New canvas height. + + Example: + + (start code js) + canvas.resize(width, height); + (end code) + + */ + resize: function(width, height) { + this.getPos(true); + this.translateOffsetX = this.translateOffsetY = 0; + this.scaleOffsetX = this.scaleOffsetY = 1; + for(var i=0, l=this.canvases.length; i class. + * + * Description: + * + * The class, just like the class, is used by the , and as a 2D point representation. + * + * See also: + * + * + * +*/ + +/* + Class: Polar + + A multi purpose polar representation. + + Description: + + The class, just like the class, is used by the , and as a 2D point representation. + + See also: + + + + Parameters: + + theta - An angle. + rho - The norm. +*/ + +var Polar = function(theta, rho) { + this.theta = theta || 0; + this.rho = rho || 0; +}; + +$jit.Polar = Polar; + +Polar.prototype = { + /* + Method: getc + + Returns a complex number. + + Parameters: + + simple - _optional_ If *true*, this method will return only an object holding x and y properties and not a instance. Default's *false*. + + Returns: + + A complex number. + */ + getc: function(simple) { + return this.toComplex(simple); + }, + + /* + Method: getp + + Returns a representation. + + Returns: + + A variable in polar coordinates. + */ + getp: function() { + return this; + }, + + + /* + Method: set + + Sets a number. + + Parameters: + + v - A or instance. + + */ + set: function(v) { + v = v.getp(); + this.theta = v.theta; this.rho = v.rho; + }, + + /* + Method: setc + + Sets a number. + + Parameters: + + x - A number real part. + y - A number imaginary part. + + */ + setc: function(x, y) { + this.rho = Math.sqrt(x * x + y * y); + this.theta = Math.atan2(y, x); + if(this.theta < 0) this.theta += Math.PI * 2; + }, + + /* + Method: setp + + Sets a polar number. + + Parameters: + + theta - A number angle property. + rho - A number rho property. + + */ + setp: function(theta, rho) { + this.theta = theta; + this.rho = rho; + }, + + /* + Method: clone + + Returns a copy of the current object. + + Returns: + + A copy of the real object. + */ + clone: function() { + return new Polar(this.theta, this.rho); + }, + + /* + Method: toComplex + + Translates from polar to cartesian coordinates and returns a new instance. + + Parameters: + + simple - _optional_ If *true* this method will only return an object with x and y properties (and not the whole instance). Default's *false*. + + Returns: + + A new instance. + */ + toComplex: function(simple) { + var x = Math.cos(this.theta) * this.rho; + var y = Math.sin(this.theta) * this.rho; + if(simple) return { 'x': x, 'y': y}; + return new Complex(x, y); + }, + + /* + Method: add + + Adds two instances. + + Parameters: + + polar - A number. + + Returns: + + A new Polar instance. + */ + add: function(polar) { + return new Polar(this.theta + polar.theta, this.rho + polar.rho); + }, + + /* + Method: scale + + Scales a polar norm. + + Parameters: + + number - A scale factor. + + Returns: + + A new Polar instance. + */ + scale: function(number) { + return new Polar(this.theta, this.rho * number); + }, + + /* + Method: equals + + Comparison method. + + Returns *true* if the theta and rho properties are equal. + + Parameters: + + c - A number. + + Returns: + + *true* if the theta and rho parameters for these objects are equal. *false* otherwise. + */ + equals: function(c) { + return this.theta == c.theta && this.rho == c.rho; + }, + + /* + Method: $add + + Adds two instances affecting the current object. + + Paramters: + + polar - A instance. + + Returns: + + The changed object. + */ + $add: function(polar) { + this.theta = this.theta + polar.theta; this.rho += polar.rho; + return this; + }, + + /* + Method: $madd + + Adds two instances affecting the current object. The resulting theta angle is modulo 2pi. + + Parameters: + + polar - A instance. + + Returns: + + The changed object. + */ + $madd: function(polar) { + this.theta = (this.theta + polar.theta) % (Math.PI * 2); this.rho += polar.rho; + return this; + }, + + + /* + Method: $scale + + Scales a polar instance affecting the object. + + Parameters: + + number - A scaling factor. + + Returns: + + The changed object. + */ + $scale: function(number) { + this.rho *= number; + return this; + }, + + /* + Method: isZero + + Returns *true* if the number is zero. + + */ + isZero: function () { + var almostZero = 0.0001, abs = Math.abs; + return abs(this.theta) < almostZero && abs(this.rho) < almostZero; + }, + + /* + Method: interpolate + + Calculates a polar interpolation between two points at a given delta moment. + + Parameters: + + elem - A instance. + delta - A delta factor ranging [0, 1]. + + Returns: + + A new instance representing an interpolation between _this_ and _elem_ + */ + interpolate: function(elem, delta) { + var pi = Math.PI, pi2 = pi * 2; + var ch = function(t) { + var a = (t < 0)? (t % pi2) + pi2 : t % pi2; + return a; + }; + var tt = this.theta, et = elem.theta; + var sum, diff = Math.abs(tt - et); + if(diff == pi) { + if(tt > et) { + sum = ch((et + ((tt - pi2) - et) * delta)) ; + } else { + sum = ch((et - pi2 + (tt - (et)) * delta)); + } + } else if(diff >= pi) { + if(tt > et) { + sum = ch((et + ((tt - pi2) - et) * delta)) ; + } else { + sum = ch((et - pi2 + (tt - (et - pi2)) * delta)); + } + } else { + sum = ch((et + (tt - et) * delta)) ; + } + var r = (this.rho - elem.rho) * delta + elem.rho; + return { + 'theta': sum, + 'rho': r + }; + } +}; + + +var $P = function(a, b) { return new Polar(a, b); }; + +Polar.KER = $P(0, 0); + + + +/* + * File: Complex.js + * + * Defines the class. + * + * Description: + * + * The class, just like the class, is used by the , and as a 2D point representation. + * + * See also: + * + * + * +*/ + +/* + Class: Complex + + A multi-purpose Complex Class with common methods. + + Description: + + The class, just like the class, is used by the , and as a 2D point representation. + + See also: + + + + Parameters: + + x - _optional_ A Complex number real part. + y - _optional_ A Complex number imaginary part. + +*/ + +var Complex = function(x, y) { + this.x = x || 0; + this.y = y || 0; +}; + +$jit.Complex = Complex; + +Complex.prototype = { + /* + Method: getc + + Returns a complex number. + + Returns: + + A complex number. + */ + getc: function() { + return this; + }, + + /* + Method: getp + + Returns a representation of this number. + + Parameters: + + simple - _optional_ If *true*, this method will return only an object holding theta and rho properties and not a instance. Default's *false*. + + Returns: + + A variable in coordinates. + */ + getp: function(simple) { + return this.toPolar(simple); + }, + + + /* + Method: set + + Sets a number. + + Parameters: + + c - A or instance. + + */ + set: function(c) { + c = c.getc(true); + this.x = c.x; + this.y = c.y; + }, + + /* + Method: setc + + Sets a complex number. + + Parameters: + + x - A number Real part. + y - A number Imaginary part. + + */ + setc: function(x, y) { + this.x = x; + this.y = y; + }, + + /* + Method: setp + + Sets a polar number. + + Parameters: + + theta - A number theta property. + rho - A number rho property. + + */ + setp: function(theta, rho) { + this.x = Math.cos(theta) * rho; + this.y = Math.sin(theta) * rho; + }, + + /* + Method: clone + + Returns a copy of the current object. + + Returns: + + A copy of the real object. + */ + clone: function() { + return new Complex(this.x, this.y); + }, + + /* + Method: toPolar + + Transforms cartesian to polar coordinates. + + Parameters: + + simple - _optional_ If *true* this method will only return an object with theta and rho properties (and not the whole instance). Default's *false*. + + Returns: + + A new instance. + */ + + toPolar: function(simple) { + var rho = this.norm(); + var atan = Math.atan2(this.y, this.x); + if(atan < 0) atan += Math.PI * 2; + if(simple) return { 'theta': atan, 'rho': rho }; + return new Polar(atan, rho); + }, + /* + Method: norm + + Calculates a number norm. + + Returns: + + A real number representing the complex norm. + */ + norm: function () { + return Math.sqrt(this.squaredNorm()); + }, + + /* + Method: squaredNorm + + Calculates a number squared norm. + + Returns: + + A real number representing the complex squared norm. + */ + squaredNorm: function () { + return this.x*this.x + this.y*this.y; + }, + + /* + Method: add + + Returns the result of adding two complex numbers. + + Does not alter the original object. + + Parameters: + + pos - A instance. + + Returns: + + The result of adding two complex numbers. + */ + add: function(pos) { + return new Complex(this.x + pos.x, this.y + pos.y); + }, + + /* + Method: prod + + Returns the result of multiplying two numbers. + + Does not alter the original object. + + Parameters: + + pos - A instance. + + Returns: + + The result of multiplying two complex numbers. + */ + prod: function(pos) { + return new Complex(this.x*pos.x - this.y*pos.y, this.y*pos.x + this.x*pos.y); + }, + + /* + Method: conjugate + + Returns the conjugate of this number. + + Does not alter the original object. + + Returns: + + The conjugate of this number. + */ + conjugate: function() { + return new Complex(this.x, -this.y); + }, + + + /* + Method: scale + + Returns the result of scaling a instance. + + Does not alter the original object. + + Parameters: + + factor - A scale factor. + + Returns: + + The result of scaling this complex to a factor. + */ + scale: function(factor) { + return new Complex(this.x * factor, this.y * factor); + }, + + /* + Method: equals + + Comparison method. + + Returns *true* if both real and imaginary parts are equal. + + Parameters: + + c - A instance. + + Returns: + + A boolean instance indicating if both numbers are equal. + */ + equals: function(c) { + return this.x == c.x && this.y == c.y; + }, + + /* + Method: $add + + Returns the result of adding two numbers. + + Alters the original object. + + Parameters: + + pos - A instance. + + Returns: + + The result of adding two complex numbers. + */ + $add: function(pos) { + this.x += pos.x; this.y += pos.y; + return this; + }, + + /* + Method: $prod + + Returns the result of multiplying two numbers. + + Alters the original object. + + Parameters: + + pos - A instance. + + Returns: + + The result of multiplying two complex numbers. + */ + $prod:function(pos) { + var x = this.x, y = this.y; + this.x = x*pos.x - y*pos.y; + this.y = y*pos.x + x*pos.y; + return this; + }, + + /* + Method: $conjugate + + Returns the conjugate for this . + + Alters the original object. + + Returns: + + The conjugate for this complex. + */ + $conjugate: function() { + this.y = -this.y; + return this; + }, + + /* + Method: $scale + + Returns the result of scaling a instance. + + Alters the original object. + + Parameters: + + factor - A scale factor. + + Returns: + + The result of scaling this complex to a factor. + */ + $scale: function(factor) { + this.x *= factor; this.y *= factor; + return this; + }, + + /* + Method: $div + + Returns the division of two numbers. + + Alters the original object. + + Parameters: + + pos - A number. + + Returns: + + The result of scaling this complex to a factor. + */ + $div: function(pos) { + var x = this.x, y = this.y; + var sq = pos.squaredNorm(); + this.x = x * pos.x + y * pos.y; this.y = y * pos.x - x * pos.y; + return this.$scale(1 / sq); + }, + + /* + Method: isZero + + Returns *true* if the number is zero. + + */ + isZero: function () { + var almostZero = 0.0001, abs = Math.abs; + return abs(this.x) < almostZero && abs(this.y) < almostZero; + } +}; + +var $C = function(a, b) { return new Complex(a, b); }; + +Complex.KER = $C(0, 0); + + + +/* + * File: Graph.js + * +*/ + +/* + Class: Graph + + A Graph Class that provides useful manipulation functions. You can find more manipulation methods in the object. + + An instance of this class can be accessed by using the *graph* parameter of any tree or graph visualization. + + Example: + + (start code js) + //create new visualization + var viz = new $jit.Viz(options); + //load JSON data + viz.loadJSON(json); + //access model + viz.graph; // instance + (end code) + + Implements: + + The following methods are implemented in + + - + - + - + - + - + - + - + +*/ + +$jit.Graph = new Class({ + + initialize: function(opt, Node, Edge, Label) { + var innerOptions = { + 'klass': Complex, + 'Node': {} + }; + this.Node = Node; + this.Edge = Edge; + this.Label = Label; + this.opt = $.merge(innerOptions, opt || {}); + this.nodes = {}; + this.edges = {}; + + //add nodeList methods + var that = this; + this.nodeList = {}; + for(var p in Accessors) { + that.nodeList[p] = (function(p) { + return function() { + var args = Array.prototype.slice.call(arguments); + that.eachNode(function(n) { + n[p].apply(n, args); + }); + }; + })(p); + } + + }, + +/* + Method: getNode + + Returns a by *id*. + + Parameters: + + id - (string) A id. + + Example: + + (start code js) + var node = graph.getNode('nodeId'); + (end code) +*/ + getNode: function(id) { + if(this.hasNode(id)) return this.nodes[id]; + return false; + }, + + /* + Method: get + + An alias for . Returns a node by *id*. + + Parameters: + + id - (string) A id. + + Example: + + (start code js) + var node = graph.get('nodeId'); + (end code) +*/ + get: function(id) { + return this.getNode(id); + }, + + /* + Method: getByName + + Returns a by *name*. + + Parameters: + + name - (string) A name. + + Example: + + (start code js) + var node = graph.getByName('someName'); + (end code) + */ + getByName: function(name) { + for(var id in this.nodes) { + var n = this.nodes[id]; + if(n.name == name) return n; + } + return false; + }, + +/* + Method: getAdjacence + + Returns a object connecting nodes with ids *id* and *id2*. + + Parameters: + + id - (string) A id. + id2 - (string) A id. +*/ + getAdjacence: function (id, id2) { + if(id in this.edges) { + return this.edges[id][id2]; + } + return false; + }, + + /* + Method: addNode + + Adds a node. + + Parameters: + + obj - An object with the properties described below + + id - (string) A node id + name - (string) A node's name + data - (object) A node's data hash + + See also: + + + */ + addNode: function(obj) { + if(!this.nodes[obj.id]) { + var edges = this.edges[obj.id] = {}; + this.nodes[obj.id] = new Graph.Node($.extend({ + 'id': obj.id, + 'name': obj.name, + 'data': $.merge(obj.data || {}, {}), + 'adjacencies': edges + }, this.opt.Node), + this.opt.klass, + this.Node, + this.Edge, + this.Label); + } + return this.nodes[obj.id]; + }, + + /* + Method: addAdjacence + + Connects nodes specified by *obj* and *obj2*. If not found, nodes are created. + + Parameters: + + obj - (object) A object. + obj2 - (object) Another object. + data - (object) A data object. Used to store some extra information in the object created. + + See also: + + , + */ + addAdjacence: function (obj, obj2, data) { + if(!this.hasNode(obj.id)) { this.addNode(obj); } + if(!this.hasNode(obj2.id)) { this.addNode(obj2); } + obj = this.nodes[obj.id]; obj2 = this.nodes[obj2.id]; + if(!obj.adjacentTo(obj2)) { + var adjsObj = this.edges[obj.id] = this.edges[obj.id] || {}; + var adjsObj2 = this.edges[obj2.id] = this.edges[obj2.id] || {}; + adjsObj[obj2.id] = adjsObj2[obj.id] = new Graph.Adjacence(obj, obj2, data, this.Edge, this.Label); + return adjsObj[obj2.id]; + } + return this.edges[obj.id][obj2.id]; + }, + + /* + Method: removeNode + + Removes a matching the specified *id*. + + Parameters: + + id - (string) A node's id. + + */ + removeNode: function(id) { + if(this.hasNode(id)) { + delete this.nodes[id]; + var adjs = this.edges[id]; + for(var to in adjs) { + delete this.edges[to][id]; + } + delete this.edges[id]; + } + }, + +/* + Method: removeAdjacence + + Removes a matching *id1* and *id2*. + + Parameters: + + id1 - (string) A id. + id2 - (string) A id. +*/ + removeAdjacence: function(id1, id2) { + delete this.edges[id1][id2]; + delete this.edges[id2][id1]; + }, + + /* + Method: hasNode + + Returns a boolean indicating if the node belongs to the or not. + + Parameters: + + id - (string) Node id. + */ + hasNode: function(id) { + return id in this.nodes; + }, + + /* + Method: empty + + Empties the Graph + + */ + empty: function() { this.nodes = {}; this.edges = {};} + +}); + +var Graph = $jit.Graph; + +/* + Object: Accessors + + Defines a set of methods for data, canvas and label styles manipulation implemented by and instances. + + */ +var Accessors; + +(function () { + var getDataInternal = function(prefix, prop, type, force, prefixConfig) { + var data; + type = type || 'current'; + prefix = "$" + (prefix ? prefix + "-" : ""); + + if(type == 'current') { + data = this.data; + } else if(type == 'start') { + data = this.startData; + } else if(type == 'end') { + data = this.endData; + } + + var dollar = prefix + prop; + + if(force) { + return data[dollar]; + } + + if(!this.Config.overridable) + return prefixConfig[prop] || 0; + + return (dollar in data) ? + data[dollar] : ((dollar in this.data) ? this.data[dollar] : (prefixConfig[prop] || 0)); + } + + var setDataInternal = function(prefix, prop, value, type) { + type = type || 'current'; + prefix = '$' + (prefix ? prefix + '-' : ''); + + var data; + + if(type == 'current') { + data = this.data; + } else if(type == 'start') { + data = this.startData; + } else if(type == 'end') { + data = this.endData; + } + + data[prefix + prop] = value; + } + + var removeDataInternal = function(prefix, properties) { + prefix = '$' + (prefix ? prefix + '-' : ''); + var that = this; + $.each(properties, function(prop) { + var pref = prefix + prop; + delete that.data[pref]; + delete that.endData[pref]; + delete that.startData[pref]; + }); + } + + Accessors = { + /* + Method: getData + + Returns the specified data value property. + This is useful for querying special/reserved data properties + (i.e dollar prefixed properties). + + Parameters: + + prop - (string) The name of the property. The dollar sign is not needed. For + example *getData(width)* will return *data.$width*. + type - (string) The type of the data property queried. Default's "current". You can access *start* and *end* + data properties also. These properties are used when making animations. + force - (boolean) Whether to obtain the true value of the property (equivalent to + *data.$prop*) or to check for *node.overridable = true* first. + + Returns: + + The value of the dollar prefixed property or the global Node/Edge property + value if *overridable=false* + + Example: + (start code js) + node.getData('width'); //will return node.data.$width if Node.overridable=true; + (end code) + */ + getData: function(prop, type, force) { + return getDataInternal.call(this, "", prop, type, force, this.Config); + }, + + + /* + Method: setData + + Sets the current data property with some specific value. + This method is only useful for reserved (dollar prefixed) properties. + + Parameters: + + prop - (string) The name of the property. The dollar sign is not necessary. For + example *setData(width)* will set *data.$width*. + value - (mixed) The value to store. + type - (string) The type of the data property to store. Default's "current" but + can also be "start" or "end". + + Example: + + (start code js) + node.setData('width', 30); + (end code) + + If we were to make an animation of a node/edge width then we could do + + (start code js) + var node = viz.getNode('nodeId'); + //set start and end values + node.setData('width', 10, 'start'); + node.setData('width', 30, 'end'); + //will animate nodes width property + viz.fx.animate({ + modes: ['node-property:width'], + duration: 1000 + }); + (end code) + */ + setData: function(prop, value, type) { + setDataInternal.call(this, "", prop, value, type); + }, + + /* + Method: setDataset + + Convenience method to set multiple data values at once. + + Parameters: + + types - (array|string) A set of 'current', 'end' or 'start' values. + obj - (object) A hash containing the names and values of the properties to be altered. + + Example: + (start code js) + node.setDataset(['current', 'end'], { + 'width': [100, 5], + 'color': ['#fff', '#ccc'] + }); + //...or also + node.setDataset('end', { + 'width': 5, + 'color': '#ccc' + }); + (end code) + + See also: + + + + */ + setDataset: function(types, obj) { + types = $.splat(types); + for(var attr in obj) { + for(var i=0, val = $.splat(obj[attr]), l=types.length; i canvas style data properties (i.e. + dollar prefixed properties that match with $canvas-). + + Parameters: + + prop - (string) The name of the property. The dollar sign is not needed. For + example *getCanvasStyle(shadowBlur)* will return *data[$canvas-shadowBlur]*. + type - (string) The type of the data property queried. Default's *current*. You can access *start* and *end* + data properties also. + + Example: + (start code js) + node.getCanvasStyle('shadowBlur'); + (end code) + + See also: + + + */ + getCanvasStyle: function(prop, type, force) { + return getDataInternal.call( + this, 'canvas', prop, type, force, this.Config.CanvasStyles); + }, + + /* + Method: setCanvasStyle + + Sets the canvas style data property with some specific value. + This method is only useful for reserved (dollar prefixed) properties. + + Parameters: + + prop - (string) Name of the property. Can be any canvas property like 'shadowBlur', 'shadowColor', 'strokeStyle', etc. + value - (mixed) The value to set to the property. + type - (string) Default's *current*. Whether to set *start*, *current* or *end* type properties. + + Example: + + (start code js) + node.setCanvasStyle('shadowBlur', 30); + (end code) + + If we were to make an animation of a node/edge shadowBlur canvas style then we could do + + (start code js) + var node = viz.getNode('nodeId'); + //set start and end values + node.setCanvasStyle('shadowBlur', 10, 'start'); + node.setCanvasStyle('shadowBlur', 30, 'end'); + //will animate nodes canvas style property for nodes + viz.fx.animate({ + modes: ['node-style:shadowBlur'], + duration: 1000 + }); + (end code) + + See also: + + . + */ + setCanvasStyle: function(prop, value, type) { + setDataInternal.call(this, 'canvas', prop, value, type); + }, + + /* + Method: setCanvasStyles + + Convenience method to set multiple styles at once. + + Parameters: + + types - (array|string) A set of 'current', 'end' or 'start' values. + obj - (object) A hash containing the names and values of the properties to be altered. + + See also: + + . + */ + setCanvasStyles: function(types, obj) { + types = $.splat(types); + for(var attr in obj) { + for(var i=0, val = $.splat(obj[attr]), l=types.length; i. + */ + removeCanvasStyle: function() { + removeDataInternal.call(this, 'canvas', Array.prototype.slice.call(arguments)); + }, + + /* + Method: getLabelData + + Returns the specified label data value property. This is useful for + querying special/reserved label options (i.e. + dollar prefixed properties that match with $label-). + + Parameters: + + prop - (string) The name of the property. The dollar sign prefix is not needed. For + example *getLabelData(size)* will return *data[$label-size]*. + type - (string) The type of the data property queried. Default's *current*. You can access *start* and *end* + data properties also. + + See also: + + . + */ + getLabelData: function(prop, type, force) { + return getDataInternal.call( + this, 'label', prop, type, force, this.Label); + }, + + /* + Method: setLabelData + + Sets the current label data with some specific value. + This method is only useful for reserved (dollar prefixed) properties. + + Parameters: + + prop - (string) Name of the property. Can be any canvas property like 'shadowBlur', 'shadowColor', 'strokeStyle', etc. + value - (mixed) The value to set to the property. + type - (string) Default's *current*. Whether to set *start*, *current* or *end* type properties. + + Example: + + (start code js) + node.setLabelData('size', 30); + (end code) + + If we were to make an animation of a node label size then we could do + + (start code js) + var node = viz.getNode('nodeId'); + //set start and end values + node.setLabelData('size', 10, 'start'); + node.setLabelData('size', 30, 'end'); + //will animate nodes label size + viz.fx.animate({ + modes: ['label-property:size'], + duration: 1000 + }); + (end code) + + See also: + + . + */ + setLabelData: function(prop, value, type) { + setDataInternal.call(this, 'label', prop, value, type); + }, + + /* + Method: setLabelDataset + + Convenience function to set multiple label data at once. + + Parameters: + + types - (array|string) A set of 'current', 'end' or 'start' values. + obj - (object) A hash containing the names and values of the properties to be altered. + + See also: + + . + */ + setLabelDataset: function(types, obj) { + types = $.splat(types); + for(var attr in obj) { + for(var i=0, val = $.splat(obj[attr]), l=types.length; i. + */ + removeLabelData: function() { + removeDataInternal.call(this, 'label', Array.prototype.slice.call(arguments)); + } + }; +})(); + +/* + Class: Graph.Node + + A node. + + Implements: + + methods. + + The following methods are implemented by + + - + - + - + - + - + - + - + - +*/ +Graph.Node = new Class({ + + initialize: function(opt, klass, Node, Edge, Label) { + var innerOptions = { + 'id': '', + 'name': '', + 'data': {}, + 'startData': {}, + 'endData': {}, + 'adjacencies': {}, + + 'selected': false, + 'drawn': false, + 'exist': false, + + 'angleSpan': { + 'begin': 0, + 'end' : 0 + }, + + 'pos': new klass, + 'startPos': new klass, + 'endPos': new klass + }; + + $.extend(this, $.extend(innerOptions, opt)); + this.Config = this.Node = Node; + this.Edge = Edge; + this.Label = Label; + }, + + /* + Method: adjacentTo + + Indicates if the node is adjacent to the node specified by id + + Parameters: + + id - (string) A node id. + + Example: + (start code js) + node.adjacentTo('nodeId') == true; + (end code) + */ + adjacentTo: function(node) { + return node.id in this.adjacencies; + }, + + /* + Method: getAdjacency + + Returns a object connecting the current and the node having *id* as id. + + Parameters: + + id - (string) A node id. + */ + getAdjacency: function(id) { + return this.adjacencies[id]; + }, + + /* + Method: getPos + + Returns the position of the node. + + Parameters: + + type - (string) Default's *current*. Possible values are "start", "end" or "current". + + Returns: + + A or instance. + + Example: + (start code js) + var pos = node.getPos('end'); + (end code) + */ + getPos: function(type) { + type = type || "current"; + if(type == "current") { + return this.pos; + } else if(type == "end") { + return this.endPos; + } else if(type == "start") { + return this.startPos; + } + }, + /* + Method: setPos + + Sets the node's position. + + Parameters: + + value - (object) A or instance. + type - (string) Default's *current*. Possible values are "start", "end" or "current". + + Example: + (start code js) + node.setPos(new $jit.Complex(0, 0), 'end'); + (end code) + */ + setPos: function(value, type) { + type = type || "current"; + var pos; + if(type == "current") { + pos = this.pos; + } else if(type == "end") { + pos = this.endPos; + } else if(type == "start") { + pos = this.startPos; + } + pos.set(value); + } +}); + +Graph.Node.implement(Accessors); + +/* + Class: Graph.Adjacence + + A adjacence (or edge) connecting two . + + Implements: + + methods. + + See also: + + , + + Properties: + + nodeFrom - A connected by this edge. + nodeTo - Another connected by this edge. + data - Node data property containing a hash (i.e {}) with custom options. +*/ +Graph.Adjacence = new Class({ + + initialize: function(nodeFrom, nodeTo, data, Edge, Label) { + this.nodeFrom = nodeFrom; + this.nodeTo = nodeTo; + this.data = data || {}; + this.startData = {}; + this.endData = {}; + this.Config = this.Edge = Edge; + this.Label = Label; + } +}); + +Graph.Adjacence.implement(Accessors); + +/* + Object: Graph.Util + + traversal and processing utility object. + + Note: + + For your convenience some of these methods have also been appended to and classes. +*/ +Graph.Util = { + /* + filter + + For internal use only. Provides a filtering function based on flags. + */ + filter: function(param) { + if(!param || !($.type(param) == 'string')) return function() { return true; }; + var props = param.split(" "); + return function(elem) { + for(var i=0; i by *id*. + + Also implemented by: + + + + Parameters: + + graph - (object) A instance. + id - (string) A id. + + Example: + + (start code js) + $jit.Graph.Util.getNode(graph, 'nodeid'); + //or... + graph.getNode('nodeid'); + (end code) + */ + getNode: function(graph, id) { + return graph.nodes[id]; + }, + + /* + Method: eachNode + + Iterates over nodes performing an *action*. + + Also implemented by: + + . + + Parameters: + + graph - (object) A instance. + action - (function) A callback function having a as first formal parameter. + + Example: + (start code js) + $jit.Graph.Util.eachNode(graph, function(node) { + alert(node.name); + }); + //or... + graph.eachNode(function(node) { + alert(node.name); + }); + (end code) + */ + eachNode: function(graph, action, flags) { + var filter = this.filter(flags); + for(var i in graph.nodes) { + if(filter(graph.nodes[i])) action(graph.nodes[i]); + } + }, + + /* + Method: each + + Iterates over nodes performing an *action*. It's an alias for . + + Also implemented by: + + . + + Parameters: + + graph - (object) A instance. + action - (function) A callback function having a as first formal parameter. + + Example: + (start code js) + $jit.Graph.Util.each(graph, function(node) { + alert(node.name); + }); + //or... + graph.each(function(node) { + alert(node.name); + }); + (end code) + */ + each: function(graph, action, flags) { + this.eachNode(graph, action, flags); + }, + + /* + Method: eachAdjacency + + Iterates over adjacencies applying the *action* function. + + Also implemented by: + + . + + Parameters: + + node - (object) A . + action - (function) A callback function having as first formal parameter. + + Example: + (start code js) + $jit.Graph.Util.eachAdjacency(node, function(adj) { + alert(adj.nodeTo.name); + }); + //or... + node.eachAdjacency(function(adj) { + alert(adj.nodeTo.name); + }); + (end code) + */ + eachAdjacency: function(node, action, flags) { + var adj = node.adjacencies, filter = this.filter(flags); + for(var id in adj) { + var a = adj[id]; + if(filter(a)) { + if(a.nodeFrom != node) { + var tmp = a.nodeFrom; + a.nodeFrom = a.nodeTo; + a.nodeTo = tmp; + } + action(a, id); + } + } + }, + + /* + Method: computeLevels + + Performs a BFS traversal setting the correct depth for each node. + + Also implemented by: + + . + + Note: + + The depth of each node can then be accessed by + >node._depth + + Parameters: + + graph - (object) A . + id - (string) A starting node id for the BFS traversal. + startDepth - (optional|number) A minimum depth value. Default's 0. + + */ + computeLevels: function(graph, id, startDepth, flags) { + startDepth = startDepth || 0; + var filter = this.filter(flags); + this.eachNode(graph, function(elem) { + elem._flag = false; + elem._depth = -1; + }, flags); + var root = graph.getNode(id); + root._depth = startDepth; + var queue = [root]; + while(queue.length != 0) { + var node = queue.pop(); + node._flag = true; + this.eachAdjacency(node, function(adj) { + var n = adj.nodeTo; + if(n._flag == false && filter(n)) { + if(n._depth < 0) n._depth = node._depth + 1 + startDepth; + queue.unshift(n); + } + }, flags); + } + }, + + /* + Method: eachBFS + + Performs a BFS traversal applying *action* to each . + + Also implemented by: + + . + + Parameters: + + graph - (object) A . + id - (string) A starting node id for the BFS traversal. + action - (function) A callback function having a as first formal parameter. + + Example: + (start code js) + $jit.Graph.Util.eachBFS(graph, 'mynodeid', function(node) { + alert(node.name); + }); + //or... + graph.eachBFS('mynodeid', function(node) { + alert(node.name); + }); + (end code) + */ + eachBFS: function(graph, id, action, flags) { + var filter = this.filter(flags); + this.clean(graph); + var queue = [graph.getNode(id)]; + while(queue.length != 0) { + var node = queue.pop(); + node._flag = true; + action(node, node._depth); + this.eachAdjacency(node, function(adj) { + var n = adj.nodeTo; + if(n._flag == false && filter(n)) { + n._flag = true; + queue.unshift(n); + } + }, flags); + } + }, + + /* + Method: eachLevel + + Iterates over a node's subgraph applying *action* to the nodes of relative depth between *levelBegin* and *levelEnd*. + + Also implemented by: + + . + + Parameters: + + node - (object) A . + levelBegin - (number) A relative level value. + levelEnd - (number) A relative level value. + action - (function) A callback function having a as first formal parameter. + + */ + eachLevel: function(node, levelBegin, levelEnd, action, flags) { + var d = node._depth, filter = this.filter(flags), that = this; + levelEnd = levelEnd === false? Number.MAX_VALUE -d : levelEnd; + (function loopLevel(node, levelBegin, levelEnd) { + var d = node._depth; + if(d >= levelBegin && d <= levelEnd && filter(node)) action(node, d); + if(d < levelEnd) { + that.eachAdjacency(node, function(adj) { + var n = adj.nodeTo; + if(n._depth > d) loopLevel(n, levelBegin, levelEnd); + }); + } + })(node, levelBegin + d, levelEnd + d); + }, + + /* + Method: eachSubgraph + + Iterates over a node's children recursively. + + Also implemented by: + + . + + Parameters: + node - (object) A . + action - (function) A callback function having a as first formal parameter. + + Example: + (start code js) + $jit.Graph.Util.eachSubgraph(node, function(node) { + alert(node.name); + }); + //or... + node.eachSubgraph(function(node) { + alert(node.name); + }); + (end code) + */ + eachSubgraph: function(node, action, flags) { + this.eachLevel(node, 0, false, action, flags); + }, + + /* + Method: eachSubnode + + Iterates over a node's children (without deeper recursion). + + Also implemented by: + + . + + Parameters: + node - (object) A . + action - (function) A callback function having a as first formal parameter. + + Example: + (start code js) + $jit.Graph.Util.eachSubnode(node, function(node) { + alert(node.name); + }); + //or... + node.eachSubnode(function(node) { + alert(node.name); + }); + (end code) + */ + eachSubnode: function(node, action, flags) { + this.eachLevel(node, 1, 1, action, flags); + }, + + /* + Method: anySubnode + + Returns *true* if any subnode matches the given condition. + + Also implemented by: + + . + + Parameters: + node - (object) A . + cond - (function) A callback function returning a Boolean instance. This function has as first formal parameter a . + + Example: + (start code js) + $jit.Graph.Util.anySubnode(node, function(node) { return node.name == "mynodename"; }); + //or... + node.anySubnode(function(node) { return node.name == 'mynodename'; }); + (end code) + */ + anySubnode: function(node, cond, flags) { + var flag = false; + cond = cond || $.lambda(true); + var c = $.type(cond) == 'string'? function(n) { return n[cond]; } : cond; + this.eachSubnode(node, function(elem) { + if(c(elem)) flag = true; + }, flags); + return flag; + }, + + /* + Method: getSubnodes + + Collects all subnodes for a specified node. + The *level* parameter filters nodes having relative depth of *level* from the root node. + + Also implemented by: + + . + + Parameters: + node - (object) A . + level - (optional|number) Default's *0*. A starting relative depth for collecting nodes. + + Returns: + An array of nodes. + + */ + getSubnodes: function(node, level, flags) { + var ans = [], that = this; + level = level || 0; + var levelStart, levelEnd; + if($.type(level) == 'array') { + levelStart = level[0]; + levelEnd = level[1]; + } else { + levelStart = level; + levelEnd = Number.MAX_VALUE - node._depth; + } + this.eachLevel(node, levelStart, levelEnd, function(n) { + ans.push(n); + }, flags); + return ans; + }, + + + /* + Method: getParents + + Returns an Array of which are parents of the given node. + + Also implemented by: + + . + + Parameters: + node - (object) A . + + Returns: + An Array of . + + Example: + (start code js) + var pars = $jit.Graph.Util.getParents(node); + //or... + var pars = node.getParents(); + + if(pars.length > 0) { + //do stuff with parents + } + (end code) + */ + getParents: function(node) { + var ans = []; + this.eachAdjacency(node, function(adj) { + var n = adj.nodeTo; + if(n._depth < node._depth) ans.push(n); + }); + return ans; + }, + + /* + Method: isDescendantOf + + Returns a boolean indicating if some node is descendant of the node with the given id. + + Also implemented by: + + . + + + Parameters: + node - (object) A . + id - (string) A id. + + Example: + (start code js) + $jit.Graph.Util.isDescendantOf(node, "nodeid"); //true|false + //or... + node.isDescendantOf('nodeid');//true|false + (end code) + */ + isDescendantOf: function(node, id) { + if(node.id == id) return true; + var pars = this.getParents(node), ans = false; + for ( var i = 0; !ans && i < pars.length; i++) { + ans = ans || this.isDescendantOf(pars[i], id); + } + return ans; + }, + + /* + Method: clean + + Cleans flags from nodes. + + Also implemented by: + + . + + Parameters: + graph - A instance. + */ + clean: function(graph) { this.eachNode(graph, function(elem) { elem._flag = false; }); }, + + /* + Method: getClosestNodeToOrigin + + Returns the closest node to the center of canvas. + + Also implemented by: + + . + + Parameters: + + graph - (object) A instance. + prop - (optional|string) Default's 'current'. A position property. Possible properties are 'start', 'current' or 'end'. + + */ + getClosestNodeToOrigin: function(graph, prop, flags) { + return this.getClosestNodeToPos(graph, Polar.KER, prop, flags); + }, + + /* + Method: getClosestNodeToPos + + Returns the closest node to the given position. + + Also implemented by: + + . + + Parameters: + + graph - (object) A instance. + pos - (object) A or instance. + prop - (optional|string) Default's *current*. A position property. Possible properties are 'start', 'current' or 'end'. + + */ + getClosestNodeToPos: function(graph, pos, prop, flags) { + var node = null; + prop = prop || 'current'; + pos = pos && pos.getc(true) || Complex.KER; + var distance = function(a, b) { + var d1 = a.x - b.x, d2 = a.y - b.y; + return d1 * d1 + d2 * d2; + }; + this.eachNode(graph, function(elem) { + node = (node == null || distance(elem.getPos(prop).getc(true), pos) < distance( + node.getPos(prop).getc(true), pos)) ? elem : node; + }, flags); + return node; + } +}; + +//Append graph methods to +$.each(['get', 'getNode', 'each', 'eachNode', 'computeLevels', 'eachBFS', 'clean', 'getClosestNodeToPos', 'getClosestNodeToOrigin'], function(m) { + Graph.prototype[m] = function() { + return Graph.Util[m].apply(Graph.Util, [this].concat(Array.prototype.slice.call(arguments))); + }; +}); + +//Append node methods to +$.each(['eachAdjacency', 'eachLevel', 'eachSubgraph', 'eachSubnode', 'anySubnode', 'getSubnodes', 'getParents', 'isDescendantOf'], function(m) { + Graph.Node.prototype[m] = function() { + return Graph.Util[m].apply(Graph.Util, [this].concat(Array.prototype.slice.call(arguments))); + }; +}); + +/* + * File: Graph.Op.js + * +*/ + +/* + Object: Graph.Op + + Perform operations like adding/removing or , + morphing a into another , contracting or expanding subtrees, etc. + +*/ +Graph.Op = { + + options: { + type: 'nothing', + duration: 2000, + hideLabels: true, + fps:30 + }, + + initialize: function(viz) { + this.viz = viz; + }, + + /* + Method: removeNode + + Removes one or more from the visualization. + It can also perform several animations like fading sequentially, fading concurrently, iterating or replotting. + + Parameters: + + node - (string|array) The node's id. Can also be an array having many ids. + opt - (object) Animation options. It's an object with optional properties described below + type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con" or "iter". + duration - Described in . + fps - Described in . + transition - Described in . + hideLabels - (boolean) Default's *true*. Hide labels during the animation. + + Example: + (start code js) + var viz = new $jit.Viz(options); + viz.op.removeNode('nodeId', { + type: 'fade:seq', + duration: 1000, + hideLabels: false, + transition: $jit.Trans.Quart.easeOut + }); + //or also + viz.op.removeNode(['someId', 'otherId'], { + type: 'fade:con', + duration: 1500 + }); + (end code) + */ + + removeNode: function(node, opt) { + var viz = this.viz; + var options = $.merge(this.options, viz.controller, opt); + var n = $.splat(node); + var i, that, nodeObj; + switch(options.type) { + case 'nothing': + for(i=0; i from the visualization. + It can also perform several animations like fading sequentially, fading concurrently, iterating or replotting. + + Parameters: + + vertex - (array) An array having two strings which are the ids of the nodes connected by this edge (i.e ['id1', 'id2']). Can also be a two dimensional array holding many edges (i.e [['id1', 'id2'], ['id3', 'id4'], ...]). + opt - (object) Animation options. It's an object with optional properties described below + type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con" or "iter". + duration - Described in . + fps - Described in . + transition - Described in . + hideLabels - (boolean) Default's *true*. Hide labels during the animation. + + Example: + (start code js) + var viz = new $jit.Viz(options); + viz.op.removeEdge(['nodeId', 'otherId'], { + type: 'fade:seq', + duration: 1000, + hideLabels: false, + transition: $jit.Trans.Quart.easeOut + }); + //or also + viz.op.removeEdge([['someId', 'otherId'], ['id3', 'id4']], { + type: 'fade:con', + duration: 1500 + }); + (end code) + + */ + removeEdge: function(vertex, opt) { + var viz = this.viz; + var options = $.merge(this.options, viz.controller, opt); + var v = ($.type(vertex[0]) == 'string')? [vertex] : vertex; + var i, that, adj; + switch(options.type) { + case 'nothing': + for(i=0; i + + Parameters: + + json - (object) A json tree or graph structure. See also . + opt - (object) Animation options. It's an object with optional properties described below + type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con". + duration - Described in . + fps - Described in . + transition - Described in . + hideLabels - (boolean) Default's *true*. Hide labels during the animation. + + Example: + (start code js) + //...json contains a tree or graph structure... + + var viz = new $jit.Viz(options); + viz.op.sum(json, { + type: 'fade:seq', + duration: 1000, + hideLabels: false, + transition: $jit.Trans.Quart.easeOut + }); + //or also + viz.op.sum(json, { + type: 'fade:con', + duration: 1500 + }); + (end code) + + */ + sum: function(json, opt) { + var viz = this.viz; + var options = $.merge(this.options, viz.controller, opt), root = viz.root; + var graph; + viz.root = opt.id || viz.root; + switch(options.type) { + case 'nothing': + graph = viz.construct(json); + graph.eachNode(function(elem) { + elem.eachAdjacency(function(adj) { + viz.graph.addAdjacence(adj.nodeFrom, adj.nodeTo, adj.data); + }); + }); + break; + + case 'replot': + viz.refresh(true); + this.sum(json, { type: 'nothing' }); + viz.refresh(true); + break; + + case 'fade:seq': case 'fade': case 'fade:con': + that = this; + graph = viz.construct(json); + + //set alpha to 0 for nodes to add. + var fadeEdges = this.preprocessSum(graph); + var modes = !fadeEdges? ['node-property:alpha'] : ['node-property:alpha', 'edge-property:alpha']; + viz.reposition(); + if(options.type != 'fade:con') { + viz.fx.animate($.merge(options, { + modes: ['linear'], + onComplete: function() { + viz.fx.animate($.merge(options, { + modes: modes, + onComplete: function() { + options.onComplete(); + } + })); + } + })); + } else { + viz.graph.eachNode(function(elem) { + if (elem.id != root && elem.pos.isZero()) { + elem.pos.set(elem.endPos); + elem.startPos.set(elem.endPos); + } + }); + viz.fx.animate($.merge(options, { + modes: ['linear'].concat(modes) + })); + } + break; + + default: this.doError(); + } + }, + + /* + Method: morph + + This method will transform the current visualized graph into the new JSON representation passed in the method. + The JSON object must at least have the root node in common with the current visualized graph. + + Parameters: + + json - (object) A json tree or graph structure. See also . + opt - (object) Animation options. It's an object with optional properties described below + type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:con". + duration - Described in . + fps - Described in . + transition - Described in . + hideLabels - (boolean) Default's *true*. Hide labels during the animation. + id - (string) The shared id between both graphs. + + extraModes - (optional|object) When morphing with an animation, dollar prefixed data parameters are added to + *endData* and not *data* itself. This way you can animate dollar prefixed parameters during your morphing operation. + For animating these extra-parameters you have to specify an object that has animation groups as keys and animation + properties as values, just like specified in . + + Example: + (start code js) + //...json contains a tree or graph structure... + + var viz = new $jit.Viz(options); + viz.op.morph(json, { + type: 'fade', + duration: 1000, + hideLabels: false, + transition: $jit.Trans.Quart.easeOut + }); + //or also + viz.op.morph(json, { + type: 'fade', + duration: 1500 + }); + //if the json data contains dollar prefixed params + //like $width or $height these too can be animated + viz.op.morph(json, { + type: 'fade', + duration: 1500 + }, { + 'node-property': ['width', 'height'] + }); + (end code) + + */ + morph: function(json, opt, extraModes) { + extraModes = extraModes || {}; + var viz = this.viz; + var options = $.merge(this.options, viz.controller, opt), root = viz.root; + var graph; + //TODO(nico) this hack makes morphing work with the Hypertree. + //Need to check if it has been solved and this can be removed. + viz.root = opt.id || viz.root; + switch(options.type) { + case 'nothing': + graph = viz.construct(json); + graph.eachNode(function(elem) { + var nodeExists = viz.graph.hasNode(elem.id); + elem.eachAdjacency(function(adj) { + var adjExists = !!viz.graph.getAdjacence(adj.nodeFrom.id, adj.nodeTo.id); + viz.graph.addAdjacence(adj.nodeFrom, adj.nodeTo, adj.data); + //Update data properties if the node existed + if(adjExists) { + var addedAdj = viz.graph.getAdjacence(adj.nodeFrom.id, adj.nodeTo.id); + for(var prop in (adj.data || {})) { + addedAdj.data[prop] = adj.data[prop]; + } + } + }); + //Update data properties if the node existed + if(nodeExists) { + var addedNode = viz.graph.getNode(elem.id); + for(var prop in (elem.data || {})) { + addedNode.data[prop] = elem.data[prop]; + } + } + }); + viz.graph.eachNode(function(elem) { + elem.eachAdjacency(function(adj) { + if(!graph.getAdjacence(adj.nodeFrom.id, adj.nodeTo.id)) { + viz.graph.removeAdjacence(adj.nodeFrom.id, adj.nodeTo.id); + } + }); + if(!graph.hasNode(elem.id)) viz.graph.removeNode(elem.id); + }); + + break; + + case 'replot': + viz.labels.clearLabels(true); + this.morph(json, { type: 'nothing' }); + viz.refresh(true); + viz.refresh(true); + break; + + case 'fade:seq': case 'fade': case 'fade:con': + that = this; + graph = viz.construct(json); + //preprocessing for nodes to delete. + //get node property modes to interpolate + var nodeModes = ('node-property' in extraModes) + && $.map($.splat(extraModes['node-property']), + function(n) { return '$' + n; }); + viz.graph.eachNode(function(elem) { + var graphNode = graph.getNode(elem.id); + if(!graphNode) { + elem.setData('alpha', 1); + elem.setData('alpha', 1, 'start'); + elem.setData('alpha', 0, 'end'); + elem.ignore = true; + } else { + //Update node data information + var graphNodeData = graphNode.data; + for(var prop in graphNodeData) { + if(nodeModes && ($.indexOf(nodeModes, prop) > -1)) { + elem.endData[prop] = graphNodeData[prop]; + } else { + elem.data[prop] = graphNodeData[prop]; + } + } + } + }); + viz.graph.eachNode(function(elem) { + if(elem.ignore) return; + elem.eachAdjacency(function(adj) { + if(adj.nodeFrom.ignore || adj.nodeTo.ignore) return; + var nodeFrom = graph.getNode(adj.nodeFrom.id); + var nodeTo = graph.getNode(adj.nodeTo.id); + if(!nodeFrom.adjacentTo(nodeTo)) { + var adj = viz.graph.getAdjacence(nodeFrom.id, nodeTo.id); + fadeEdges = true; + adj.setData('alpha', 1); + adj.setData('alpha', 1, 'start'); + adj.setData('alpha', 0, 'end'); + } + }); + }); + //preprocessing for adding nodes. + var fadeEdges = this.preprocessSum(graph); + + var modes = !fadeEdges? ['node-property:alpha'] : + ['node-property:alpha', + 'edge-property:alpha']; + //Append extra node-property animations (if any) + modes[0] = modes[0] + (('node-property' in extraModes)? + (':' + $.splat(extraModes['node-property']).join(':')) : ''); + //Append extra edge-property animations (if any) + modes[1] = (modes[1] || 'edge-property:alpha') + (('edge-property' in extraModes)? + (':' + $.splat(extraModes['edge-property']).join(':')) : ''); + //Add label-property animations (if any) + if('label-property' in extraModes) { + modes.push('label-property:' + $.splat(extraModes['label-property']).join(':')) + } + //only use reposition if its implemented. + if (viz.reposition) { + viz.reposition(); + } else { + viz.compute('end'); + } + viz.graph.eachNode(function(elem) { + if (elem.id != root && elem.pos.getp().equals(Polar.KER)) { + elem.pos.set(elem.endPos); elem.startPos.set(elem.endPos); + } + }); + viz.fx.animate($.merge(options, { + modes: [extraModes.position || 'polar'].concat(modes), + onComplete: function() { + viz.graph.eachNode(function(elem) { + if(elem.ignore) viz.graph.removeNode(elem.id); + }); + viz.graph.eachNode(function(elem) { + elem.eachAdjacency(function(adj) { + if(adj.ignore) viz.graph.removeAdjacence(adj.nodeFrom.id, adj.nodeTo.id); + }); + }); + options.onComplete(); + } + })); + break; + + default:; + } + }, + + + /* + Method: contract + + Collapses the subtree of the given node. The node will have a _collapsed=true_ property. + + Parameters: + + node - (object) A . + opt - (object) An object containing options described below + type - (string) Whether to 'replot' or 'animate' the contraction. + + There are also a number of Animation options. For more information see . + + Example: + (start code js) + var viz = new $jit.Viz(options); + viz.op.contract(node, { + type: 'animate', + duration: 1000, + hideLabels: true, + transition: $jit.Trans.Quart.easeOut + }); + (end code) + + */ + contract: function(node, opt) { + var viz = this.viz; + if(node.collapsed || !node.anySubnode($.lambda(true))) return; + opt = $.merge(this.options, viz.config, opt || {}, { + 'modes': ['node-property:alpha:span', 'linear'] + }); + node.collapsed = true; + (function subn(n) { + n.eachSubnode(function(ch) { + ch.ignore = true; + ch.setData('alpha', 0, opt.type == 'animate'? 'end' : 'current'); + subn(ch); + }); + })(node); + if(opt.type == 'animate') { + viz.compute('end'); + if(viz.rotated) { + viz.rotate(viz.rotated, 'none', { + 'property':'end' + }); + } + (function subn(n) { + n.eachSubnode(function(ch) { + ch.setPos(node.getPos('end'), 'end'); + subn(ch); + }); + })(node); + viz.fx.animate(opt); + } else if(opt.type == 'replot'){ + viz.refresh(); + } + }, + + /* + Method: expand + + Expands the previously contracted subtree. The given node must have the _collapsed=true_ property. + + Parameters: + + node - (object) A . + opt - (object) An object containing options described below + type - (string) Whether to 'replot' or 'animate'. + + There are also a number of Animation options. For more information see . + + Example: + (start code js) + var viz = new $jit.Viz(options); + viz.op.expand(node, { + type: 'animate', + duration: 1000, + hideLabels: true, + transition: $jit.Trans.Quart.easeOut + }); + (end code) + + */ + expand: function(node, opt) { + if(!('collapsed' in node)) return; + var viz = this.viz; + opt = $.merge(this.options, viz.config, opt || {}, { + 'modes': ['node-property:alpha:span', 'linear'] + }); + delete node.collapsed; + (function subn(n) { + n.eachSubnode(function(ch) { + delete ch.ignore; + ch.setData('alpha', 1, opt.type == 'animate'? 'end' : 'current'); + subn(ch); + }); + })(node); + if(opt.type == 'animate') { + viz.compute('end'); + if(viz.rotated) { + viz.rotate(viz.rotated, 'none', { + 'property':'end' + }); + } + viz.fx.animate(opt); + } else if(opt.type == 'replot'){ + viz.refresh(); + } + }, + + preprocessSum: function(graph) { + var viz = this.viz; + graph.eachNode(function(elem) { + if(!viz.graph.hasNode(elem.id)) { + viz.graph.addNode(elem); + var n = viz.graph.getNode(elem.id); + n.setData('alpha', 0); + n.setData('alpha', 0, 'start'); + n.setData('alpha', 1, 'end'); + } + }); + var fadeEdges = false; + graph.eachNode(function(elem) { + elem.eachAdjacency(function(adj) { + var nodeFrom = viz.graph.getNode(adj.nodeFrom.id); + var nodeTo = viz.graph.getNode(adj.nodeTo.id); + if(!nodeFrom.adjacentTo(nodeTo)) { + var adj = viz.graph.addAdjacence(nodeFrom, nodeTo, adj.data); + if(nodeFrom.startAlpha == nodeFrom.endAlpha + && nodeTo.startAlpha == nodeTo.endAlpha) { + fadeEdges = true; + adj.setData('alpha', 0); + adj.setData('alpha', 0, 'start'); + adj.setData('alpha', 1, 'end'); + } + } + }); + }); + return fadeEdges; + } +}; + + + +/* + File: Helpers.js + + Helpers are objects that contain rendering primitives (like rectangles, ellipses, etc), for plotting nodes and edges. + Helpers also contain implementations of the *contains* method, a method returning a boolean indicating whether the mouse + position is over the rendered shape. + + Helpers are very useful when implementing new NodeTypes, since you can access them through *this.nodeHelper* and + *this.edgeHelper* properties, providing you with simple primitives and mouse-position check functions. + + Example: + (start code js) + //implement a new node type + $jit.Viz.Plot.NodeTypes.implement({ + 'customNodeType': { + 'render': function(node, canvas) { + this.nodeHelper.circle.render ... + }, + 'contains': function(node, pos) { + this.nodeHelper.circle.contains ... + } + } + }); + //implement an edge type + $jit.Viz.Plot.EdgeTypes.implement({ + 'customNodeType': { + 'render': function(node, canvas) { + this.edgeHelper.circle.render ... + }, + //optional + 'contains': function(node, pos) { + this.edgeHelper.circle.contains ... + } + } + }); + (end code) + +*/ + +/* + Object: NodeHelper + + Contains rendering and other type of primitives for simple shapes. + */ +var NodeHelper = { + 'none': { + 'render': $.empty, + 'contains': $.lambda(false) + }, + /* + Object: NodeHelper.circle + */ + 'circle': { + /* + Method: render + + Renders a circle into the canvas. + + Parameters: + + type - (string) Possible options are 'fill' or 'stroke'. + pos - (object) An *x*, *y* object with the position of the center of the circle. + radius - (number) The radius of the circle to be rendered. + canvas - (object) A instance. + + Example: + (start code js) + NodeHelper.circle.render('fill', { x: 10, y: 30 }, 30, viz.canvas); + (end code) + */ + 'render': function(type, pos, radius, canvas){ + var ctx = canvas.getCtx(); + ctx.beginPath(); + ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2, true); + ctx.closePath(); + ctx[type](); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + npos - (object) An *x*, *y* object with the position. + pos - (object) An *x*, *y* object with the position to check. + radius - (number) The radius of the rendered circle. + + Example: + (start code js) + NodeHelper.circle.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); //true + (end code) + */ + 'contains': function(npos, pos, radius){ + var diffx = npos.x - pos.x, + diffy = npos.y - pos.y, + diff = diffx * diffx + diffy * diffy; + return diff <= radius * radius; + } + }, + /* + Object: NodeHelper.ellipse + */ + 'ellipse': { + /* + Method: render + + Renders an ellipse into the canvas. + + Parameters: + + type - (string) Possible options are 'fill' or 'stroke'. + pos - (object) An *x*, *y* object with the position of the center of the ellipse. + width - (number) The width of the ellipse. + height - (number) The height of the ellipse. + canvas - (object) A instance. + + Example: + (start code js) + NodeHelper.ellipse.render('fill', { x: 10, y: 30 }, 30, 40, viz.canvas); + (end code) + */ + 'render': function(type, pos, width, height, canvas){ + var ctx = canvas.getCtx(), + scalex = 1, + scaley = 1, + scaleposx = 1, + scaleposy = 1, + radius = 0; + + if (width > height) { + radius = width / 2; + scaley = height / width; + scaleposy = width / height; + } else { + radius = height / 2; + scalex = width / height; + scaleposx = height / width; + } + + ctx.save(); + ctx.scale(scalex, scaley); + ctx.beginPath(); + ctx.arc(pos.x * scaleposx, pos.y * scaleposy, radius, 0, Math.PI * 2, true); + ctx.closePath(); + ctx[type](); + ctx.restore(); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + npos - (object) An *x*, *y* object with the position. + pos - (object) An *x*, *y* object with the position to check. + width - (number) The width of the rendered ellipse. + height - (number) The height of the rendered ellipse. + + Example: + (start code js) + NodeHelper.ellipse.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30, 40); + (end code) + */ + 'contains': function(npos, pos, width, height){ + var radius = 0, + scalex = 1, + scaley = 1, + diffx = 0, + diffy = 0, + diff = 0; + + if (width > height) { + radius = width / 2; + scaley = height / width; + } else { + radius = height / 2; + scalex = width / height; + } + + diffx = (npos.x - pos.x) * (1 / scalex); + diffy = (npos.y - pos.y) * (1 / scaley); + diff = diffx * diffx + diffy * diffy; + return diff <= radius * radius; + } + }, + /* + Object: NodeHelper.square + */ + 'square': { + /* + Method: render + + Renders a square into the canvas. + + Parameters: + + type - (string) Possible options are 'fill' or 'stroke'. + pos - (object) An *x*, *y* object with the position of the center of the square. + dim - (number) The radius (or half-diameter) of the square. + canvas - (object) A instance. + + Example: + (start code js) + NodeHelper.square.render('stroke', { x: 10, y: 30 }, 40, viz.canvas); + (end code) + */ + 'render': function(type, pos, dim, canvas){ + canvas.getCtx()[type + "Rect"](pos.x - dim, pos.y - dim, 2*dim, 2*dim); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + npos - (object) An *x*, *y* object with the position. + pos - (object) An *x*, *y* object with the position to check. + dim - (number) The radius (or half-diameter) of the square. + + Example: + (start code js) + NodeHelper.square.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); + (end code) + */ + 'contains': function(npos, pos, dim){ + return Math.abs(pos.x - npos.x) <= dim && Math.abs(pos.y - npos.y) <= dim; + } + }, + /* + Object: NodeHelper.rectangle + */ + 'rectangle': { + /* + Method: render + + Renders a rectangle into the canvas. + + Parameters: + + type - (string) Possible options are 'fill' or 'stroke'. + pos - (object) An *x*, *y* object with the position of the center of the rectangle. + width - (number) The width of the rectangle. + height - (number) The height of the rectangle. + canvas - (object) A instance. + + Example: + (start code js) + NodeHelper.rectangle.render('fill', { x: 10, y: 30 }, 30, 40, viz.canvas); + (end code) + */ + 'render': function(type, pos, width, height, canvas){ + canvas.getCtx()[type + "Rect"](pos.x - width / 2, pos.y - height / 2, + width, height); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + npos - (object) An *x*, *y* object with the position. + pos - (object) An *x*, *y* object with the position to check. + width - (number) The width of the rendered rectangle. + height - (number) The height of the rendered rectangle. + + Example: + (start code js) + NodeHelper.rectangle.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30, 40); + (end code) + */ + 'contains': function(npos, pos, width, height){ + return Math.abs(pos.x - npos.x) <= width / 2 + && Math.abs(pos.y - npos.y) <= height / 2; + } + }, + /* + Object: NodeHelper.triangle + */ + 'triangle': { + /* + Method: render + + Renders a triangle into the canvas. + + Parameters: + + type - (string) Possible options are 'fill' or 'stroke'. + pos - (object) An *x*, *y* object with the position of the center of the triangle. + dim - (number) Half the base and half the height of the triangle. + canvas - (object) A instance. + + Example: + (start code js) + NodeHelper.triangle.render('stroke', { x: 10, y: 30 }, 40, viz.canvas); + (end code) + */ + 'render': function(type, pos, dim, canvas){ + var ctx = canvas.getCtx(), + c1x = pos.x, + c1y = pos.y - dim, + c2x = c1x - dim, + c2y = pos.y + dim, + c3x = c1x + dim, + c3y = c2y; + ctx.beginPath(); + ctx.moveTo(c1x, c1y); + ctx.lineTo(c2x, c2y); + ctx.lineTo(c3x, c3y); + ctx.closePath(); + ctx[type](); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + npos - (object) An *x*, *y* object with the position. + pos - (object) An *x*, *y* object with the position to check. + dim - (number) Half the base and half the height of the triangle. + + Example: + (start code js) + NodeHelper.triangle.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); + (end code) + */ + 'contains': function(npos, pos, dim) { + return NodeHelper.circle.contains(npos, pos, dim); + } + }, + /* + Object: NodeHelper.star + */ + 'star': { + /* + Method: render + + Renders a star (concave decagon) into the canvas. + + Parameters: + + type - (string) Possible options are 'fill' or 'stroke'. + pos - (object) An *x*, *y* object with the position of the center of the star. + dim - (number) The length of a side of a concave decagon. + canvas - (object) A instance. + + Example: + (start code js) + NodeHelper.star.render('stroke', { x: 10, y: 30 }, 40, viz.canvas); + (end code) + */ + 'render': function(type, pos, dim, canvas){ + var ctx = canvas.getCtx(), + pi5 = Math.PI / 5; + ctx.save(); + ctx.translate(pos.x, pos.y); + ctx.beginPath(); + ctx.moveTo(dim, 0); + for (var i = 0; i < 9; i++) { + ctx.rotate(pi5); + if (i % 2 == 0) { + ctx.lineTo((dim / 0.525731) * 0.200811, 0); + } else { + ctx.lineTo(dim, 0); + } + } + ctx.closePath(); + ctx[type](); + ctx.restore(); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + npos - (object) An *x*, *y* object with the position. + pos - (object) An *x*, *y* object with the position to check. + dim - (number) The length of a side of a concave decagon. + + Example: + (start code js) + NodeHelper.star.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); + (end code) + */ + 'contains': function(npos, pos, dim) { + return NodeHelper.circle.contains(npos, pos, dim); + } + } +}; + +/* + Object: EdgeHelper + + Contains rendering primitives for simple edge shapes. +*/ +var EdgeHelper = { + /* + Object: EdgeHelper.line + */ + 'line': { + /* + Method: render + + Renders a line into the canvas. + + Parameters: + + from - (object) An *x*, *y* object with the starting position of the line. + to - (object) An *x*, *y* object with the ending position of the line. + canvas - (object) A instance. + + Example: + (start code js) + EdgeHelper.line.render({ x: 10, y: 30 }, { x: 10, y: 50 }, viz.canvas); + (end code) + */ + 'render': function(from, to, canvas){ + var ctx = canvas.getCtx(); + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + posFrom - (object) An *x*, *y* object with a position. + posTo - (object) An *x*, *y* object with a position. + pos - (object) An *x*, *y* object with the position to check. + epsilon - (number) The dimension of the shape. + + Example: + (start code js) + EdgeHelper.line.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, { x: 15, y: 35 }, 30); + (end code) + */ + 'contains': function(posFrom, posTo, pos, epsilon) { + var min = Math.min, + max = Math.max, + minPosX = min(posFrom.x, posTo.x), + maxPosX = max(posFrom.x, posTo.x), + minPosY = min(posFrom.y, posTo.y), + maxPosY = max(posFrom.y, posTo.y); + + if(pos.x >= minPosX && pos.x <= maxPosX + && pos.y >= minPosY && pos.y <= maxPosY) { + if(Math.abs(posTo.x - posFrom.x) <= epsilon) { + return true; + } + var dist = (posTo.y - posFrom.y) / (posTo.x - posFrom.x) * (pos.x - posFrom.x) + posFrom.y; + return Math.abs(dist - pos.y) <= epsilon; + } + return false; + } + }, + /* + Object: EdgeHelper.arrow + */ + 'arrow': { + /* + Method: render + + Renders an arrow into the canvas. + + Parameters: + + from - (object) An *x*, *y* object with the starting position of the arrow. + to - (object) An *x*, *y* object with the ending position of the arrow. + dim - (number) The dimension of the arrow. + swap - (boolean) Whether to set the arrow pointing to the starting position or the ending position. + canvas - (object) A instance. + + Example: + (start code js) + EdgeHelper.arrow.render({ x: 10, y: 30 }, { x: 10, y: 50 }, 13, false, viz.canvas); + (end code) + */ + 'render': function(from, to, dim, swap, canvas){ + var ctx = canvas.getCtx(); + // invert edge direction + if (swap) { + var tmp = from; + from = to; + to = tmp; + } + var vect = new Complex(to.x - from.x, to.y - from.y); + vect.$scale(dim / vect.norm()); + var intermediatePoint = new Complex(to.x - vect.x, to.y - vect.y), + normal = new Complex(-vect.y / 2, vect.x / 2), + v1 = intermediatePoint.add(normal), + v2 = intermediatePoint.$add(normal.$scale(-1)); + + ctx.beginPath(); + ctx.moveTo(from.x, from.y); + ctx.lineTo(to.x, to.y); + ctx.stroke(); + ctx.beginPath(); + ctx.moveTo(v1.x, v1.y); + ctx.lineTo(v2.x, v2.y); + ctx.lineTo(to.x, to.y); + ctx.closePath(); + ctx.fill(); + }, + /* + Method: contains + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + posFrom - (object) An *x*, *y* object with a position. + posTo - (object) An *x*, *y* object with a position. + pos - (object) An *x*, *y* object with the position to check. + epsilon - (number) The dimension of the shape. + + Example: + (start code js) + EdgeHelper.arrow.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, { x: 15, y: 35 }, 30); + (end code) + */ + 'contains': function(posFrom, posTo, pos, epsilon) { + return EdgeHelper.line.contains(posFrom, posTo, pos, epsilon); + } + }, + /* + Object: EdgeHelper.hyperline + */ + 'hyperline': { + /* + Method: render + + Renders a hyperline into the canvas. A hyperline are the lines drawn for the visualization. + + Parameters: + + from - (object) An *x*, *y* object with the starting position of the hyperline. *x* and *y* must belong to [0, 1). + to - (object) An *x*, *y* object with the ending position of the hyperline. *x* and *y* must belong to [0, 1). + r - (number) The scaling factor. + canvas - (object) A instance. + + Example: + (start code js) + EdgeHelper.hyperline.render({ x: 10, y: 30 }, { x: 10, y: 50 }, 100, viz.canvas); + (end code) + */ + 'render': function(from, to, r, canvas){ + var ctx = canvas.getCtx(); + var centerOfCircle = computeArcThroughTwoPoints(from, to); + if (centerOfCircle.a > 1000 || centerOfCircle.b > 1000 + || centerOfCircle.ratio < 0) { + ctx.beginPath(); + ctx.moveTo(from.x * r, from.y * r); + ctx.lineTo(to.x * r, to.y * r); + ctx.stroke(); + } else { + var angleBegin = Math.atan2(to.y - centerOfCircle.y, to.x + - centerOfCircle.x); + var angleEnd = Math.atan2(from.y - centerOfCircle.y, from.x + - centerOfCircle.x); + var sense = sense(angleBegin, angleEnd); + ctx.beginPath(); + ctx.arc(centerOfCircle.x * r, centerOfCircle.y * r, centerOfCircle.ratio + * r, angleBegin, angleEnd, sense); + ctx.stroke(); + } + /* + Calculates the arc parameters through two points. + + More information in + + Parameters: + + p1 - A instance. + p2 - A instance. + scale - The Disk's diameter. + + Returns: + + An object containing some arc properties. + */ + function computeArcThroughTwoPoints(p1, p2){ + var aDen = (p1.x * p2.y - p1.y * p2.x), bDen = aDen; + var sq1 = p1.squaredNorm(), sq2 = p2.squaredNorm(); + // Fall back to a straight line + if (aDen == 0) + return { + x: 0, + y: 0, + ratio: -1 + }; + + var a = (p1.y * sq2 - p2.y * sq1 + p1.y - p2.y) / aDen; + var b = (p2.x * sq1 - p1.x * sq2 + p2.x - p1.x) / bDen; + var x = -a / 2; + var y = -b / 2; + var squaredRatio = (a * a + b * b) / 4 - 1; + // Fall back to a straight line + if (squaredRatio < 0) + return { + x: 0, + y: 0, + ratio: -1 + }; + var ratio = Math.sqrt(squaredRatio); + var out = { + x: x, + y: y, + ratio: ratio > 1000? -1 : ratio, + a: a, + b: b + }; + + return out; + } + /* + Sets angle direction to clockwise (true) or counterclockwise (false). + + Parameters: + + angleBegin - Starting angle for drawing the arc. + angleEnd - The HyperLine will be drawn from angleBegin to angleEnd. + + Returns: + + A Boolean instance describing the sense for drawing the HyperLine. + */ + function sense(angleBegin, angleEnd){ + return (angleBegin < angleEnd)? ((angleBegin + Math.PI > angleEnd)? false + : true) : ((angleEnd + Math.PI > angleBegin)? true : false); + } + }, + /* + Method: contains + + Not Implemented + + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. + + Parameters: + + posFrom - (object) An *x*, *y* object with a position. + posTo - (object) An *x*, *y* object with a position. + pos - (object) An *x*, *y* object with the position to check. + epsilon - (number) The dimension of the shape. + + Example: + (start code js) + EdgeHelper.hyperline.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, { x: 15, y: 35 }, 30); + (end code) + */ + 'contains': $.lambda(false) + } +}; + + +/* + * File: Graph.Plot.js + */ + +/* + Object: Graph.Plot + + rendering and animation methods. + + Properties: + + nodeHelper - object. + edgeHelper - object. +*/ +Graph.Plot = { + //Default initializer + initialize: function(viz, klass){ + this.viz = viz; + this.config = viz.config; + this.node = viz.config.Node; + this.edge = viz.config.Edge; + this.animation = new Animation; + this.nodeTypes = new klass.Plot.NodeTypes; + this.edgeTypes = new klass.Plot.EdgeTypes; + this.labels = viz.labels; + }, + + //Add helpers + nodeHelper: NodeHelper, + edgeHelper: EdgeHelper, + + Interpolator: { + //node/edge property parsers + 'map': { + 'border': 'color', + 'color': 'color', + 'width': 'number', + 'height': 'number', + 'dim': 'number', + 'alpha': 'number', + 'lineWidth': 'number', + 'angularWidth':'number', + 'span':'number', + 'valueArray':'array-number', + 'dimArray':'array-number' + //'colorArray':'array-color' + }, + + //canvas specific parsers + 'canvas': { + 'globalAlpha': 'number', + 'fillStyle': 'color', + 'strokeStyle': 'color', + 'lineWidth': 'number', + 'shadowBlur': 'number', + 'shadowColor': 'color', + 'shadowOffsetX': 'number', + 'shadowOffsetY': 'number', + 'miterLimit': 'number' + }, + + //label parsers + 'label': { + 'size': 'number', + 'color': 'color' + }, + + //Number interpolator + 'compute': function(from, to, delta) { + return from + (to - from) * delta; + }, + + //Position interpolators + 'moebius': function(elem, props, delta, vector) { + var v = vector.scale(-delta); + if(v.norm() < 1) { + var x = v.x, y = v.y; + var ans = elem.startPos + .getc().moebiusTransformation(v); + elem.pos.setc(ans.x, ans.y); + v.x = x; v.y = y; + } + }, + + 'linear': function(elem, props, delta) { + var from = elem.startPos.getc(true); + var to = elem.endPos.getc(true); + elem.pos.setc(this.compute(from.x, to.x, delta), + this.compute(from.y, to.y, delta)); + }, + + 'polar': function(elem, props, delta) { + var from = elem.startPos.getp(true); + var to = elem.endPos.getp(); + var ans = to.interpolate(from, delta); + elem.pos.setp(ans.theta, ans.rho); + }, + + //Graph's Node/Edge interpolators + 'number': function(elem, prop, delta, getter, setter) { + var from = elem[getter](prop, 'start'); + var to = elem[getter](prop, 'end'); + elem[setter](prop, this.compute(from, to, delta)); + }, + + 'color': function(elem, prop, delta, getter, setter) { + var from = $.hexToRgb(elem[getter](prop, 'start')); + var to = $.hexToRgb(elem[getter](prop, 'end')); + var comp = this.compute; + var val = $.rgbToHex([parseInt(comp(from[0], to[0], delta)), + parseInt(comp(from[1], to[1], delta)), + parseInt(comp(from[2], to[2], delta))]); + + elem[setter](prop, val); + }, + + 'array-number': function(elem, prop, delta, getter, setter) { + var from = elem[getter](prop, 'start'), + to = elem[getter](prop, 'end'), + cur = []; + for(var i=0, l=from.length; i, + + */ + prepare: function(modes) { + var graph = this.viz.graph, + accessors = { + 'node-property': { + 'getter': 'getData', + 'setter': 'setData' + }, + 'edge-property': { + 'getter': 'getData', + 'setter': 'setData' + }, + 'node-style': { + 'getter': 'getCanvasStyle', + 'setter': 'setCanvasStyle' + }, + 'edge-style': { + 'getter': 'getCanvasStyle', + 'setter': 'setCanvasStyle' + } + }; + + //parse modes + var m = {}; + if($.type(modes) == 'array') { + for(var i=0, len=modes.length; i < len; i++) { + var elems = modes[i].split(':'); + m[elems.shift()] = elems; + } + } else { + for(var p in modes) { + if(p == 'position') { + m[modes.position] = []; + } else { + m[p] = $.splat(modes[p]); + } + } + } + + graph.eachNode(function(node) { + node.startPos.set(node.pos); + $.each(['node-property', 'node-style'], function(p) { + if(p in m) { + var prop = m[p]; + for(var i=0, l=prop.length; i < l; i++) { + node[accessors[p].setter](prop[i], node[accessors[p].getter](prop[i]), 'start'); + } + } + }); + $.each(['edge-property', 'edge-style'], function(p) { + if(p in m) { + var prop = m[p]; + node.eachAdjacency(function(adj) { + for(var i=0, l=prop.length; i < l; i++) { + adj[accessors[p].setter](prop[i], adj[accessors[p].getter](prop[i]), 'start'); + } + }); + } + }); + }); + return m; + }, + + /* + Method: animate + + Animates a by interpolating some , or properties. + + Parameters: + + opt - (object) Animation options. The object properties are described below + duration - (optional) Described in . + fps - (optional) Described in . + hideLabels - (optional|boolean) Whether to hide labels during the animation. + modes - (required|object) An object with animation modes (described below). + + Animation modes: + + Animation modes are strings representing different node/edge and graph properties that you'd like to animate. + They are represented by an object that has as keys main categories of properties to animate and as values a list + of these specific properties. The properties are described below + + position - Describes the way nodes' positions must be interpolated. Possible values are 'linear', 'polar' or 'moebius'. + node-property - Describes which Node properties will be interpolated. These properties can be any of the ones defined in . + edge-property - Describes which Edge properties will be interpolated. These properties can be any the ones defined in . + label-property - Describes which Label properties will be interpolated. These properties can be any of the ones defined in like color or size. + node-style - Describes which Node Canvas Styles will be interpolated. These are specific canvas properties like fillStyle, strokeStyle, lineWidth, shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY, etc. + edge-style - Describes which Edge Canvas Styles will be interpolated. These are specific canvas properties like fillStyle, strokeStyle, lineWidth, shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY, etc. + + Example: + (start code js) + var viz = new $jit.Viz(options); + //...tweak some Data, CanvasStyles or LabelData properties... + viz.fx.animate({ + modes: { + 'position': 'linear', + 'node-property': ['width', 'height'], + 'node-style': 'shadowColor', + 'label-property': 'size' + }, + hideLabels: false + }); + //...can also be written like this... + viz.fx.animate({ + modes: ['linear', + 'node-property:width:height', + 'node-style:shadowColor', + 'label-property:size'], + hideLabels: false + }); + (end code) + */ + animate: function(opt, versor) { + opt = $.merge(this.viz.config, opt || {}); + var that = this, + viz = this.viz, + graph = viz.graph, + interp = this.Interpolator, + animation = opt.type === 'nodefx'? this.nodeFxAnimation : this.animation; + //prepare graph values + var m = this.prepare(opt.modes); + + //animate + if(opt.hideLabels) this.labels.hideLabels(true); + animation.setOptions($.extend(opt, { + $animating: false, + compute: function(delta) { + graph.eachNode(function(node) { + for(var p in m) { + interp[p](node, m[p], delta, versor); + } + }); + that.plot(opt, this.$animating, delta); + this.$animating = true; + }, + complete: function() { + if(opt.hideLabels) that.labels.hideLabels(false); + that.plot(opt); + opt.onComplete(); + //TODO(nico): This shouldn't be here! + //opt.onAfterCompute(); + } + })).start(); + }, + + /* + nodeFx + + Apply animation to node properties like color, width, height, dim, etc. + + Parameters: + + options - Animation options. This object properties is described below + elements - The Elements to be transformed. This is an object that has a properties + + (start code js) + 'elements': { + //can also be an array of ids + 'id': 'id-of-node-to-transform', + //properties to be modified. All properties are optional. + 'properties': { + 'color': '#ccc', //some color + 'width': 10, //some width + 'height': 10, //some height + 'dim': 20, //some dim + 'lineWidth': 10 //some line width + } + } + (end code) + + - _reposition_ Whether to recalculate positions and add a motion animation. + This might be used when changing _width_ or _height_ properties in a like layout. Default's *false*. + + - _onComplete_ A method that is called when the animation completes. + + ...and all other options like _duration_, _fps_, _transition_, etc. + + Example: + (start code js) + var rg = new RGraph(canvas, config); //can be also Hypertree or ST + rg.fx.nodeFx({ + 'elements': { + 'id':'mynodeid', + 'properties': { + 'color':'#ccf' + }, + 'transition': Trans.Quart.easeOut + } + }); + (end code) + */ + nodeFx: function(opt) { + var viz = this.viz, + graph = viz.graph, + animation = this.nodeFxAnimation, + options = $.merge(this.viz.config, { + 'elements': { + 'id': false, + 'properties': {} + }, + 'reposition': false + }); + opt = $.merge(options, opt || {}, { + onBeforeCompute: $.empty, + onAfterCompute: $.empty + }); + //check if an animation is running + animation.stopTimer(); + var props = opt.elements.properties; + //set end values for nodes + if(!opt.elements.id) { + graph.eachNode(function(n) { + for(var prop in props) { + n.setData(prop, props[prop], 'end'); + } + }); + } else { + var ids = $.splat(opt.elements.id); + $.each(ids, function(id) { + var n = graph.getNode(id); + if(n) { + for(var prop in props) { + n.setData(prop, props[prop], 'end'); + } + } + }); + } + //get keys + var propnames = []; + for(var prop in props) propnames.push(prop); + //add node properties modes + var modes = ['node-property:' + propnames.join(':')]; + //set new node positions + if(opt.reposition) { + modes.push('linear'); + viz.compute('end'); + } + //animate + this.animate($.merge(opt, { + modes: modes, + type: 'nodefx' + })); + }, + + + /* + Method: plot + + Plots a . + + Parameters: + + opt - (optional) Plotting options. Most of them are described in . + + Example: + + (start code js) + var viz = new $jit.Viz(options); + viz.fx.plot(); + (end code) + + */ + plot: function(opt, animating) { + var viz = this.viz, + aGraph = viz.graph, + canvas = viz.canvas, + id = viz.root, + that = this, + ctx = canvas.getCtx(), + min = Math.min, + opt = opt || this.viz.controller; + + opt.clearCanvas && canvas.clear(); + + var root = aGraph.getNode(id); + if(!root) return; + + var T = !!root.visited; + aGraph.eachNode(function(node) { + var nodeAlpha = node.getData('alpha'); + node.eachAdjacency(function(adj) { + var nodeTo = adj.nodeTo; + if(!!nodeTo.visited === T && node.drawn && nodeTo.drawn) { + !animating && opt.onBeforePlotLine(adj); + that.plotLine(adj, canvas, animating); + !animating && opt.onAfterPlotLine(adj); + } + }); + if(node.drawn) { + !animating && opt.onBeforePlotNode(node); + that.plotNode(node, canvas, animating); + !animating && opt.onAfterPlotNode(node); + } + if(!that.labelsHidden && opt.withLabels) { + if(node.drawn && nodeAlpha >= 0.95) { + that.labels.plotLabel(canvas, node, opt); + } else { + that.labels.hideLabel(node, false); + } + } + node.visited = !T; + }); + }, + + /* + Plots a Subtree. + */ + plotTree: function(node, opt, animating) { + var that = this, + viz = this.viz, + canvas = viz.canvas, + config = this.config, + ctx = canvas.getCtx(); + var nodeAlpha = node.getData('alpha'); + node.eachSubnode(function(elem) { + if(opt.plotSubtree(node, elem) && elem.exist && elem.drawn) { + var adj = node.getAdjacency(elem.id); + !animating && opt.onBeforePlotLine(adj); + that.plotLine(adj, canvas, animating); + !animating && opt.onAfterPlotLine(adj); + that.plotTree(elem, opt, animating); + } + }); + if(node.drawn) { + !animating && opt.onBeforePlotNode(node); + this.plotNode(node, canvas, animating); + !animating && opt.onAfterPlotNode(node); + if(!opt.hideLabels && opt.withLabels && nodeAlpha >= 0.95) + this.labels.plotLabel(canvas, node, opt); + else + this.labels.hideLabel(node, false); + } else { + this.labels.hideLabel(node, true); + } + }, + + /* + Method: plotNode + + Plots a . + + Parameters: + + node - (object) A . + canvas - (object) A element. + + */ + plotNode: function(node, canvas, animating) { + var f = node.getData('type'), + ctxObj = this.node.CanvasStyles; + if(f != 'none') { + var width = node.getData('lineWidth'), + color = node.getData('color'), + alpha = node.getData('alpha'), + ctx = canvas.getCtx(); + ctx.save(); + ctx.lineWidth = width; + ctx.fillStyle = ctx.strokeStyle = color; + ctx.globalAlpha = alpha; + + for(var s in ctxObj) { + ctx[s] = node.getCanvasStyle(s); + } + + this.nodeTypes[f].render.call(this, node, canvas, animating); + ctx.restore(); + } + }, + + /* + Method: plotLine + + Plots a . + + Parameters: + + adj - (object) A . + canvas - (object) A instance. + + */ + plotLine: function(adj, canvas, animating) { + var f = adj.getData('type'), + ctxObj = this.edge.CanvasStyles; + if(f != 'none') { + var width = adj.getData('lineWidth'), + color = adj.getData('color'), + ctx = canvas.getCtx(), + nodeFrom = adj.nodeFrom, + nodeTo = adj.nodeTo; + + ctx.save(); + ctx.lineWidth = width; + ctx.fillStyle = ctx.strokeStyle = color; + ctx.globalAlpha = Math.min(nodeFrom.getData('alpha'), + nodeTo.getData('alpha'), + adj.getData('alpha')); + + for(var s in ctxObj) { + ctx[s] = adj.getCanvasStyle(s); + } + + this.edgeTypes[f].render.call(this, adj, canvas, animating); + ctx.restore(); + } + } + +}; + +/* + Object: Graph.Plot3D + + 3D rendering and animation methods. + + Properties: + + nodeHelper - object. + edgeHelper - object. + +*/ +Graph.Plot3D = $.merge(Graph.Plot, { + Interpolator: { + 'linear': function(elem, props, delta) { + var from = elem.startPos.getc(true); + var to = elem.endPos.getc(true); + elem.pos.setc(this.compute(from.x, to.x, delta), + this.compute(from.y, to.y, delta), + this.compute(from.z, to.z, delta)); + } + }, + + plotNode: function(node, canvas) { + if(node.getData('type') == 'none') return; + this.plotElement(node, canvas, { + getAlpha: function() { + return node.getData('alpha'); + } + }); + }, + + plotLine: function(adj, canvas) { + if(adj.getData('type') == 'none') return; + this.plotElement(adj, canvas, { + getAlpha: function() { + return Math.min(adj.nodeFrom.getData('alpha'), + adj.nodeTo.getData('alpha'), + adj.getData('alpha')); + } + }); + }, + + plotElement: function(elem, canvas, opt) { + var gl = canvas.getCtx(), + viewMatrix = new Matrix4, + lighting = canvas.config.Scene.Lighting, + wcanvas = canvas.canvases[0], + program = wcanvas.program, + camera = wcanvas.camera; + + if(!elem.geometry) { + elem.geometry = new O3D[elem.getData('type')]; + } + elem.geometry.update(elem); + if(!elem.webGLVertexBuffer) { + var vertices = [], + faces = [], + normals = [], + vertexIndex = 0, + geom = elem.geometry; + + for(var i=0, vs=geom.vertices, fs=geom.faces, fsl=fs.length; i interface is implemented in multiple ways to provide + different label types. + + For example, the Graph.Label interface is implemented as to provide + HTML label elements. Also we provide the interface for SVG type labels. + The interface implements these methods with the native Canvas text rendering functions. + + All subclasses (, and ) implement the method plotLabel. +*/ + +Graph.Label = {}; + +/* + Class: Graph.Label.Native + + Implements labels natively, using the Canvas text API. +*/ +Graph.Label.Native = new Class({ + initialize: function(viz) { + this.viz = viz; + }, + + /* + Method: plotLabel + + Plots a label for a given node. + + Parameters: + + canvas - (object) A instance. + node - (object) A . + controller - (object) A configuration object. + + Example: + + (start code js) + var viz = new $jit.Viz(options); + var node = viz.graph.getNode('nodeId'); + viz.labels.plotLabel(viz.canvas, node, viz.config); + (end code) + */ + plotLabel: function(canvas, node, controller) { + var ctx = canvas.getCtx(); + var pos = node.pos.getc(true); + + ctx.font = node.getLabelData('style') + ' ' + node.getLabelData('size') + 'px ' + node.getLabelData('family'); + ctx.textAlign = node.getLabelData('textAlign'); + ctx.fillStyle = ctx.strokeStyle = node.getLabelData('color'); + ctx.textBaseline = node.getLabelData('textBaseline'); + + this.renderLabel(canvas, node, controller); + }, + + /* + renderLabel + + Does the actual rendering of the label in the canvas. The default + implementation renders the label close to the position of the node, this + method should be overriden to position the labels differently. + + Parameters: + + canvas - A instance. + node - A . + controller - A configuration object. See also , , . + */ + renderLabel: function(canvas, node, controller) { + var ctx = canvas.getCtx(); + var pos = node.pos.getc(true); + ctx.fillText(node.name, pos.x, pos.y + node.getData("height") / 2); + }, + + hideLabel: $.empty, + hideLabels: $.empty +}); + +/* + Class: Graph.Label.DOM + + Abstract Class implementing some DOM label methods. + + Implemented by: + + and . + +*/ +Graph.Label.DOM = new Class({ + //A flag value indicating if node labels are being displayed or not. + labelsHidden: false, + //Label container + labelContainer: false, + //Label elements hash. + labels: {}, + + /* + Method: getLabelContainer + + Lazy fetcher for the label container. + + Returns: + + The label container DOM element. + + Example: + + (start code js) + var viz = new $jit.Viz(options); + var labelContainer = viz.labels.getLabelContainer(); + alert(labelContainer.innerHTML); + (end code) + */ + getLabelContainer: function() { + return this.labelContainer ? + this.labelContainer : + this.labelContainer = document.getElementById(this.viz.config.labelContainer); + }, + + /* + Method: getLabel + + Lazy fetcher for the label element. + + Parameters: + + id - (string) The label id (which is also a id). + + Returns: + + The label element. + + Example: + + (start code js) + var viz = new $jit.Viz(options); + var label = viz.labels.getLabel('someid'); + alert(label.innerHTML); + (end code) + + */ + getLabel: function(id) { + return (id in this.labels && this.labels[id] != null) ? + this.labels[id] : + this.labels[id] = document.getElementById(id); + }, + + /* + Method: hideLabels + + Hides all labels (by hiding the label container). + + Parameters: + + hide - (boolean) A boolean value indicating if the label container must be hidden or not. + + Example: + (start code js) + var viz = new $jit.Viz(options); + rg.labels.hideLabels(true); + (end code) + + */ + hideLabels: function (hide) { + var container = this.getLabelContainer(); + if(hide) + container.style.display = 'none'; + else + container.style.display = ''; + this.labelsHidden = hide; + }, + + /* + Method: clearLabels + + Clears the label container. + + Useful when using a new visualization with the same canvas element/widget. + + Parameters: + + force - (boolean) Forces deletion of all labels. + + Example: + (start code js) + var viz = new $jit.Viz(options); + viz.labels.clearLabels(); + (end code) + */ + clearLabels: function(force) { + for(var id in this.labels) { + if (force || !this.viz.graph.hasNode(id)) { + this.disposeLabel(id); + delete this.labels[id]; + } + } + }, + + /* + Method: disposeLabel + + Removes a label. + + Parameters: + + id - (string) A label id (which generally is also a id). + + Example: + (start code js) + var viz = new $jit.Viz(options); + viz.labels.disposeLabel('labelid'); + (end code) + */ + disposeLabel: function(id) { + var elem = this.getLabel(id); + if(elem && elem.parentNode) { + elem.parentNode.removeChild(elem); + } + }, + + /* + Method: hideLabel + + Hides the corresponding label. + + Parameters: + + node - (object) A . Can also be an array of . + show - (boolean) If *true*, nodes will be shown. Otherwise nodes will be hidden. + + Example: + (start code js) + var rg = new $jit.Viz(options); + viz.labels.hideLabel(viz.graph.getNode('someid'), false); + (end code) + */ + hideLabel: function(node, show) { + node = $.splat(node); + var st = show ? "" : "none", lab, that = this; + $.each(node, function(n) { + var lab = that.getLabel(n.id); + if (lab) { + lab.style.display = st; + } + }); + }, + + /* + fitsInCanvas + + Returns _true_ or _false_ if the label for the node is contained in the canvas dom element or not. + + Parameters: + + pos - A instance (I'm doing duck typing here so any object with _x_ and _y_ parameters will do). + canvas - A instance. + + Returns: + + A boolean value specifying if the label is contained in the DOM element or not. + + */ + fitsInCanvas: function(pos, canvas) { + var size = canvas.getSize(); + if(pos.x >= size.width || pos.x < 0 + || pos.y >= size.height || pos.y < 0) return false; + return true; + } +}); + +/* + Class: Graph.Label.HTML + + Implements HTML labels. + + Extends: + + All methods. + +*/ +Graph.Label.HTML = new Class({ + Implements: Graph.Label.DOM, + + /* + Method: plotLabel + + Plots a label for a given node. + + Parameters: + + canvas - (object) A instance. + node - (object) A . + controller - (object) A configuration object. + + Example: + + (start code js) + var viz = new $jit.Viz(options); + var node = viz.graph.getNode('nodeId'); + viz.labels.plotLabel(viz.canvas, node, viz.config); + (end code) + + + */ + plotLabel: function(canvas, node, controller) { + var id = node.id, tag = this.getLabel(id); + + if(!tag && !(tag = document.getElementById(id))) { + tag = document.createElement('div'); + var container = this.getLabelContainer(); + tag.id = id; + tag.className = 'node'; + tag.style.position = 'absolute'; + controller.onCreateLabel(tag, node); + container.appendChild(tag); + this.labels[node.id] = tag; + } + + this.placeLabel(tag, node, controller); + } +}); + +/* + Class: Graph.Label.SVG + + Implements SVG labels. + + Extends: + + All methods. +*/ +Graph.Label.SVG = new Class({ + Implements: Graph.Label.DOM, + + /* + Method: plotLabel + + Plots a label for a given node. + + Parameters: + + canvas - (object) A instance. + node - (object) A . + controller - (object) A configuration object. + + Example: + + (start code js) + var viz = new $jit.Viz(options); + var node = viz.graph.getNode('nodeId'); + viz.labels.plotLabel(viz.canvas, node, viz.config); + (end code) + + + */ + plotLabel: function(canvas, node, controller) { + var id = node.id, tag = this.getLabel(id); + if(!tag && !(tag = document.getElementById(id))) { + var ns = 'http://www.w3.org/2000/svg'; + tag = document.createElementNS(ns, 'svg:text'); + var tspan = document.createElementNS(ns, 'svg:tspan'); + tag.appendChild(tspan); + var container = this.getLabelContainer(); + tag.setAttribute('id', id); + tag.setAttribute('class', 'node'); + container.appendChild(tag); + controller.onCreateLabel(tag, node); + this.labels[node.id] = tag; + } + this.placeLabel(tag, node, controller); + } +}); + + + +Graph.Geom = new Class({ + + initialize: function(viz) { + this.viz = viz; + this.config = viz.config; + this.node = viz.config.Node; + this.edge = viz.config.Edge; + }, + /* + Applies a translation to the tree. + + Parameters: + + pos - A number specifying translation vector. + prop - A position property ('pos', 'start' or 'end'). + + Example: + + (start code js) + st.geom.translate(new Complex(300, 100), 'end'); + (end code) + */ + translate: function(pos, prop) { + prop = $.splat(prop); + this.viz.graph.eachNode(function(elem) { + $.each(prop, function(p) { elem.getPos(p).$add(pos); }); + }); + }, + /* + Hides levels of the tree until it properly fits in canvas. + */ + setRightLevelToShow: function(node, canvas, callback) { + var level = this.getRightLevelToShow(node, canvas), + fx = this.viz.labels, + opt = $.merge({ + execShow:true, + execHide:true, + onHide: $.empty, + onShow: $.empty + }, callback || {}); + node.eachLevel(0, this.config.levelsToShow, function(n) { + var d = n._depth - node._depth; + if(d > level) { + opt.onHide(n); + if(opt.execHide) { + n.drawn = false; + n.exist = false; + fx.hideLabel(n, false); + } + } else { + opt.onShow(n); + if(opt.execShow) { + n.exist = true; + } + } + }); + node.drawn= true; + }, + /* + Returns the right level to show for the current tree in order to fit in canvas. + */ + getRightLevelToShow: function(node, canvas) { + var config = this.config; + var level = config.levelsToShow; + var constrained = config.constrained; + if(!constrained) return level; + while(!this.treeFitsInCanvas(node, canvas, level) && level > 1) { level-- ; } + return level; + } +}); + +/* + * File: Loader.js + * + */ + +/* + Object: Loader + + Provides methods for loading and serving JSON data. +*/ +var Loader = { + construct: function(json) { + var isGraph = ($.type(json) == 'array'); + var ans = new Graph(this.graphOptions, this.config.Node, this.config.Edge, this.config.Label); + if(!isGraph) + //make tree + (function (ans, json) { + ans.addNode(json); + if(json.children) { + for(var i=0, ch = json.children; i will override the general value for that option with that particular value. For this to work + however, you do have to set *overridable = true* in . + + The same thing is true for JSON adjacencies. Dollar prefixed data properties will alter values set in + if has *overridable = true*. + + When loading JSON data into TreeMaps, the *data* property must contain a value for the *$area* key, + since this is the value which will be taken into account when creating the layout. + The same thing goes for the *$color* parameter. + + In JSON Nodes you can use also *$label-* prefixed properties to refer to properties. For example, + *$label-size* will refer to size property. Also, in JSON nodes and adjacencies you can set + canvas specific properties individually by using the *$canvas-* prefix. For example, *$canvas-shadowBlur* will refer + to the *shadowBlur* property. + + These properties can also be accessed after loading the JSON data from and + by using . For more information take a look at the and documentation. + + Finally, these properties can also be used to create advanced animations like with . For more + information about creating animations please take a look at the and documentation. + + loadJSON Parameters: + + json - A JSON Tree or Graph structure. + i - For Graph structures only. Sets the indexed node as root for the visualization. + + */ + loadJSON: function(json, i) { + this.json = json; + //if they're canvas labels erase them. + if(this.labels && this.labels.clearLabels) { + this.labels.clearLabels(true); + } + this.graph = this.construct(json); + if($.type(json) != 'array'){ + this.root = json.id; + } else { + this.root = json[i? i : 0].id; + } + }, + + /* + Method: toJSON + + Returns a JSON tree/graph structure from the visualization's . + See for the graph formats available. + + See also: + + + + Parameters: + + type - (string) Default's "tree". The type of the JSON structure to be returned. + Possible options are "tree" or "graph". + */ + toJSON: function(type) { + type = type || "tree"; + if(type == 'tree') { + var ans = {}; + var rootNode = this.graph.getNode(this.root); + var ans = (function recTree(node) { + var ans = {}; + ans.id = node.id; + ans.name = node.name; + ans.data = node.data; + var ch =[]; + node.eachSubnode(function(n) { + ch.push(recTree(n)); + }); + ans.children = ch; + return ans; + })(rootNode); + return ans; + } else { + var ans = []; + var T = !!this.graph.getNode(this.root).visited; + this.graph.eachNode(function(node) { + var ansNode = {}; + ansNode.id = node.id; + ansNode.name = node.name; + ansNode.data = node.data; + var adjs = []; + node.eachAdjacency(function(adj) { + var nodeTo = adj.nodeTo; + if(!!nodeTo.visited === T) { + var ansAdj = {}; + ansAdj.nodeTo = nodeTo.id; + ansAdj.data = adj.data; + adjs.push(ansAdj); + } + }); + ansNode.adjacencies = adjs; + ans.push(ansNode); + node.visited = !T; + }); + return ans; + } + } +}; + + + +/* + * File: Layouts.js + * + * Implements base Tree and Graph layouts. + * + * Description: + * + * Implements base Tree and Graph layouts like Radial, Tree, etc. + * + */ + +/* + * Object: Layouts + * + * Parent object for common layouts. + * + */ +var Layouts = $jit.Layouts = {}; + + +//Some util shared layout functions are defined here. +var NodeDim = { + label: null, + + compute: function(graph, prop, opt) { + this.initializeLabel(opt); + var label = this.label, style = label.style; + graph.eachNode(function(n) { + var autoWidth = n.getData('autoWidth'), + autoHeight = n.getData('autoHeight'); + if(autoWidth || autoHeight) { + //delete dimensions since these are + //going to be overridden now. + delete n.data.$width; + delete n.data.$height; + delete n.data.$dim; + + var width = n.getData('width'), + height = n.getData('height'); + //reset label dimensions + style.width = autoWidth? 'auto' : width + 'px'; + style.height = autoHeight? 'auto' : height + 'px'; + + //TODO(nico) should let the user choose what to insert here. + label.innerHTML = n.name; + + var offsetWidth = label.offsetWidth, + offsetHeight = label.offsetHeight; + var type = n.getData('type'); + if($.indexOf(['circle', 'square', 'triangle', 'star'], type) === -1) { + n.setData('width', offsetWidth); + n.setData('height', offsetHeight); + } else { + var dim = offsetWidth > offsetHeight? offsetWidth : offsetHeight; + n.setData('width', dim); + n.setData('height', dim); + n.setData('dim', dim); + } + } + }); + }, + + initializeLabel: function(opt) { + if(!this.label) { + this.label = document.createElement('div'); + document.body.appendChild(this.label); + } + this.setLabelStyles(opt); + }, + + setLabelStyles: function(opt) { + $.extend(this.label.style, { + 'visibility': 'hidden', + 'position': 'absolute', + 'width': 'auto', + 'height': 'auto' + }); + this.label.className = 'jit-autoadjust-label'; + } +}; + + +/* + * Class: Layouts.Tree + * + * Implements a Tree Layout. + * + * Implemented By: + * + * + * + * Inspired by: + * + * Drawing Trees (Andrew J. Kennedy) + * + */ +Layouts.Tree = (function() { + //Layout functions + var slice = Array.prototype.slice; + + /* + Calculates the max width and height nodes for a tree level + */ + function getBoundaries(graph, config, level, orn, prop) { + var dim = config.Node; + var multitree = config.multitree; + if (dim.overridable) { + var w = -1, h = -1; + graph.eachNode(function(n) { + if (n._depth == level + && (!multitree || ('$orn' in n.data) && n.data.$orn == orn)) { + var dw = n.getData('width', prop); + var dh = n.getData('height', prop); + w = (w < dw) ? dw : w; + h = (h < dh) ? dh : h; + } + }); + return { + 'width' : w < 0 ? dim.width : w, + 'height' : h < 0 ? dim.height : h + }; + } else { + return dim; + } + } + + + function movetree(node, prop, val, orn) { + var p = (orn == "left" || orn == "right") ? "y" : "x"; + node.getPos(prop)[p] += val; + } + + + function moveextent(extent, val) { + var ans = []; + $.each(extent, function(elem) { + elem = slice.call(elem); + elem[0] += val; + elem[1] += val; + ans.push(elem); + }); + return ans; + } + + + function merge(ps, qs) { + if (ps.length == 0) + return qs; + if (qs.length == 0) + return ps; + var p = ps.shift(), q = qs.shift(); + return [ [ p[0], q[1] ] ].concat(merge(ps, qs)); + } + + + function mergelist(ls, def) { + def = def || []; + if (ls.length == 0) + return def; + var ps = ls.pop(); + return mergelist(ls, merge(ps, def)); + } + + + function fit(ext1, ext2, subtreeOffset, siblingOffset, i) { + if (ext1.length <= i || ext2.length <= i) + return 0; + + var p = ext1[i][1], q = ext2[i][0]; + return Math.max(fit(ext1, ext2, subtreeOffset, siblingOffset, ++i) + + subtreeOffset, p - q + siblingOffset); + } + + + function fitlistl(es, subtreeOffset, siblingOffset) { + function $fitlistl(acc, es, i) { + if (es.length <= i) + return []; + var e = es[i], ans = fit(acc, e, subtreeOffset, siblingOffset, 0); + return [ ans ].concat($fitlistl(merge(acc, moveextent(e, ans)), es, ++i)); + } + ; + return $fitlistl( [], es, 0); + } + + + function fitlistr(es, subtreeOffset, siblingOffset) { + function $fitlistr(acc, es, i) { + if (es.length <= i) + return []; + var e = es[i], ans = -fit(e, acc, subtreeOffset, siblingOffset, 0); + return [ ans ].concat($fitlistr(merge(moveextent(e, ans), acc), es, ++i)); + } + ; + es = slice.call(es); + var ans = $fitlistr( [], es.reverse(), 0); + return ans.reverse(); + } + + + function fitlist(es, subtreeOffset, siblingOffset, align) { + var esl = fitlistl(es, subtreeOffset, siblingOffset), esr = fitlistr(es, + subtreeOffset, siblingOffset); + + if (align == "left") + esr = esl; + else if (align == "right") + esl = esr; + + for ( var i = 0, ans = []; i < esl.length; i++) { + ans[i] = (esl[i] + esr[i]) / 2; + } + return ans; + } + + + function design(graph, node, prop, config, orn) { + var multitree = config.multitree; + var auxp = [ 'x', 'y' ], auxs = [ 'width', 'height' ]; + var ind = +(orn == "left" || orn == "right"); + var p = auxp[ind], notp = auxp[1 - ind]; + + var cnode = config.Node; + var s = auxs[ind], nots = auxs[1 - ind]; + + var siblingOffset = config.siblingOffset; + var subtreeOffset = config.subtreeOffset; + var align = config.align; + + function $design(node, maxsize, acum) { + var sval = node.getData(s, prop); + var notsval = maxsize + || (node.getData(nots, prop)); + + var trees = [], extents = [], chmaxsize = false; + var chacum = notsval + config.levelDistance; + node.eachSubnode(function(n) { + if (n.exist + && (!multitree || ('$orn' in n.data) && n.data.$orn == orn)) { + + if (!chmaxsize) + chmaxsize = getBoundaries(graph, config, n._depth, orn, prop); + + var s = $design(n, chmaxsize[nots], acum + chacum); + trees.push(s.tree); + extents.push(s.extent); + } + }); + var positions = fitlist(extents, subtreeOffset, siblingOffset, align); + for ( var i = 0, ptrees = [], pextents = []; i < trees.length; i++) { + movetree(trees[i], prop, positions[i], orn); + pextents.push(moveextent(extents[i], positions[i])); + } + var resultextent = [ [ -sval / 2, sval / 2 ] ] + .concat(mergelist(pextents)); + node.getPos(prop)[p] = 0; + + if (orn == "top" || orn == "left") { + node.getPos(prop)[notp] = acum; + } else { + node.getPos(prop)[notp] = -acum; + } + + return { + tree : node, + extent : resultextent + }; + } + + $design(node, false, 0); + } + + + return new Class({ + /* + Method: compute + + Computes nodes' positions. + + */ + compute : function(property, computeLevels) { + var prop = property || 'start'; + var node = this.graph.getNode(this.root); + $.extend(node, { + 'drawn' : true, + 'exist' : true, + 'selected' : true + }); + NodeDim.compute(this.graph, prop, this.config); + if (!!computeLevels || !("_depth" in node)) { + this.graph.computeLevels(this.root, 0, "ignore"); + } + + this.computePositions(node, prop); + }, + + computePositions : function(node, prop) { + var config = this.config; + var multitree = config.multitree; + var align = config.align; + var indent = align !== 'center' && config.indent; + var orn = config.orientation; + var orns = multitree ? [ 'top', 'right', 'bottom', 'left' ] : [ orn ]; + var that = this; + $.each(orns, function(orn) { + //calculate layout + design(that.graph, node, prop, that.config, orn, prop); + var i = [ 'x', 'y' ][+(orn == "left" || orn == "right")]; + //absolutize + (function red(node) { + node.eachSubnode(function(n) { + if (n.exist + && (!multitree || ('$orn' in n.data) && n.data.$orn == orn)) { + + n.getPos(prop)[i] += node.getPos(prop)[i]; + if (indent) { + n.getPos(prop)[i] += align == 'left' ? indent : -indent; + } + red(n); + } + }); + })(node); + }); + } + }); + +})(); + +/* + * File: Spacetree.js + */ + +/* + Class: ST + + A Tree layout with advanced contraction and expansion animations. + + Inspired by: + + SpaceTree: Supporting Exploration in Large Node Link Tree, Design Evolution and Empirical Evaluation (Catherine Plaisant, Jesse Grosjean, Benjamin B. Bederson) + + + Drawing Trees (Andrew J. Kennedy) + + Note: + + This visualization was built and engineered from scratch, taking only the papers as inspiration, and only shares some features with the visualization described in those papers. + + Implements: + + All methods + + Constructor Options: + + Inherits options from + + - + - + - + - + - + - + - + - + - + - + + Additionally, there are other parameters and some default values changed + + constrained - (boolean) Default's *true*. Whether to show the entire tree when loaded or just the number of levels specified by _levelsToShow_. + levelsToShow - (number) Default's *2*. The number of levels to show for a subtree. This number is relative to the selected node. + levelDistance - (number) Default's *30*. The distance between two consecutive levels of the tree. + Node.type - Described in . Default's set to *rectangle*. + offsetX - (number) Default's *0*. The x-offset distance from the selected node to the center of the canvas. + offsetY - (number) Default's *0*. The y-offset distance from the selected node to the center of the canvas. + duration - Described in . It's default value has been changed to *700*. + + Instance Properties: + + canvas - Access a instance. + graph - Access a instance. + op - Access a instance. + fx - Access a instance. + labels - Access a interface implementation. + + */ + +$jit.ST= (function() { + // Define some private methods first... + // Nodes in path + var nodesInPath = []; + // Nodes to contract + function getNodesToHide(node) { + node = node || this.clickedNode; + if(!this.config.constrained) { + return []; + } + var Geom = this.geom; + var graph = this.graph; + var canvas = this.canvas; + var level = node._depth, nodeArray = []; + graph.eachNode(function(n) { + if(n.exist && !n.selected) { + if(n.isDescendantOf(node.id)) { + if(n._depth <= level) nodeArray.push(n); + } else { + nodeArray.push(n); + } + } + }); + var leafLevel = Geom.getRightLevelToShow(node, canvas); + node.eachLevel(leafLevel, leafLevel, function(n) { + if(n.exist && !n.selected) nodeArray.push(n); + }); + + for (var i = 0; i < nodesInPath.length; i++) { + var n = this.graph.getNode(nodesInPath[i]); + if(!n.isDescendantOf(node.id)) { + nodeArray.push(n); + } + } + return nodeArray; + }; + // Nodes to expand + function getNodesToShow(node) { + var nodeArray = [], config = this.config; + node = node || this.clickedNode; + this.clickedNode.eachLevel(0, config.levelsToShow, function(n) { + if(config.multitree && !('$orn' in n.data) + && n.anySubnode(function(ch){ return ch.exist && !ch.drawn; })) { + nodeArray.push(n); + } else if(n.drawn && !n.anySubnode("drawn")) { + nodeArray.push(n); + } + }); + return nodeArray; + }; + // Now define the actual class. + return new Class({ + + Implements: [Loader, Extras, Layouts.Tree], + + initialize: function(controller) { + var $ST = $jit.ST; + + var config= { + levelsToShow: 2, + levelDistance: 30, + constrained: true, + Node: { + type: 'rectangle' + }, + duration: 700, + offsetX: 0, + offsetY: 0 + }; + + this.controller = this.config = $.merge( + Options("Canvas", "Fx", "Tree", "Node", "Edge", "Controller", + "Tips", "NodeStyles", "Events", "Navigation", "Label"), config, controller); + + var canvasConfig = this.config; + if(canvasConfig.useCanvas) { + this.canvas = canvasConfig.useCanvas; + this.config.labelContainer = this.canvas.id + '-label'; + } else { + if(canvasConfig.background) { + canvasConfig.background = $.merge({ + type: 'Circles' + }, canvasConfig.background); + } + this.canvas = new Canvas(this, canvasConfig); + this.config.labelContainer = (typeof canvasConfig.injectInto == 'string'? canvasConfig.injectInto : canvasConfig.injectInto.id) + '-label'; + } + + this.graphOptions = { + 'klass': Complex + }; + this.graph = new Graph(this.graphOptions, this.config.Node, this.config.Edge); + this.labels = new $ST.Label[canvasConfig.Label.type](this); + this.fx = new $ST.Plot(this, $ST); + this.op = new $ST.Op(this); + this.group = new $ST.Group(this); + this.geom = new $ST.Geom(this); + this.clickedNode= null; + // initialize extras + this.initializeExtras(); + }, + + /* + Method: plot + + Plots the . This is a shortcut to *fx.plot*. + + */ + plot: function() { this.fx.plot(this.controller); }, + + + /* + Method: switchPosition + + Switches the tree orientation. + + Parameters: + + pos - (string) The new tree orientation. Possible values are "top", "left", "right" and "bottom". + method - (string) Set this to "animate" if you want to animate the tree when switching its position. You can also set this parameter to "replot" to just replot the subtree. + onComplete - (optional|object) This callback is called once the "switching" animation is complete. + + Example: + + (start code js) + st.switchPosition("right", "animate", { + onComplete: function() { + alert('completed!'); + } + }); + (end code) + */ + switchPosition: function(pos, method, onComplete) { + var Geom = this.geom, Plot = this.fx, that = this; + if(!Plot.busy) { + Plot.busy = true; + this.contract({ + onComplete: function() { + Geom.switchOrientation(pos); + that.compute('end', false); + Plot.busy = false; + if(method == 'animate') { + that.onClick(that.clickedNode.id, onComplete); + } else if(method == 'replot') { + that.select(that.clickedNode.id, onComplete); + } + } + }, pos); + } + }, + + /* + Method: switchAlignment + + Switches the tree alignment. + + Parameters: + + align - (string) The new tree alignment. Possible values are "left", "center" and "right". + method - (string) Set this to "animate" if you want to animate the tree after aligning its position. You can also set this parameter to "replot" to just replot the subtree. + onComplete - (optional|object) This callback is called once the "switching" animation is complete. + + Example: + + (start code js) + st.switchAlignment("right", "animate", { + onComplete: function() { + alert('completed!'); + } + }); + (end code) + */ + switchAlignment: function(align, method, onComplete) { + this.config.align = align; + if(method == 'animate') { + this.select(this.clickedNode.id, onComplete); + } else if(method == 'replot') { + this.onClick(this.clickedNode.id, onComplete); + } + }, + + /* + Method: addNodeInPath + + Adds a node to the current path as selected node. The selected node will be visible (as in non-collapsed) at all times. + + + Parameters: + + id - (string) A id. + + Example: + + (start code js) + st.addNodeInPath("nodeId"); + (end code) + */ + addNodeInPath: function(id) { + nodesInPath.push(id); + this.select((this.clickedNode && this.clickedNode.id) || this.root); + }, + + /* + Method: clearNodesInPath + + Removes all nodes tagged as selected by the method. + + See also: + + + + Example: + + (start code js) + st.clearNodesInPath(); + (end code) + */ + clearNodesInPath: function(id) { + nodesInPath.length = 0; + this.select((this.clickedNode && this.clickedNode.id) || this.root); + }, + + /* + Method: refresh + + Computes positions and plots the tree. + + */ + refresh: function() { + this.reposition(); + this.select((this.clickedNode && this.clickedNode.id) || this.root); + }, + + reposition: function() { + this.graph.computeLevels(this.root, 0, "ignore"); + this.geom.setRightLevelToShow(this.clickedNode, this.canvas); + this.graph.eachNode(function(n) { + if(n.exist) n.drawn = true; + }); + this.compute('end'); + }, + + requestNodes: function(node, onComplete) { + var handler = $.merge(this.controller, onComplete), + lev = this.config.levelsToShow; + if(handler.request) { + var leaves = [], d = node._depth; + node.eachLevel(0, lev, function(n) { + if(n.drawn && + !n.anySubnode()) { + leaves.push(n); + n._level = lev - (n._depth - d); + } + }); + this.group.requestNodes(leaves, handler); + } + else + handler.onComplete(); + }, + + contract: function(onComplete, switched) { + var orn = this.config.orientation; + var Geom = this.geom, Group = this.group; + if(switched) Geom.switchOrientation(switched); + var nodes = getNodesToHide.call(this); + if(switched) Geom.switchOrientation(orn); + Group.contract(nodes, $.merge(this.controller, onComplete)); + }, + + move: function(node, onComplete) { + this.compute('end', false); + var move = onComplete.Move, offset = { + 'x': move.offsetX, + 'y': move.offsetY + }; + if(move.enable) { + this.geom.translate(node.endPos.add(offset).$scale(-1), "end"); + } + this.fx.animate($.merge(this.controller, { modes: ['linear'] }, onComplete)); + }, + + expand: function (node, onComplete) { + var nodeArray = getNodesToShow.call(this, node); + this.group.expand(nodeArray, $.merge(this.controller, onComplete)); + }, + + selectPath: function(node) { + var that = this; + this.graph.eachNode(function(n) { n.selected = false; }); + function path(node) { + if(node == null || node.selected) return; + node.selected = true; + $.each(that.group.getSiblings([node])[node.id], + function(n) { + n.exist = true; + n.drawn = true; + }); + var parents = node.getParents(); + parents = (parents.length > 0)? parents[0] : null; + path(parents); + }; + for(var i=0, ns = [node.id].concat(nodesInPath); i < ns.length; i++) { + path(this.graph.getNode(ns[i])); + } + }, + + /* + Method: setRoot + + Switches the current root node. Changes the topology of the Tree. + + Parameters: + id - (string) The id of the node to be set as root. + method - (string) Set this to "animate" if you want to animate the tree after adding the subtree. You can also set this parameter to "replot" to just replot the subtree. + onComplete - (optional|object) An action to perform after the animation (if any). + + Example: + + (start code js) + st.setRoot('nodeId', 'animate', { + onComplete: function() { + alert('complete!'); + } + }); + (end code) + */ + setRoot: function(id, method, onComplete) { + if(this.busy) return; + this.busy = true; + var that = this, canvas = this.canvas; + var rootNode = this.graph.getNode(this.root); + var clickedNode = this.graph.getNode(id); + function $setRoot() { + if(this.config.multitree && clickedNode.data.$orn) { + var orn = clickedNode.data.$orn; + var opp = { + 'left': 'right', + 'right': 'left', + 'top': 'bottom', + 'bottom': 'top' + }[orn]; + rootNode.data.$orn = opp; + (function tag(rootNode) { + rootNode.eachSubnode(function(n) { + if(n.id != id) { + n.data.$orn = opp; + tag(n); + } + }); + })(rootNode); + delete clickedNode.data.$orn; + } + this.root = id; + this.clickedNode = clickedNode; + this.graph.computeLevels(this.root, 0, "ignore"); + this.geom.setRightLevelToShow(clickedNode, canvas, { + execHide: false, + onShow: function(node) { + if(!node.drawn) { + node.drawn = true; + node.setData('alpha', 1, 'end'); + node.setData('alpha', 0); + node.pos.setc(clickedNode.pos.x, clickedNode.pos.y); + } + } + }); + this.compute('end'); + this.busy = true; + this.fx.animate({ + modes: ['linear', 'node-property:alpha'], + onComplete: function() { + that.busy = false; + that.onClick(id, { + onComplete: function() { + onComplete && onComplete.onComplete(); + } + }); + } + }); + } + + // delete previous orientations (if any) + delete rootNode.data.$orns; + + if(method == 'animate') { + $setRoot.call(this); + that.selectPath(clickedNode); + } else if(method == 'replot') { + $setRoot.call(this); + this.select(this.root); + } + }, + + /* + Method: addSubtree + + Adds a subtree. + + Parameters: + subtree - (object) A JSON Tree object. See also . + method - (string) Set this to "animate" if you want to animate the tree after adding the subtree. You can also set this parameter to "replot" to just replot the subtree. + onComplete - (optional|object) An action to perform after the animation (if any). + + Example: + + (start code js) + st.addSubtree(json, 'animate', { + onComplete: function() { + alert('complete!'); + } + }); + (end code) + */ + addSubtree: function(subtree, method, onComplete) { + if(method == 'replot') { + this.op.sum(subtree, $.extend({ type: 'replot' }, onComplete || {})); + } else if (method == 'animate') { + this.op.sum(subtree, $.extend({ type: 'fade:seq' }, onComplete || {})); + } + }, + + /* + Method: removeSubtree + + Removes a subtree. + + Parameters: + id - (string) The _id_ of the subtree to be removed. + removeRoot - (boolean) Default's *false*. Remove the root of the subtree or only its subnodes. + method - (string) Set this to "animate" if you want to animate the tree after removing the subtree. You can also set this parameter to "replot" to just replot the subtree. + onComplete - (optional|object) An action to perform after the animation (if any). + + Example: + + (start code js) + st.removeSubtree('idOfSubtreeToBeRemoved', false, 'animate', { + onComplete: function() { + alert('complete!'); + } + }); + (end code) + + */ + removeSubtree: function(id, removeRoot, method, onComplete) { + var node = this.graph.getNode(id), subids = []; + node.eachLevel(+!removeRoot, false, function(n) { + subids.push(n.id); + }); + if(method == 'replot') { + this.op.removeNode(subids, $.extend({ type: 'replot' }, onComplete || {})); + } else if (method == 'animate') { + this.op.removeNode(subids, $.extend({ type: 'fade:seq'}, onComplete || {})); + } + }, + + /* + Method: select + + Selects a node in the without performing an animation. Useful when selecting + nodes which are currently hidden or deep inside the tree. + + Parameters: + id - (string) The id of the node to select. + onComplete - (optional|object) an onComplete callback. + + Example: + (start code js) + st.select('mynodeid', { + onComplete: function() { + alert('complete!'); + } + }); + (end code) + */ + select: function(id, onComplete) { + var group = this.group, geom = this.geom; + var node= this.graph.getNode(id), canvas = this.canvas; + var root = this.graph.getNode(this.root); + var complete = $.merge(this.controller, onComplete); + var that = this; + + complete.onBeforeCompute(node); + this.selectPath(node); + this.clickedNode= node; + this.requestNodes(node, { + onComplete: function(){ + group.hide(group.prepare(getNodesToHide.call(that)), complete); + geom.setRightLevelToShow(node, canvas); + that.compute("current"); + that.graph.eachNode(function(n) { + var pos = n.pos.getc(true); + n.startPos.setc(pos.x, pos.y); + n.endPos.setc(pos.x, pos.y); + n.visited = false; + }); + var offset = { x: complete.offsetX, y: complete.offsetY }; + that.geom.translate(node.endPos.add(offset).$scale(-1), ["start", "current", "end"]); + group.show(getNodesToShow.call(that)); + that.plot(); + complete.onAfterCompute(that.clickedNode); + complete.onComplete(); + } + }); + }, + + /* + Method: onClick + + Animates the to center the node specified by *id*. + + Parameters: + + id - (string) A node id. + options - (optional|object) A group of options and callbacks described below. + onComplete - (object) An object callback called when the animation finishes. + Move - (object) An object that has as properties _offsetX_ or _offsetY_ for adding some offset position to the centered node. + + Example: + + (start code js) + st.onClick('mynodeid', { + Move: { + enable: true, + offsetX: 30, + offsetY: 5 + }, + onComplete: function() { + alert('yay!'); + } + }); + (end code) + + */ + onClick: function (id, options) { + var canvas = this.canvas, that = this, Geom = this.geom, config = this.config; + var innerController = { + Move: { + enable: true, + offsetX: config.offsetX || 0, + offsetY: config.offsetY || 0 + }, + setRightLevelToShowConfig: false, + onBeforeRequest: $.empty, + onBeforeContract: $.empty, + onBeforeMove: $.empty, + onBeforeExpand: $.empty + }; + var complete = $.merge(this.controller, innerController, options); + + if(!this.busy) { + this.busy = true; + var node = this.graph.getNode(id); + this.selectPath(node, this.clickedNode); + this.clickedNode = node; + complete.onBeforeCompute(node); + complete.onBeforeRequest(node); + this.requestNodes(node, { + onComplete: function() { + complete.onBeforeContract(node); + that.contract({ + onComplete: function() { + Geom.setRightLevelToShow(node, canvas, complete.setRightLevelToShowConfig); + complete.onBeforeMove(node); + that.move(node, { + Move: complete.Move, + onComplete: function() { + complete.onBeforeExpand(node); + that.expand(node, { + onComplete: function() { + that.busy = false; + complete.onAfterCompute(id); + complete.onComplete(); + } + }); // expand + } + }); // move + } + });// contract + } + });// request + } + } + }); + +})(); + +$jit.ST.$extend = true; + +/* + Class: ST.Op + + Custom extension of . + + Extends: + + All methods + + See also: + + + +*/ +$jit.ST.Op = new Class({ + + Implements: Graph.Op + +}); + +/* + + Performs operations on group of nodes. + +*/ +$jit.ST.Group = new Class({ + + initialize: function(viz) { + this.viz = viz; + this.canvas = viz.canvas; + this.config = viz.config; + this.animation = new Animation; + this.nodes = null; + }, + + /* + + Calls the request method on the controller to request a subtree for each node. + */ + requestNodes: function(nodes, controller) { + var counter = 0, len = nodes.length, nodeSelected = {}; + var complete = function() { controller.onComplete(); }; + var viz = this.viz; + if(len == 0) complete(); + for(var i=0; i= b._depth); }); + for(var i=0; i 0 + && n.drawn) { + n.drawn = false; + nds[node.id].push(n); + } else if((!root || !orns) && n.drawn) { + n.drawn = false; + nds[node.id].push(n); + } + }); + node.drawn = true; + } + // plot the whole (non-scaled) tree + if(nodes.length > 0) viz.fx.plot(); + // show nodes that were previously hidden + for(i in nds) { + $.each(nds[i], function(n) { n.drawn = true; }); + } + // plot each scaled subtree + for(i=0; i method + (end code) + +*/ + +$jit.ST.Geom = new Class({ + Implements: Graph.Geom, + /* + Changes the tree current orientation to the one specified. + + You should usually use instead. + */ + switchOrientation: function(orn) { + this.config.orientation = orn; + }, + + /* + Makes a value dispatch according to the current layout + Works like a CSS property, either _top-right-bottom-left_ or _top|bottom - left|right_. + */ + dispatch: function() { + // TODO(nico) should store Array.prototype.slice.call somewhere. + var args = Array.prototype.slice.call(arguments); + var s = args.shift(), len = args.length; + var val = function(a) { return typeof a == 'function'? a() : a; }; + if(len == 2) { + return (s == "top" || s == "bottom")? val(args[0]) : val(args[1]); + } else if(len == 4) { + switch(s) { + case "top": return val(args[0]); + case "right": return val(args[1]); + case "bottom": return val(args[2]); + case "left": return val(args[3]); + } + } + return undefined; + }, + + /* + Returns label height or with, depending on the tree current orientation. + */ + getSize: function(n, invert) { + var data = n.data, config = this.config; + var siblingOffset = config.siblingOffset; + var s = (config.multitree + && ('$orn' in data) + && data.$orn) || config.orientation; + var w = n.getData('width') + siblingOffset; + var h = n.getData('height') + siblingOffset; + if(!invert) + return this.dispatch(s, h, w); + else + return this.dispatch(s, w, h); + }, + + /* + Calculates a subtree base size. This is an utility function used by _getBaseSize_ + */ + getTreeBaseSize: function(node, level, leaf) { + var size = this.getSize(node, true), baseHeight = 0, that = this; + if(leaf(level, node)) return size; + if(level === 0) return 0; + node.eachSubnode(function(elem) { + baseHeight += that.getTreeBaseSize(elem, level -1, leaf); + }); + return (size > baseHeight? size : baseHeight) + this.config.subtreeOffset; + }, + + + /* + getEdge + + Returns a Complex instance with the begin or end position of the edge to be plotted. + + Parameters: + + node - A that is connected to this edge. + type - Returns the begin or end edge position. Possible values are 'begin' or 'end'. + + Returns: + + A number specifying the begin or end position. + */ + getEdge: function(node, type, s) { + var $C = function(a, b) { + return function(){ + return node.pos.add(new Complex(a, b)); + }; + }; + var dim = this.node; + var w = node.getData('width'); + var h = node.getData('height'); + + if(type == 'begin') { + if(dim.align == "center") { + return this.dispatch(s, $C(0, h/2), $C(-w/2, 0), + $C(0, -h/2),$C(w/2, 0)); + } else if(dim.align == "left") { + return this.dispatch(s, $C(0, h), $C(0, 0), + $C(0, 0), $C(w, 0)); + } else if(dim.align == "right") { + return this.dispatch(s, $C(0, 0), $C(-w, 0), + $C(0, -h),$C(0, 0)); + } else throw "align: not implemented"; + + + } else if(type == 'end') { + if(dim.align == "center") { + return this.dispatch(s, $C(0, -h/2), $C(w/2, 0), + $C(0, h/2), $C(-w/2, 0)); + } else if(dim.align == "left") { + return this.dispatch(s, $C(0, 0), $C(w, 0), + $C(0, h), $C(0, 0)); + } else if(dim.align == "right") { + return this.dispatch(s, $C(0, -h),$C(0, 0), + $C(0, 0), $C(-w, 0)); + } else throw "align: not implemented"; + } + }, + + /* + Adjusts the tree position due to canvas scaling or translation. + */ + getScaledTreePosition: function(node, scale) { + var dim = this.node; + var w = node.getData('width'); + var h = node.getData('height'); + var s = (this.config.multitree + && ('$orn' in node.data) + && node.data.$orn) || this.config.orientation; + + var $C = function(a, b) { + return function(){ + return node.pos.add(new Complex(a, b)).$scale(1 - scale); + }; + }; + if(dim.align == "left") { + return this.dispatch(s, $C(0, h), $C(0, 0), + $C(0, 0), $C(w, 0)); + } else if(dim.align == "center") { + return this.dispatch(s, $C(0, h / 2), $C(-w / 2, 0), + $C(0, -h / 2),$C(w / 2, 0)); + } else if(dim.align == "right") { + return this.dispatch(s, $C(0, 0), $C(-w, 0), + $C(0, -h),$C(0, 0)); + } else throw "align: not implemented"; + }, + + /* + treeFitsInCanvas + + Returns a Boolean if the current subtree fits in canvas. + + Parameters: + + node - A which is the current root of the subtree. + canvas - The object. + level - The depth of the subtree to be considered. + */ + treeFitsInCanvas: function(node, canvas, level) { + var csize = canvas.getSize(); + var s = (this.config.multitree + && ('$orn' in node.data) + && node.data.$orn) || this.config.orientation; + + var size = this.dispatch(s, csize.width, csize.height); + var baseSize = this.getTreeBaseSize(node, level, function(level, node) { + return level === 0 || !node.anySubnode(); + }); + return (baseSize < size); + } +}); + +/* + Class: ST.Plot + + Custom extension of . + + Extends: + + All methods + + See also: + + + +*/ +$jit.ST.Plot = new Class({ + + Implements: Graph.Plot, + + /* + Plots a subtree from the spacetree. + */ + plotSubtree: function(node, opt, scale, animating) { + var viz = this.viz, canvas = viz.canvas, config = viz.config; + scale = Math.min(Math.max(0.001, scale), 1); + if(scale >= 0) { + node.drawn = false; + var ctx = canvas.getCtx(); + var diff = viz.geom.getScaledTreePosition(node, scale); + ctx.translate(diff.x, diff.y); + ctx.scale(scale, scale); + } + this.plotTree(node, $.merge(opt, { + 'withLabels': true, + 'hideLabels': !!scale, + 'plotSubtree': function(n, ch) { + var root = config.multitree && !('$orn' in node.data); + var orns = root && node.getData('orns'); + return !root || orns.indexOf(node.getData('orn')) > -1; + } + }), animating); + if(scale >= 0) node.drawn = true; + }, + + /* + Method: getAlignedPos + + Returns a *x, y* object with the position of the top/left corner of a node. + + Parameters: + + pos - (object) A position. + width - (number) The width of the node. + height - (number) The height of the node. + + */ + getAlignedPos: function(pos, width, height) { + var nconfig = this.node; + var square, orn; + if(nconfig.align == "center") { + square = { + x: pos.x - width / 2, + y: pos.y - height / 2 + }; + } else if (nconfig.align == "left") { + orn = this.config.orientation; + if(orn == "bottom" || orn == "top") { + square = { + x: pos.x - width / 2, + y: pos.y + }; + } else { + square = { + x: pos.x, + y: pos.y - height / 2 + }; + } + } else if(nconfig.align == "right") { + orn = this.config.orientation; + if(orn == "bottom" || orn == "top") { + square = { + x: pos.x - width / 2, + y: pos.y - height + }; + } else { + square = { + x: pos.x - width, + y: pos.y - height / 2 + }; + } + } else throw "align: not implemented"; + + return square; + }, + + getOrientation: function(adj) { + var config = this.config; + var orn = config.orientation; + + if(config.multitree) { + var nodeFrom = adj.nodeFrom; + var nodeTo = adj.nodeTo; + orn = (('$orn' in nodeFrom.data) + && nodeFrom.data.$orn) + || (('$orn' in nodeTo.data) + && nodeTo.data.$orn); + } + + return orn; + } +}); + +/* + Class: ST.Label + + Custom extension of . + Contains custom , and extensions. + + Extends: + + All methods and subclasses. + + See also: + + , , , . + */ +$jit.ST.Label = {}; + +/* + ST.Label.Native + + Custom extension of . + + Extends: + + All methods + + See also: + + +*/ +$jit.ST.Label.Native = new Class({ + Implements: Graph.Label.Native, + + renderLabel: function(canvas, node, controller) { + var ctx = canvas.getCtx(), + coord = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + pos = this.viz.fx.getAlignedPos(coord, width, height); + ctx.fillText(node.name, pos.x + width / 2, pos.y + height / 2); + } +}); + +$jit.ST.Label.DOM = new Class({ + Implements: Graph.Label.DOM, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller) { + var pos = node.pos.getc(true), + config = this.viz.config, + dim = config.Node, + canvas = this.viz.canvas, + w = node.getData('width'), + h = node.getData('height'), + radius = canvas.getSize(), + labelPos, orn; + + var ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + posx = pos.x * sx + ox, + posy = pos.y * sy + oy; + + if(dim.align == "center") { + labelPos= { + x: Math.round(posx - w / 2 + radius.width/2), + y: Math.round(posy - h / 2 + radius.height/2) + }; + } else if (dim.align == "left") { + orn = config.orientation; + if(orn == "bottom" || orn == "top") { + labelPos= { + x: Math.round(posx - w / 2 + radius.width/2), + y: Math.round(posy + radius.height/2) + }; + } else { + labelPos= { + x: Math.round(posx + radius.width/2), + y: Math.round(posy - h / 2 + radius.height/2) + }; + } + } else if(dim.align == "right") { + orn = config.orientation; + if(orn == "bottom" || orn == "top") { + labelPos= { + x: Math.round(posx - w / 2 + radius.width/2), + y: Math.round(posy - h + radius.height/2) + }; + } else { + labelPos= { + x: Math.round(posx - w + radius.width/2), + y: Math.round(posy - h / 2 + radius.height/2) + }; + } + } else throw "align: not implemented"; + + var style = tag.style; + style.left = labelPos.x + 'px'; + style.top = labelPos.y + 'px'; + style.display = this.fitsInCanvas(labelPos, canvas)? '' : 'none'; + controller.onPlaceLabel(tag, node); + } +}); + +/* + ST.Label.SVG + + Custom extension of . + + Extends: + + All methods + + See also: + + +*/ +$jit.ST.Label.SVG = new Class({ + Implements: [$jit.ST.Label.DOM, Graph.Label.SVG], + + initialize: function(viz) { + this.viz = viz; + } +}); + +/* + ST.Label.HTML + + Custom extension of . + + Extends: + + All methods. + + See also: + + + +*/ +$jit.ST.Label.HTML = new Class({ + Implements: [$jit.ST.Label.DOM, Graph.Label.HTML], + + initialize: function(viz) { + this.viz = viz; + } +}); + + +/* + Class: ST.Plot.NodeTypes + + This class contains a list of built-in types. + Node types implemented are 'none', 'circle', 'rectangle', 'ellipse' and 'square'. + + You can add your custom node types, customizing your visualization to the extreme. + + Example: + + (start code js) + ST.Plot.NodeTypes.implement({ + 'mySpecialType': { + 'render': function(node, canvas) { + //print your custom node to canvas + }, + //optional + 'contains': function(node, pos) { + //return true if pos is inside the node or false otherwise + } + } + }); + (end code) + +*/ +$jit.ST.Plot.NodeTypes = new Class({ + 'none': { + 'render': $.empty, + 'contains': $.lambda(false) + }, + 'circle': { + 'render': function(node, canvas) { + var dim = node.getData('dim'), + pos = this.getAlignedPos(node.pos.getc(true), dim, dim), + dim2 = dim/2; + this.nodeHelper.circle.render('fill', {x:pos.x+dim2, y:pos.y+dim2}, dim2, canvas); + }, + 'contains': function(node, pos) { + var dim = node.getData('dim'), + npos = this.getAlignedPos(node.pos.getc(true), dim, dim), + dim2 = dim/2; + this.nodeHelper.circle.contains({x:npos.x+dim2, y:npos.y+dim2}, pos, dim2); + } + }, + 'square': { + 'render': function(node, canvas) { + var dim = node.getData('dim'), + dim2 = dim/2, + pos = this.getAlignedPos(node.pos.getc(true), dim, dim); + this.nodeHelper.square.render('fill', {x:pos.x+dim2, y:pos.y+dim2}, dim2, canvas); + }, + 'contains': function(node, pos) { + var dim = node.getData('dim'), + npos = this.getAlignedPos(node.pos.getc(true), dim, dim), + dim2 = dim/2; + this.nodeHelper.square.contains({x:npos.x+dim2, y:npos.y+dim2}, pos, dim2); + } + }, + 'ellipse': { + 'render': function(node, canvas) { + var width = node.getData('width'), + height = node.getData('height'), + pos = this.getAlignedPos(node.pos.getc(true), width, height); + this.nodeHelper.ellipse.render('fill', {x:pos.x+width/2, y:pos.y+height/2}, width, height, canvas); + }, + 'contains': function(node, pos) { + var width = node.getData('width'), + height = node.getData('height'), + npos = this.getAlignedPos(node.pos.getc(true), width, height); + this.nodeHelper.ellipse.contains({x:npos.x+width/2, y:npos.y+height/2}, pos, width, height); + } + }, + 'rectangle': { + 'render': function(node, canvas) { + var width = node.getData('width'), + height = node.getData('height'), + pos = this.getAlignedPos(node.pos.getc(true), width, height); + this.nodeHelper.rectangle.render('fill', {x:pos.x+width/2, y:pos.y+height/2}, width, height, canvas); + }, + 'contains': function(node, pos) { + var width = node.getData('width'), + height = node.getData('height'), + npos = this.getAlignedPos(node.pos.getc(true), width, height); + this.nodeHelper.rectangle.contains({x:npos.x+width/2, y:npos.y+height/2}, pos, width, height); + } + } +}); + +/* + Class: ST.Plot.EdgeTypes + + This class contains a list of built-in types. + Edge types implemented are 'none', 'line', 'arrow', 'quadratic:begin', 'quadratic:end', 'bezier'. + + You can add your custom edge types, customizing your visualization to the extreme. + + Example: + + (start code js) + ST.Plot.EdgeTypes.implement({ + 'mySpecialType': { + 'render': function(adj, canvas) { + //print your custom edge to canvas + }, + //optional + 'contains': function(adj, pos) { + //return true if pos is inside the arc or false otherwise + } + } + }); + (end code) + +*/ +$jit.ST.Plot.EdgeTypes = new Class({ + 'none': $.empty, + 'line': { + 'render': function(adj, canvas) { + var orn = this.getOrientation(adj), + nodeFrom = adj.nodeFrom, + nodeTo = adj.nodeTo, + rel = nodeFrom._depth < nodeTo._depth, + from = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), + to = this.viz.geom.getEdge(rel? nodeTo:nodeFrom, 'end', orn); + this.edgeHelper.line.render(from, to, canvas); + }, + 'contains': function(adj, pos) { + var orn = this.getOrientation(adj), + nodeFrom = adj.nodeFrom, + nodeTo = adj.nodeTo, + rel = nodeFrom._depth < nodeTo._depth, + from = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), + to = this.viz.geom.getEdge(rel? nodeTo:nodeFrom, 'end', orn); + return this.edgeHelper.line.contains(from, to, pos, this.edge.epsilon); + } + }, + 'arrow': { + 'render': function(adj, canvas) { + var orn = this.getOrientation(adj), + node = adj.nodeFrom, + child = adj.nodeTo, + dim = adj.getData('dim'), + from = this.viz.geom.getEdge(node, 'begin', orn), + to = this.viz.geom.getEdge(child, 'end', orn), + direction = adj.data.$direction, + inv = (direction && direction.length>1 && direction[0] != node.id); + this.edgeHelper.arrow.render(from, to, dim, inv, canvas); + }, + 'contains': function(adj, pos) { + var orn = this.getOrientation(adj), + nodeFrom = adj.nodeFrom, + nodeTo = adj.nodeTo, + rel = nodeFrom._depth < nodeTo._depth, + from = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), + to = this.viz.geom.getEdge(rel? nodeTo:nodeFrom, 'end', orn); + return this.edgeHelper.arrow.contains(from, to, pos, this.edge.epsilon); + } + }, + 'quadratic:begin': { + 'render': function(adj, canvas) { + var orn = this.getOrientation(adj); + var nodeFrom = adj.nodeFrom, + nodeTo = adj.nodeTo, + rel = nodeFrom._depth < nodeTo._depth, + begin = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), + end = this.viz.geom.getEdge(rel? nodeTo:nodeFrom, 'end', orn), + dim = adj.getData('dim'), + ctx = canvas.getCtx(); + ctx.beginPath(); + ctx.moveTo(begin.x, begin.y); + switch(orn) { + case "left": + ctx.quadraticCurveTo(begin.x + dim, begin.y, end.x, end.y); + break; + case "right": + ctx.quadraticCurveTo(begin.x - dim, begin.y, end.x, end.y); + break; + case "top": + ctx.quadraticCurveTo(begin.x, begin.y + dim, end.x, end.y); + break; + case "bottom": + ctx.quadraticCurveTo(begin.x, begin.y - dim, end.x, end.y); + break; + } + ctx.stroke(); + } + }, + 'quadratic:end': { + 'render': function(adj, canvas) { + var orn = this.getOrientation(adj); + var nodeFrom = adj.nodeFrom, + nodeTo = adj.nodeTo, + rel = nodeFrom._depth < nodeTo._depth, + begin = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), + end = this.viz.geom.getEdge(rel? nodeTo:nodeFrom, 'end', orn), + dim = adj.getData('dim'), + ctx = canvas.getCtx(); + ctx.beginPath(); + ctx.moveTo(begin.x, begin.y); + switch(orn) { + case "left": + ctx.quadraticCurveTo(end.x - dim, end.y, end.x, end.y); + break; + case "right": + ctx.quadraticCurveTo(end.x + dim, end.y, end.x, end.y); + break; + case "top": + ctx.quadraticCurveTo(end.x, end.y - dim, end.x, end.y); + break; + case "bottom": + ctx.quadraticCurveTo(end.x, end.y + dim, end.x, end.y); + break; + } + ctx.stroke(); + } + }, + 'bezier': { + 'render': function(adj, canvas) { + var orn = this.getOrientation(adj), + nodeFrom = adj.nodeFrom, + nodeTo = adj.nodeTo, + rel = nodeFrom._depth < nodeTo._depth, + begin = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), + end = this.viz.geom.getEdge(rel? nodeTo:nodeFrom, 'end', orn), + dim = adj.getData('dim'), + ctx = canvas.getCtx(); + ctx.beginPath(); + ctx.moveTo(begin.x, begin.y); + switch(orn) { + case "left": + ctx.bezierCurveTo(begin.x + dim, begin.y, end.x - dim, end.y, end.x, end.y); + break; + case "right": + ctx.bezierCurveTo(begin.x - dim, begin.y, end.x + dim, end.y, end.x, end.y); + break; + case "top": + ctx.bezierCurveTo(begin.x, begin.y + dim, end.x, end.y - dim, end.x, end.y); + break; + case "bottom": + ctx.bezierCurveTo(begin.x, begin.y - dim, end.x, end.y + dim, end.x, end.y); + break; + } + ctx.stroke(); + } + } +}); + + + +/* + * File: AreaChart.js + * +*/ + +$jit.ST.Plot.NodeTypes.implement({ + 'areachart-stacked' : { + 'render' : function(node, canvas) { + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + algnPos = this.getAlignedPos(pos, width, height), + x = algnPos.x, y = algnPos.y, + stringArray = node.getData('stringArray'), + dimArray = node.getData('dimArray'), + valArray = node.getData('valueArray'), + valLeft = $.reduce(valArray, function(x, y) { return x + y[0]; }, 0), + valRight = $.reduce(valArray, function(x, y) { return x + y[1]; }, 0), + colorArray = node.getData('colorArray'), + colorLength = colorArray.length, + config = node.getData('config'), + gradient = node.getData('gradient'), + showLabels = config.showLabels, + aggregates = config.showAggregates, + label = config.Label, + prev = node.getData('prev'); + + var ctx = canvas.getCtx(), border = node.getData('border'); + if (colorArray && dimArray && stringArray) { + for (var i=0, l=dimArray.length, acumLeft=0, acumRight=0, valAcum=0; i 0 || dimArray[i][1] > 0)) { + var h1 = acumLeft + dimArray[i][0], + h2 = acumRight + dimArray[i][1], + alpha = Math.atan((h2 - h1) / width), + delta = 55; + var linear = ctx.createLinearGradient(x + width/2, + y - (h1 + h2)/2, + x + width/2 + delta * Math.sin(alpha), + y - (h1 + h2)/2 + delta * Math.cos(alpha)); + var color = $.rgbToHex($.map($.hexToRgb(colorArray[i % colorLength].slice(1)), + function(v) { return (v * 0.85) >> 0; })); + linear.addColorStop(0, colorArray[i % colorLength]); + linear.addColorStop(1, color); + ctx.fillStyle = linear; + } + ctx.beginPath(); + ctx.moveTo(x, y - acumLeft); + ctx.lineTo(x + width, y - acumRight); + ctx.lineTo(x + width, y - acumRight - dimArray[i][1]); + ctx.lineTo(x, y - acumLeft - dimArray[i][0]); + ctx.lineTo(x, y - acumLeft); + ctx.fill(); + ctx.restore(); + if(border) { + var strong = border.name == stringArray[i]; + var perc = strong? 0.7 : 0.8; + var color = $.rgbToHex($.map($.hexToRgb(colorArray[i % colorLength].slice(1)), + function(v) { return (v * perc) >> 0; })); + ctx.strokeStyle = color; + ctx.lineWidth = strong? 4 : 1; + ctx.save(); + ctx.beginPath(); + if(border.index === 0) { + ctx.moveTo(x, y - acumLeft); + ctx.lineTo(x, y - acumLeft - dimArray[i][0]); + } else { + ctx.moveTo(x + width, y - acumRight); + ctx.lineTo(x + width, y - acumRight - dimArray[i][1]); + } + ctx.stroke(); + ctx.restore(); + } + acumLeft += (dimArray[i][0] || 0); + acumRight += (dimArray[i][1] || 0); + + if(dimArray[i][0] > 0) + valAcum += (valArray[i][0] || 0); + } + if(prev && label.type == 'Native') { + ctx.save(); + ctx.beginPath(); + ctx.fillStyle = ctx.strokeStyle = label.color; + ctx.font = label.style + ' ' + label.size + 'px ' + label.family; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + var aggValue = aggregates(node.name, valLeft, valRight, node, valAcum); + if(aggValue !== false) { + ctx.fillText(aggValue !== true? aggValue : valAcum, x, y - acumLeft - config.labelOffset - label.size/2, width); + } + if(showLabels(node.name, valLeft, valRight, node)) { + ctx.fillText(node.name, x, y + label.size/2 + config.labelOffset); + } + ctx.restore(); + } + } + }, + 'contains': function(node, mpos) { + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + algnPos = this.getAlignedPos(pos, width, height), + x = algnPos.x, y = algnPos.y, + dimArray = node.getData('dimArray'), + rx = mpos.x - x; + //bounding box check + if(mpos.x < x || mpos.x > x + width + || mpos.y > y || mpos.y < y - height) { + return false; + } + //deep check + for(var i=0, l=dimArray.length, lAcum=y, rAcum=y; i= intersec) { + var index = +(rx > width/2); + return { + 'name': node.getData('stringArray')[i], + 'color': node.getData('colorArray')[i], + 'value': node.getData('valueArray')[i][index], + 'index': index + }; + } + } + return false; + } + } +}); + +/* + Class: AreaChart + + A visualization that displays stacked area charts. + + Constructor Options: + + See . + +*/ +$jit.AreaChart = new Class({ + st: null, + colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"], + selected: {}, + busy: false, + + initialize: function(opt) { + this.controller = this.config = + $.merge(Options("Canvas", "Margin", "Label", "AreaChart"), { + Label: { type: 'Native' } + }, opt); + //set functions for showLabels and showAggregates + var showLabels = this.config.showLabels, + typeLabels = $.type(showLabels), + showAggregates = this.config.showAggregates, + typeAggregates = $.type(showAggregates); + this.config.showLabels = typeLabels == 'function'? showLabels : $.lambda(showLabels); + this.config.showAggregates = typeAggregates == 'function'? showAggregates : $.lambda(showAggregates); + + this.initializeViz(); + }, + + initializeViz: function() { + var config = this.config, + that = this, + nodeType = config.type.split(":")[0], + nodeLabels = {}; + + var delegate = new $jit.ST({ + injectInto: config.injectInto, + width: config.width, + height: config.height, + orientation: "bottom", + levelDistance: 0, + siblingOffset: 0, + subtreeOffset: 0, + withLabels: config.Label.type != 'Native', + useCanvas: config.useCanvas, + Label: { + type: config.Label.type + }, + Node: { + overridable: true, + type: 'areachart-' + nodeType, + align: 'left', + width: 1, + height: 1 + }, + Edge: { + type: 'none' + }, + Tips: { + enable: config.Tips.enable, + type: 'Native', + force: true, + onShow: function(tip, node, contains) { + var elem = contains; + config.Tips.onShow(tip, elem, node); + } + }, + Events: { + enable: true, + type: 'Native', + onClick: function(node, eventInfo, evt) { + if(!config.filterOnClick && !config.Events.enable) return; + var elem = eventInfo.getContains(); + if(elem) config.filterOnClick && that.filter(elem.name); + config.Events.enable && config.Events.onClick(elem, eventInfo, evt); + }, + onRightClick: function(node, eventInfo, evt) { + if(!config.restoreOnRightClick) return; + that.restore(); + }, + onMouseMove: function(node, eventInfo, evt) { + if(!config.selectOnHover) return; + if(node) { + var elem = eventInfo.getContains(); + that.select(node.id, elem.name, elem.index); + } else { + that.select(false, false, false); + } + } + }, + onCreateLabel: function(domElement, node) { + var labelConf = config.Label, + valueArray = node.getData('valueArray'), + acumLeft = $.reduce(valueArray, function(x, y) { return x + y[0]; }, 0), + acumRight = $.reduce(valueArray, function(x, y) { return x + y[1]; }, 0); + if(node.getData('prev')) { + var nlbs = { + wrapper: document.createElement('div'), + aggregate: document.createElement('div'), + label: document.createElement('div') + }; + var wrapper = nlbs.wrapper, + label = nlbs.label, + aggregate = nlbs.aggregate, + wrapperStyle = wrapper.style, + labelStyle = label.style, + aggregateStyle = aggregate.style; + //store node labels + nodeLabels[node.id] = nlbs; + //append labels + wrapper.appendChild(label); + wrapper.appendChild(aggregate); + if(!config.showLabels(node.name, acumLeft, acumRight, node)) { + label.style.display = 'none'; + } + if(!config.showAggregates(node.name, acumLeft, acumRight, node)) { + aggregate.style.display = 'none'; + } + wrapperStyle.position = 'relative'; + wrapperStyle.overflow = 'visible'; + wrapperStyle.fontSize = labelConf.size + 'px'; + wrapperStyle.fontFamily = labelConf.family; + wrapperStyle.color = labelConf.color; + wrapperStyle.textAlign = 'center'; + aggregateStyle.position = labelStyle.position = 'absolute'; + + domElement.style.width = node.getData('width') + 'px'; + domElement.style.height = node.getData('height') + 'px'; + label.innerHTML = node.name; + + domElement.appendChild(wrapper); + } + }, + onPlaceLabel: function(domElement, node) { + if(!node.getData('prev')) return; + var labels = nodeLabels[node.id], + wrapperStyle = labels.wrapper.style, + labelStyle = labels.label.style, + aggregateStyle = labels.aggregate.style, + width = node.getData('width'), + height = node.getData('height'), + dimArray = node.getData('dimArray'), + valArray = node.getData('valueArray'), + acumLeft = $.reduce(valArray, function(x, y) { return x + y[0]; }, 0), + acumRight = $.reduce(valArray, function(x, y) { return x + y[1]; }, 0), + font = parseInt(wrapperStyle.fontSize, 10), + domStyle = domElement.style; + + if(dimArray && valArray) { + if(config.showLabels(node.name, acumLeft, acumRight, node)) { + labelStyle.display = ''; + } else { + labelStyle.display = 'none'; + } + var aggValue = config.showAggregates(node.name, acumLeft, acumRight, node); + if(aggValue !== false) { + aggregateStyle.display = ''; + } else { + aggregateStyle.display = 'none'; + } + wrapperStyle.width = aggregateStyle.width = labelStyle.width = domElement.style.width = width + 'px'; + aggregateStyle.left = labelStyle.left = -width/2 + 'px'; + for(var i=0, l=valArray.length, acum=0, leftAcum=0; i 0) { + acum+= valArray[i][0]; + leftAcum+= dimArray[i][0]; + } + } + aggregateStyle.top = (-font - config.labelOffset) + 'px'; + labelStyle.top = (config.labelOffset + leftAcum) + 'px'; + domElement.style.top = parseInt(domElement.style.top, 10) - leftAcum + 'px'; + domElement.style.height = wrapperStyle.height = leftAcum + 'px'; + labels.aggregate.innerHTML = aggValue !== true? aggValue : acum; + } + } + }); + + var size = delegate.canvas.getSize(), + margin = config.Margin; + delegate.config.offsetY = -size.height/2 + margin.bottom + + (config.showLabels && (config.labelOffset + config.Label.size)); + delegate.config.offsetX = (margin.right - margin.left)/2; + this.delegate = delegate; + this.canvas = this.delegate.canvas; + }, + + /* + Method: loadJSON + + Loads JSON data into the visualization. + + Parameters: + + json - The JSON data format. This format is described in . + + Example: + (start code js) + var areaChart = new $jit.AreaChart(options); + areaChart.loadJSON(json); + (end code) + */ + loadJSON: function(json) { + var prefix = $.time(), + ch = [], + delegate = this.delegate, + name = $.splat(json.label), + color = $.splat(json.color || this.colors), + config = this.config, + gradient = !!config.type.split(":")[1], + animate = config.animate; + + for(var i=0, values=json.values, l=values.length; i. + onComplete - (object) A callback object to be called when the animation transition when updating the data end. + + Example: + + (start code js) + areaChart.updateJSON(json, { + onComplete: function() { + alert('update complete!'); + } + }); + (end code) + */ + updateJSON: function(json, onComplete) { + if(this.busy) return; + this.busy = true; + + var delegate = this.delegate, + graph = delegate.graph, + labels = json.label && $.splat(json.label), + values = json.values, + animate = this.config.animate, + that = this, + hashValues = {}; + + //convert the whole thing into a hash + for (var i = 0, l = values.length; i < l; i++) { + hashValues[values[i].label] = values[i]; + } + + graph.eachNode(function(n) { + var v = hashValues[n.name], + stringArray = n.getData('stringArray'), + valArray = n.getData('valueArray'), + next = n.getData('next'); + + if (v) { + v.values = $.splat(v.values); + $.each(valArray, function(a, i) { + a[0] = v.values[i]; + if(labels) stringArray[i] = labels[i]; + }); + n.setData('valueArray', valArray); + } + + if(next) { + v = hashValues[next]; + if(v) { + $.each(valArray, function(a, i) { + a[1] = v.values[i]; + }); + } + } + }); + this.normalizeDims(); + delegate.compute(); + delegate.select(delegate.root); + if(animate) { + delegate.fx.animate({ + modes: ['node-property:height:dimArray'], + duration:1500, + onComplete: function() { + that.busy = false; + onComplete && onComplete.onComplete(); + } + }); + } + }, + +/* + Method: filter + + Filter selected stacks, collapsing all other stacks. You can filter multiple stacks at the same time. + + Parameters: + + filters - (array) An array of strings with the name of the stacks to be filtered. + callback - (object) An object with an *onComplete* callback method. + + Example: + + (start code js) + areaChart.filter(['label A', 'label C'], { + onComplete: function() { + console.log('done!'); + } + }); + (end code) + + See also: + + . + */ + filter: function(filters, callback) { + if(this.busy) return; + this.busy = true; + if(this.config.Tips.enable) this.delegate.tips.hide(); + this.select(false, false, false); + var args = $.splat(filters); + var rt = this.delegate.graph.getNode(this.delegate.root); + var that = this; + this.normalizeDims(); + rt.eachAdjacency(function(adj) { + var n = adj.nodeTo, + dimArray = n.getData('dimArray', 'end'), + stringArray = n.getData('stringArray'); + n.setData('dimArray', $.map(dimArray, function(d, i) { + return ($.indexOf(args, stringArray[i]) > -1)? d:[0, 0]; + }), 'end'); + }); + this.delegate.fx.animate({ + modes: ['node-property:dimArray'], + duration:1500, + onComplete: function() { + that.busy = false; + callback && callback.onComplete(); + } + }); + }, + + /* + Method: restore + + Sets all stacks that could have been filtered visible. + + Example: + + (start code js) + areaChart.restore(); + (end code) + + See also: + + . + */ + restore: function(callback) { + if(this.busy) return; + this.busy = true; + if(this.config.Tips.enable) this.delegate.tips.hide(); + this.select(false, false, false); + this.normalizeDims(); + var that = this; + this.delegate.fx.animate({ + modes: ['node-property:height:dimArray'], + duration:1500, + onComplete: function() { + that.busy = false; + callback && callback.onComplete(); + } + }); + }, + //adds the little brown bar when hovering the node + select: function(id, name, index) { + if(!this.config.selectOnHover) return; + var s = this.selected; + if(s.id != id || s.name != name + || s.index != index) { + s.id = id; + s.name = name; + s.index = index; + this.delegate.graph.eachNode(function(n) { + n.setData('border', false); + }); + if(id) { + var n = this.delegate.graph.getNode(id); + n.setData('border', s); + var link = index === 0? 'prev':'next'; + link = n.getData(link); + if(link) { + n = this.delegate.graph.getByName(link); + if(n) { + n.setData('border', { + name: name, + index: 1-index + }); + } + } + } + this.delegate.plot(); + } + }, + + /* + Method: getLegend + + Returns an object containing as keys the legend names and as values hex strings with color values. + + Example: + + (start code js) + var legend = areaChart.getLegend(); + (end code) + */ + getLegend: function() { + var legend = {}; + var n; + this.delegate.graph.getNode(this.delegate.root).eachAdjacency(function(adj) { + n = adj.nodeTo; + }); + var colors = n.getData('colorArray'), + len = colors.length; + $.each(n.getData('stringArray'), function(s, i) { + legend[s] = colors[i % len]; + }); + return legend; + }, + + /* + Method: getMaxValue + + Returns the maximum accumulated value for the stacks. This method is used for normalizing the graph heights according to the canvas height. + + Example: + + (start code js) + var ans = areaChart.getMaxValue(); + (end code) + + In some cases it could be useful to override this method to normalize heights for a group of AreaCharts, like when doing small multiples. + + Example: + + (start code js) + //will return 100 for all AreaChart instances, + //displaying all of them with the same scale + $jit.AreaChart.implement({ + 'getMaxValue': function() { + return 100; + } + }); + (end code) + +*/ + getMaxValue: function() { + var maxValue = 0; + this.delegate.graph.eachNode(function(n) { + var valArray = n.getData('valueArray'), + acumLeft = 0, acumRight = 0; + $.each(valArray, function(v) { + acumLeft += +v[0]; + acumRight += +v[1]; + }); + var acum = acumRight>acumLeft? acumRight:acumLeft; + maxValue = maxValue>acum? maxValue:acum; + }); + return maxValue; + }, + + normalizeDims: function() { + //number of elements + var root = this.delegate.graph.getNode(this.delegate.root), l=0; + root.eachAdjacency(function() { + l++; + }); + var maxValue = this.getMaxValue() || 1, + size = this.delegate.canvas.getSize(), + config = this.config, + margin = config.Margin, + labelOffset = config.labelOffset + config.Label.size, + fixedDim = (size.width - (margin.left + margin.right)) / l, + animate = config.animate, + height = size.height - (margin.top + margin.bottom) - (config.showAggregates && labelOffset) + - (config.showLabels && labelOffset); + this.delegate.graph.eachNode(function(n) { + var acumLeft = 0, acumRight = 0, animateValue = []; + $.each(n.getData('valueArray'), function(v) { + acumLeft += +v[0]; + acumRight += +v[1]; + animateValue.push([0, 0]); + }); + var acum = acumRight>acumLeft? acumRight:acumLeft; + n.setData('width', fixedDim); + if(animate) { + n.setData('height', acum * height / maxValue, 'end'); + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return [n[0] * height / maxValue, n[1] * height / maxValue]; + }), 'end'); + var dimArray = n.getData('dimArray'); + if(!dimArray) { + n.setData('dimArray', animateValue); + } + } else { + n.setData('height', acum * height / maxValue); + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return [n[0] * height / maxValue, n[1] * height / maxValue]; + })); + } + }); + } +}); + + +/* + * File: Options.BarChart.js + * +*/ + +/* + Object: Options.BarChart + + options. + Other options included in the BarChart are , , , and . + + Syntax: + + (start code js) + + Options.BarChart = { + animate: true, + labelOffset: 3, + barsOffset: 0, + type: 'stacked', + hoveredColor: '#9fd4ff', + orientation: 'horizontal', + showAggregates: true, + showLabels: true + }; + + (end code) + + Example: + + (start code js) + + var barChart = new $jit.BarChart({ + animate: true, + barsOffset: 10, + type: 'stacked:gradient' + }); + + (end code) + + Parameters: + + animate - (boolean) Default's *true*. Whether to add animated transitions when filtering/restoring stacks. + offset - (number) Default's *25*. Adds margin between the visualization and the canvas. + labelOffset - (number) Default's *3*. Adds margin between the label and the default place where it should be drawn. + barsOffset - (number) Default's *0*. Separation between bars. + type - (string) Default's *'stacked'*. Stack or grouped styles. Posible values are 'stacked', 'grouped', 'stacked:gradient', 'grouped:gradient' to add gradients. + hoveredColor - (boolean|string) Default's *'#9fd4ff'*. Sets the selected color for a hovered bar stack. + orientation - (string) Default's 'horizontal'. Sets the direction of the bars. Possible options are 'vertical' or 'horizontal'. + showAggregates - (boolean, function) Default's *true*. Display the sum the values of each bar. Can also be a function that returns *true* or *false* to display the value of the bar or not. That same function can also return a string with the formatted data to be added. + showLabels - (boolean, function) Default's *true*. Display the name of the slots. Can also be a function that returns *true* or *false* for each bar to decide whether to show the label or not. + +*/ + +Options.BarChart = { + $extend: true, + + animate: true, + type: 'stacked', //stacked, grouped, : gradient + labelOffset: 3, //label offset + barsOffset: 0, //distance between bars + hoveredColor: '#9fd4ff', + orientation: 'horizontal', + showAggregates: true, + showLabels: true, + Tips: { + enable: false, + onShow: $.empty, + onHide: $.empty + }, + Events: { + enable: false, + onClick: $.empty + } +}; + +/* + * File: BarChart.js + * +*/ + +$jit.ST.Plot.NodeTypes.implement({ + 'barchart-stacked' : { + 'render' : function(node, canvas) { + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + algnPos = this.getAlignedPos(pos, width, height), + x = algnPos.x, y = algnPos.y, + dimArray = node.getData('dimArray'), + valueArray = node.getData('valueArray'), + colorArray = node.getData('colorArray'), + colorLength = colorArray.length, + stringArray = node.getData('stringArray'); + + var ctx = canvas.getCtx(), + opt = {}, + border = node.getData('border'), + gradient = node.getData('gradient'), + config = node.getData('config'), + horz = config.orientation == 'horizontal', + aggregates = config.showAggregates, + showLabels = config.showLabels, + label = config.Label; + + if (colorArray && dimArray && stringArray) { + for (var i=0, l=dimArray.length, acum=0, valAcum=0; i> 0; })); + linear.addColorStop(0, color); + linear.addColorStop(0.5, colorArray[i % colorLength]); + linear.addColorStop(1, color); + ctx.fillStyle = linear; + } + if(horz) { + ctx.fillRect(x + acum, y, dimArray[i], height); + } else { + ctx.fillRect(x, y - acum - dimArray[i], width, dimArray[i]); + } + if(border && border.name == stringArray[i]) { + opt.acum = acum; + opt.dimValue = dimArray[i]; + } + acum += (dimArray[i] || 0); + valAcum += (valueArray[i] || 0); + } + if(border) { + ctx.save(); + ctx.lineWidth = 2; + ctx.strokeStyle = border.color; + if(horz) { + ctx.strokeRect(x + opt.acum + 1, y + 1, opt.dimValue -2, height - 2); + } else { + ctx.strokeRect(x + 1, y - opt.acum - opt.dimValue + 1, width -2, opt.dimValue -2); + } + ctx.restore(); + } + if(label.type == 'Native') { + ctx.save(); + ctx.fillStyle = ctx.strokeStyle = label.color; + ctx.font = label.style + ' ' + label.size + 'px ' + label.family; + ctx.textBaseline = 'middle'; + var aggValue = aggregates(node.name, valAcum, node); + if(aggValue !== false) { + aggValue = aggValue !== true? aggValue : valAcum; + if(horz) { + ctx.textAlign = 'right'; + ctx.fillText(aggValue, x + acum - config.labelOffset, y + height/2); + } else { + ctx.textAlign = 'center'; + ctx.fillText(aggValue, x + width/2, y - height - label.size/2 - config.labelOffset); + } + } + if(showLabels(node.name, valAcum, node)) { + if(horz) { + ctx.textAlign = 'center'; + ctx.translate(x - config.labelOffset - label.size/2, y + height/2); + ctx.rotate(Math.PI / 2); + ctx.fillText(node.name, 0, 0); + } else { + ctx.textAlign = 'center'; + ctx.fillText(node.name, x + width/2, y + label.size/2 + config.labelOffset); + } + } + ctx.restore(); + } + } + }, + 'contains': function(node, mpos) { + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + algnPos = this.getAlignedPos(pos, width, height), + x = algnPos.x, y = algnPos.y, + dimArray = node.getData('dimArray'), + config = node.getData('config'), + rx = mpos.x - x, + horz = config.orientation == 'horizontal'; + //bounding box check + if(horz) { + if(mpos.x < x || mpos.x > x + width + || mpos.y > y + height || mpos.y < y) { + return false; + } + } else { + if(mpos.x < x || mpos.x > x + width + || mpos.y > y || mpos.y < y - height) { + return false; + } + } + //deep check + for(var i=0, l=dimArray.length, acum=(horz? x:y); i= intersec) { + return { + 'name': node.getData('stringArray')[i], + 'color': node.getData('colorArray')[i], + 'value': node.getData('valueArray')[i], + 'label': node.name + }; + } + } + } + return false; + } + }, + 'barchart-grouped' : { + 'render' : function(node, canvas) { + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + algnPos = this.getAlignedPos(pos, width, height), + x = algnPos.x, y = algnPos.y, + dimArray = node.getData('dimArray'), + valueArray = node.getData('valueArray'), + valueLength = valueArray.length, + colorArray = node.getData('colorArray'), + colorLength = colorArray.length, + stringArray = node.getData('stringArray'); + + var ctx = canvas.getCtx(), + opt = {}, + border = node.getData('border'), + gradient = node.getData('gradient'), + config = node.getData('config'), + horz = config.orientation == 'horizontal', + aggregates = config.showAggregates, + showLabels = config.showLabels, + label = config.Label, + fixedDim = (horz? height : width) / valueLength; + + if (colorArray && dimArray && stringArray) { + for (var i=0, l=valueLength, acum=0, valAcum=0; i> 0; })); + linear.addColorStop(0, color); + linear.addColorStop(0.5, colorArray[i % colorLength]); + linear.addColorStop(1, color); + ctx.fillStyle = linear; + } + if(horz) { + ctx.fillRect(x, y + fixedDim * i, dimArray[i], fixedDim); + } else { + ctx.fillRect(x + fixedDim * i, y - dimArray[i], fixedDim, dimArray[i]); + } + if(border && border.name == stringArray[i]) { + opt.acum = fixedDim * i; + opt.dimValue = dimArray[i]; + } + acum += (dimArray[i] || 0); + valAcum += (valueArray[i] || 0); + } + if(border) { + ctx.save(); + ctx.lineWidth = 2; + ctx.strokeStyle = border.color; + if(horz) { + ctx.strokeRect(x + 1, y + opt.acum + 1, opt.dimValue -2, fixedDim - 2); + } else { + ctx.strokeRect(x + opt.acum + 1, y - opt.dimValue + 1, fixedDim -2, opt.dimValue -2); + } + ctx.restore(); + } + if(label.type == 'Native') { + ctx.save(); + ctx.fillStyle = ctx.strokeStyle = label.color; + ctx.font = label.style + ' ' + label.size + 'px ' + label.family; + ctx.textBaseline = 'middle'; + var aggValue = aggregates(node.name, valAcum, node); + if(aggValue !== false) { + aggValue = aggValue !== true? aggValue : valAcum; + if(horz) { + ctx.textAlign = 'right'; + ctx.fillText(aggValue, x + Math.max.apply(null, dimArray) - config.labelOffset, y + height/2); + } else { + ctx.textAlign = 'center'; + ctx.fillText(aggValue, x + width/2, y - Math.max.apply(null, dimArray) - label.size/2 - config.labelOffset); + } + } + if(showLabels(node.name, valAcum, node)) { + if(horz) { + ctx.textAlign = 'center'; + ctx.translate(x - config.labelOffset - label.size/2, y + height/2); + ctx.rotate(Math.PI / 2); + ctx.fillText(node.name, 0, 0); + } else { + ctx.textAlign = 'center'; + ctx.fillText(node.name, x + width/2, y + label.size/2 + config.labelOffset); + } + } + ctx.restore(); + } + } + }, + 'contains': function(node, mpos) { + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + algnPos = this.getAlignedPos(pos, width, height), + x = algnPos.x, y = algnPos.y, + dimArray = node.getData('dimArray'), + len = dimArray.length, + config = node.getData('config'), + rx = mpos.x - x, + horz = config.orientation == 'horizontal', + fixedDim = (horz? height : width) / len; + //bounding box check + if(horz) { + if(mpos.x < x || mpos.x > x + width + || mpos.y > y + height || mpos.y < y) { + return false; + } + } else { + if(mpos.x < x || mpos.x > x + width + || mpos.y > y || mpos.y < y - height) { + return false; + } + } + //deep check + for(var i=0, l=dimArray.length; i= limit && mpos.y <= limit + fixedDim) { + return { + 'name': node.getData('stringArray')[i], + 'color': node.getData('colorArray')[i], + 'value': node.getData('valueArray')[i], + 'label': node.name + }; + } + } else { + var limit = x + fixedDim * i; + if(mpos.x >= limit && mpos.x <= limit + fixedDim && mpos.y >= y - dimi) { + return { + 'name': node.getData('stringArray')[i], + 'color': node.getData('colorArray')[i], + 'value': node.getData('valueArray')[i], + 'label': node.name + }; + } + } + } + return false; + } + } +}); + +/* + Class: BarChart + + A visualization that displays stacked bar charts. + + Constructor Options: + + See . + +*/ +$jit.BarChart = new Class({ + st: null, + colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"], + selected: {}, + busy: false, + + initialize: function(opt) { + this.controller = this.config = + $.merge(Options("Canvas", "Margin", "Label", "BarChart"), { + Label: { type: 'Native' } + }, opt); + //set functions for showLabels and showAggregates + var showLabels = this.config.showLabels, + typeLabels = $.type(showLabels), + showAggregates = this.config.showAggregates, + typeAggregates = $.type(showAggregates); + this.config.showLabels = typeLabels == 'function'? showLabels : $.lambda(showLabels); + this.config.showAggregates = typeAggregates == 'function'? showAggregates : $.lambda(showAggregates); + + this.initializeViz(); + }, + + initializeViz: function() { + var config = this.config, that = this; + var nodeType = config.type.split(":")[0], + horz = config.orientation == 'horizontal', + nodeLabels = {}; + + var delegate = new $jit.ST({ + injectInto: config.injectInto, + width: config.width, + height: config.height, + orientation: horz? 'left' : 'bottom', + levelDistance: 0, + siblingOffset: config.barsOffset, + subtreeOffset: 0, + withLabels: config.Label.type != 'Native', + useCanvas: config.useCanvas, + Label: { + type: config.Label.type + }, + Node: { + overridable: true, + type: 'barchart-' + nodeType, + align: 'left', + width: 1, + height: 1 + }, + Edge: { + type: 'none' + }, + Tips: { + enable: config.Tips.enable, + type: 'Native', + force: true, + onShow: function(tip, node, contains) { + var elem = contains; + config.Tips.onShow(tip, elem, node); + } + }, + Events: { + enable: true, + type: 'Native', + onClick: function(node, eventInfo, evt) { + if(!config.Events.enable) return; + var elem = eventInfo.getContains(); + config.Events.onClick(elem, eventInfo, evt); + }, + onMouseMove: function(node, eventInfo, evt) { + if(!config.hoveredColor) return; + if(node) { + var elem = eventInfo.getContains(); + that.select(node.id, elem.name, elem.index); + } else { + that.select(false, false, false); + } + } + }, + onCreateLabel: function(domElement, node) { + var labelConf = config.Label, + valueArray = node.getData('valueArray'), + acum = $.reduce(valueArray, function(x, y) { return x + y; }, 0); + var nlbs = { + wrapper: document.createElement('div'), + aggregate: document.createElement('div'), + label: document.createElement('div') + }; + var wrapper = nlbs.wrapper, + label = nlbs.label, + aggregate = nlbs.aggregate, + wrapperStyle = wrapper.style, + labelStyle = label.style, + aggregateStyle = aggregate.style; + //store node labels + nodeLabels[node.id] = nlbs; + //append labels + wrapper.appendChild(label); + wrapper.appendChild(aggregate); + if(!config.showLabels(node.name, acum, node)) { + labelStyle.display = 'none'; + } + if(!config.showAggregates(node.name, acum, node)) { + aggregateStyle.display = 'none'; + } + wrapperStyle.position = 'relative'; + wrapperStyle.overflow = 'visible'; + wrapperStyle.fontSize = labelConf.size + 'px'; + wrapperStyle.fontFamily = labelConf.family; + wrapperStyle.color = labelConf.color; + wrapperStyle.textAlign = 'center'; + aggregateStyle.position = labelStyle.position = 'absolute'; + + domElement.style.width = node.getData('width') + 'px'; + domElement.style.height = node.getData('height') + 'px'; + aggregateStyle.left = labelStyle.left = '0px'; + + label.innerHTML = node.name; + + domElement.appendChild(wrapper); + }, + onPlaceLabel: function(domElement, node) { + if(!nodeLabels[node.id]) return; + var labels = nodeLabels[node.id], + wrapperStyle = labels.wrapper.style, + labelStyle = labels.label.style, + aggregateStyle = labels.aggregate.style, + grouped = config.type.split(':')[0] == 'grouped', + horz = config.orientation == 'horizontal', + dimArray = node.getData('dimArray'), + valArray = node.getData('valueArray'), + width = (grouped && horz)? Math.max.apply(null, dimArray) : node.getData('width'), + height = (grouped && !horz)? Math.max.apply(null, dimArray) : node.getData('height'), + font = parseInt(wrapperStyle.fontSize, 10), + domStyle = domElement.style; + + + if(dimArray && valArray) { + wrapperStyle.width = aggregateStyle.width = labelStyle.width = domElement.style.width = width + 'px'; + for(var i=0, l=valArray.length, acum=0; i 0) { + acum+= valArray[i]; + } + } + if(config.showLabels(node.name, acum, node)) { + labelStyle.display = ''; + } else { + labelStyle.display = 'none'; + } + var aggValue = config.showAggregates(node.name, acum, node); + if(aggValue !== false) { + aggregateStyle.display = ''; + } else { + aggregateStyle.display = 'none'; + } + if(config.orientation == 'horizontal') { + aggregateStyle.textAlign = 'right'; + labelStyle.textAlign = 'left'; + labelStyle.textIndex = aggregateStyle.textIndent = config.labelOffset + 'px'; + aggregateStyle.top = labelStyle.top = (height-font)/2 + 'px'; + domElement.style.height = wrapperStyle.height = height + 'px'; + } else { + aggregateStyle.top = (-font - config.labelOffset) + 'px'; + labelStyle.top = (config.labelOffset + height) + 'px'; + domElement.style.top = parseInt(domElement.style.top, 10) - height + 'px'; + domElement.style.height = wrapperStyle.height = height + 'px'; + } + labels.aggregate.innerHTML = aggValue !== true? aggValue : acum; + } + } + }); + + var size = delegate.canvas.getSize(), + margin = config.Margin; + if(horz) { + delegate.config.offsetX = size.width/2 - margin.left + - (config.showLabels && (config.labelOffset + config.Label.size)); + delegate.config.offsetY = (margin.bottom - margin.top)/2; + } else { + delegate.config.offsetY = -size.height/2 + margin.bottom + + (config.showLabels && (config.labelOffset + config.Label.size)); + delegate.config.offsetX = (margin.right - margin.left)/2; + } + this.delegate = delegate; + this.canvas = this.delegate.canvas; + }, + + /* + Method: loadJSON + + Loads JSON data into the visualization. + + Parameters: + + json - The JSON data format. This format is described in . + + Example: + (start code js) + var barChart = new $jit.BarChart(options); + barChart.loadJSON(json); + (end code) + */ + loadJSON: function(json) { + if(this.busy) return; + this.busy = true; + + var prefix = $.time(), + ch = [], + delegate = this.delegate, + name = $.splat(json.label), + color = $.splat(json.color || this.colors), + config = this.config, + gradient = !!config.type.split(":")[1], + animate = config.animate, + horz = config.orientation == 'horizontal', + that = this; + + for(var i=0, values=json.values, l=values.length; i. + onComplete - (object) A callback object to be called when the animation transition when updating the data end. + + Example: + + (start code js) + barChart.updateJSON(json, { + onComplete: function() { + alert('update complete!'); + } + }); + (end code) + */ + updateJSON: function(json, onComplete) { + if(this.busy) return; + this.busy = true; + this.select(false, false, false); + var delegate = this.delegate; + var graph = delegate.graph; + var values = json.values; + var animate = this.config.animate; + var that = this; + var horz = this.config.orientation == 'horizontal'; + $.each(values, function(v) { + var n = graph.getByName(v.label); + if(n) { + n.setData('valueArray', $.splat(v.values)); + if(json.label) { + n.setData('stringArray', $.splat(json.label)); + } + } + }); + this.normalizeDims(); + delegate.compute(); + delegate.select(delegate.root); + if(animate) { + if(horz) { + delegate.fx.animate({ + modes: ['node-property:width:dimArray'], + duration:1500, + onComplete: function() { + that.busy = false; + onComplete && onComplete.onComplete(); + } + }); + } else { + delegate.fx.animate({ + modes: ['node-property:height:dimArray'], + duration:1500, + onComplete: function() { + that.busy = false; + onComplete && onComplete.onComplete(); + } + }); + } + } + }, + + //adds the little brown bar when hovering the node + select: function(id, name) { + if(!this.config.hoveredColor) return; + var s = this.selected; + if(s.id != id || s.name != name) { + s.id = id; + s.name = name; + s.color = this.config.hoveredColor; + this.delegate.graph.eachNode(function(n) { + if(id == n.id) { + n.setData('border', s); + } else { + n.setData('border', false); + } + }); + this.delegate.plot(); + } + }, + + /* + Method: getLegend + + Returns an object containing as keys the legend names and as values hex strings with color values. + + Example: + + (start code js) + var legend = barChart.getLegend(); + (end code) + */ + getLegend: function() { + var legend = {}; + var n; + this.delegate.graph.getNode(this.delegate.root).eachAdjacency(function(adj) { + n = adj.nodeTo; + }); + var colors = n.getData('colorArray'), + len = colors.length; + $.each(n.getData('stringArray'), function(s, i) { + legend[s] = colors[i % len]; + }); + return legend; + }, + + /* + Method: getMaxValue + + Returns the maximum accumulated value for the stacks. This method is used for normalizing the graph heights according to the canvas height. + + Example: + + (start code js) + var ans = barChart.getMaxValue(); + (end code) + + In some cases it could be useful to override this method to normalize heights for a group of BarCharts, like when doing small multiples. + + Example: + + (start code js) + //will return 100 for all BarChart instances, + //displaying all of them with the same scale + $jit.BarChart.implement({ + 'getMaxValue': function() { + return 100; + } + }); + (end code) + + */ + getMaxValue: function() { + var maxValue = 0, stacked = this.config.type.split(':')[0] == 'stacked'; + this.delegate.graph.eachNode(function(n) { + var valArray = n.getData('valueArray'), + acum = 0; + if(!valArray) return; + if(stacked) { + $.each(valArray, function(v) { + acum += +v; + }); + } else { + acum = Math.max.apply(null, valArray); + } + maxValue = maxValue>acum? maxValue:acum; + }); + return maxValue; + }, + + setBarType: function(type) { + this.config.type = type; + this.delegate.config.Node.type = 'barchart-' + type.split(':')[0]; + }, + + normalizeDims: function() { + //number of elements + var root = this.delegate.graph.getNode(this.delegate.root), l=0; + root.eachAdjacency(function() { + l++; + }); + var maxValue = this.getMaxValue() || 1, + size = this.delegate.canvas.getSize(), + config = this.config, + margin = config.Margin, + marginWidth = margin.left + margin.right, + marginHeight = margin.top + margin.bottom, + horz = config.orientation == 'horizontal', + fixedDim = (size[horz? 'height':'width'] - (horz? marginHeight:marginWidth) - (l -1) * config.barsOffset) / l, + animate = config.animate, + height = size[horz? 'width':'height'] - (horz? marginWidth:marginHeight) + - (!horz && config.showAggregates && (config.Label.size + config.labelOffset)) + - (config.showLabels && (config.Label.size + config.labelOffset)), + dim1 = horz? 'height':'width', + dim2 = horz? 'width':'height'; + this.delegate.graph.eachNode(function(n) { + var acum = 0, animateValue = []; + $.each(n.getData('valueArray'), function(v) { + acum += +v; + animateValue.push(0); + }); + n.setData(dim1, fixedDim); + if(animate) { + n.setData(dim2, acum * height / maxValue, 'end'); + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return n * height / maxValue; + }), 'end'); + var dimArray = n.getData('dimArray'); + if(!dimArray) { + n.setData('dimArray', animateValue); + } + } else { + n.setData(dim2, acum * height / maxValue); + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return n * height / maxValue; + })); + } + }); + } +}); + + +/* + * File: Options.PieChart.js + * +*/ +/* + Object: Options.PieChart + + options. + Other options included in the PieChart are , , and . + + Syntax: + + (start code js) + + Options.PieChart = { + animate: true, + offset: 25, + sliceOffset:0, + labelOffset: 3, + type: 'stacked', + hoveredColor: '#9fd4ff', + showLabels: true, + resizeLabels: false, + updateHeights: false + }; + + (end code) + + Example: + + (start code js) + + var pie = new $jit.PieChart({ + animate: true, + sliceOffset: 5, + type: 'stacked:gradient' + }); + + (end code) + + Parameters: + + animate - (boolean) Default's *true*. Whether to add animated transitions when plotting/updating the visualization. + offset - (number) Default's *25*. Adds margin between the visualization and the canvas. + sliceOffset - (number) Default's *0*. Separation between the center of the canvas and each pie slice. + labelOffset - (number) Default's *3*. Adds margin between the label and the default place where it should be drawn. + type - (string) Default's *'stacked'*. Stack style. Posible values are 'stacked', 'stacked:gradient' to add gradients. + hoveredColor - (boolean|string) Default's *'#9fd4ff'*. Sets the selected color for a hovered pie stack. + showLabels - (boolean) Default's *true*. Display the name of the slots. + resizeLabels - (boolean|number) Default's *false*. Resize the pie labels according to their stacked values. Set a number for *resizeLabels* to set a font size minimum. + updateHeights - (boolean) Default's *false*. Only for mono-valued (most common) pie charts. Resize the height of the pie slices according to their current values. + +*/ +Options.PieChart = { + $extend: true, + + animate: true, + offset: 25, // page offset + sliceOffset:0, + labelOffset: 3, // label offset + type: 'stacked', // gradient + hoveredColor: '#9fd4ff', + Events: { + enable: false, + onClick: $.empty + }, + Tips: { + enable: false, + onShow: $.empty, + onHide: $.empty + }, + showLabels: true, + resizeLabels: false, + + //only valid for mono-valued datasets + updateHeights: false +}; + +/* + * Class: Layouts.Radial + * + * Implements a Radial Layout. + * + * Implemented By: + * + * , + * + */ +Layouts.Radial = new Class({ + + /* + * Method: compute + * + * Computes nodes' positions. + * + * Parameters: + * + * property - _optional_ A position property to store the new + * positions. Possible values are 'pos', 'end' or 'start'. + * + */ + compute : function(property) { + var prop = $.splat(property || [ 'current', 'start', 'end' ]); + NodeDim.compute(this.graph, prop, this.config); + this.graph.computeLevels(this.root, 0, "ignore"); + var lengthFunc = this.createLevelDistanceFunc(); + this.computeAngularWidths(prop); + this.computePositions(prop, lengthFunc); + }, + + /* + * computePositions + * + * Performs the main algorithm for computing node positions. + */ + computePositions : function(property, getLength) { + var propArray = property; + var graph = this.graph; + var root = graph.getNode(this.root); + var parent = this.parent; + var config = this.config; + + for ( var i=0, l=propArray.length; i < l; i++) { + var pi = propArray[i]; + root.setPos($P(0, 0), pi); + root.setData('span', Math.PI * 2, pi); + } + + root.angleSpan = { + begin : 0, + end : 2 * Math.PI + }; + + graph.eachBFS(this.root, function(elem) { + var angleSpan = elem.angleSpan.end - elem.angleSpan.begin; + var angleInit = elem.angleSpan.begin; + var len = getLength(elem); + //Calculate the sum of all angular widths + var totalAngularWidths = 0, subnodes = [], maxDim = {}; + elem.eachSubnode(function(sib) { + totalAngularWidths += sib._treeAngularWidth; + //get max dim + for ( var i=0, l=propArray.length; i < l; i++) { + var pi = propArray[i], dim = sib.getData('dim', pi); + maxDim[pi] = (pi in maxDim)? (dim > maxDim[pi]? dim : maxDim[pi]) : dim; + } + subnodes.push(sib); + }, "ignore"); + //Maintain children order + //Second constraint for + if (parent && parent.id == elem.id && subnodes.length > 0 + && subnodes[0].dist) { + subnodes.sort(function(a, b) { + return (a.dist >= b.dist) - (a.dist <= b.dist); + }); + } + //Calculate nodes positions. + for (var k = 0, ls=subnodes.length; k < ls; k++) { + var child = subnodes[k]; + if (!child._flag) { + var angleProportion = child._treeAngularWidth / totalAngularWidths * angleSpan; + var theta = angleInit + angleProportion / 2; + + for ( var i=0, l=propArray.length; i < l; i++) { + var pi = propArray[i]; + child.setPos($P(theta, len), pi); + child.setData('span', angleProportion, pi); + child.setData('dim-quotient', child.getData('dim', pi) / maxDim[pi], pi); + } + + child.angleSpan = { + begin : angleInit, + end : angleInit + angleProportion + }; + angleInit += angleProportion; + } + } + }, "ignore"); + }, + + /* + * Method: setAngularWidthForNodes + * + * Sets nodes angular widths. + */ + setAngularWidthForNodes : function(prop) { + this.graph.eachBFS(this.root, function(elem, i) { + var diamValue = elem.getData('angularWidth', prop[0]) || 5; + elem._angularWidth = diamValue / i; + }, "ignore"); + }, + + /* + * Method: setSubtreesAngularWidth + * + * Sets subtrees angular widths. + */ + setSubtreesAngularWidth : function() { + var that = this; + this.graph.eachNode(function(elem) { + that.setSubtreeAngularWidth(elem); + }, "ignore"); + }, + + /* + * Method: setSubtreeAngularWidth + * + * Sets the angular width for a subtree. + */ + setSubtreeAngularWidth : function(elem) { + var that = this, nodeAW = elem._angularWidth, sumAW = 0; + elem.eachSubnode(function(child) { + that.setSubtreeAngularWidth(child); + sumAW += child._treeAngularWidth; + }, "ignore"); + elem._treeAngularWidth = Math.max(nodeAW, sumAW); + }, + + /* + * Method: computeAngularWidths + * + * Computes nodes and subtrees angular widths. + */ + computeAngularWidths : function(prop) { + this.setAngularWidthForNodes(prop); + this.setSubtreesAngularWidth(); + } + +}); + + +/* + * File: Sunburst.js + */ + +/* + Class: Sunburst + + A radial space filling tree visualization. + + Inspired by: + + Sunburst . + + Note: + + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the visualization described in the paper. + + Implements: + + All methods + + Constructor Options: + + Inherits options from + + - + - + - + - + - + - + - + - + - + + Additionally, there are other parameters and some default values changed + + interpolation - (string) Default's *linear*. Describes the way nodes are interpolated. Possible values are 'linear' and 'polar'. + levelDistance - (number) Default's *100*. The distance between levels of the tree. + Node.type - Described in . Default's to *multipie*. + Node.height - Described in . Default's *0*. + Edge.type - Described in . Default's *none*. + Label.textAlign - Described in . Default's *start*. + Label.textBaseline - Described in . Default's *middle*. + + Instance Properties: + + canvas - Access a instance. + graph - Access a instance. + op - Access a instance. + fx - Access a instance. + labels - Access a interface implementation. + +*/ + +$jit.Sunburst = new Class({ + + Implements: [ Loader, Extras, Layouts.Radial ], + + initialize: function(controller) { + var $Sunburst = $jit.Sunburst; + + var config = { + interpolation: 'linear', + levelDistance: 100, + Node: { + 'type': 'multipie', + 'height':0 + }, + Edge: { + 'type': 'none' + }, + Label: { + textAlign: 'start', + textBaseline: 'middle' + } + }; + + this.controller = this.config = $.merge(Options("Canvas", "Node", "Edge", + "Fx", "Tips", "NodeStyles", "Events", "Navigation", "Controller", "Label"), config, controller); + + var canvasConfig = this.config; + if(canvasConfig.useCanvas) { + this.canvas = canvasConfig.useCanvas; + this.config.labelContainer = this.canvas.id + '-label'; + } else { + if(canvasConfig.background) { + canvasConfig.background = $.merge({ + type: 'Circles' + }, canvasConfig.background); + } + this.canvas = new Canvas(this, canvasConfig); + this.config.labelContainer = (typeof canvasConfig.injectInto == 'string'? canvasConfig.injectInto : canvasConfig.injectInto.id) + '-label'; + } + + this.graphOptions = { + 'klass': Polar, + 'Node': { + 'selected': false, + 'exist': true, + 'drawn': true + } + }; + this.graph = new Graph(this.graphOptions, this.config.Node, + this.config.Edge); + this.labels = new $Sunburst.Label[canvasConfig.Label.type](this); + this.fx = new $Sunburst.Plot(this, $Sunburst); + this.op = new $Sunburst.Op(this); + this.json = null; + this.root = null; + this.rotated = null; + this.busy = false; + // initialize extras + this.initializeExtras(); + }, + + /* + + createLevelDistanceFunc + + Returns the levelDistance function used for calculating a node distance + to its origin. This function returns a function that is computed + per level and not per node, such that all nodes with the same depth will have the + same distance to the origin. The resulting function gets the + parent node as parameter and returns a float. + + */ + createLevelDistanceFunc: function() { + var ld = this.config.levelDistance; + return function(elem) { + return (elem._depth + 1) * ld; + }; + }, + + /* + Method: refresh + + Computes positions and plots the tree. + + */ + refresh: function() { + this.compute(); + this.plot(); + }, + + /* + reposition + + An alias for computing new positions to _endPos_ + + See also: + + + + */ + reposition: function() { + this.compute('end'); + }, + + /* + Method: rotate + + Rotates the graph so that the selected node is horizontal on the right. + + Parameters: + + node - (object) A . + method - (string) Whether to perform an animation or just replot the graph. Possible values are "replot" or "animate". + opt - (object) Configuration options merged with this visualization configuration options. + + See also: + + + + */ + rotate: function(node, method, opt) { + var theta = node.getPos(opt.property || 'current').getp(true).theta; + this.rotated = node; + this.rotateAngle(-theta, method, opt); + }, + + /* + Method: rotateAngle + + Rotates the graph of an angle theta. + + Parameters: + + node - (object) A . + method - (string) Whether to perform an animation or just replot the graph. Possible values are "replot" or "animate". + opt - (object) Configuration options merged with this visualization configuration options. + + See also: + + + + */ + rotateAngle: function(theta, method, opt) { + var that = this; + var options = $.merge(this.config, opt || {}, { + modes: [ 'polar' ] + }); + var prop = opt.property || (method === "animate" ? 'end' : 'current'); + if(method === 'animate') { + this.fx.animation.pause(); + } + this.graph.eachNode(function(n) { + var p = n.getPos(prop); + p.theta += theta; + if (p.theta < 0) { + p.theta += Math.PI * 2; + } + }); + if (method == 'animate') { + this.fx.animate(options); + } else if (method == 'replot') { + this.fx.plot(); + this.busy = false; + } + }, + + /* + Method: plot + + Plots the Sunburst. This is a shortcut to *fx.plot*. + */ + plot: function() { + this.fx.plot(); + } +}); + +$jit.Sunburst.$extend = true; + +(function(Sunburst) { + + /* + Class: Sunburst.Op + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + Sunburst.Op = new Class( { + + Implements: Graph.Op + + }); + + /* + Class: Sunburst.Plot + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + Sunburst.Plot = new Class( { + + Implements: Graph.Plot + + }); + + /* + Class: Sunburst.Label + + Custom extension of . + Contains custom , and extensions. + + Extends: + + All methods and subclasses. + + See also: + + , , , . + + */ + Sunburst.Label = {}; + + /* + Sunburst.Label.Native + + Custom extension of . + + Extends: + + All methods + + See also: + + + */ + Sunburst.Label.Native = new Class( { + Implements: Graph.Label.Native, + + initialize: function(viz) { + this.viz = viz; + this.label = viz.config.Label; + this.config = viz.config; + }, + + renderLabel: function(canvas, node, controller) { + var span = node.getData('span'); + if(span < Math.PI /2 && Math.tan(span) * + this.config.levelDistance * node._depth < 10) { + return; + } + var ctx = canvas.getCtx(); + var measure = ctx.measureText(node.name); + if (node.id == this.viz.root) { + var x = -measure.width / 2, y = 0, thetap = 0; + var ld = 0; + } else { + var indent = 5; + var ld = controller.levelDistance - indent; + var clone = node.pos.clone(); + clone.rho += indent; + var p = clone.getp(true); + var ct = clone.getc(true); + var x = ct.x, y = ct.y; + // get angle in degrees + var pi = Math.PI; + var cond = (p.theta > pi / 2 && p.theta < 3 * pi / 2); + var thetap = cond ? p.theta + pi : p.theta; + if (cond) { + x -= Math.abs(Math.cos(p.theta) * measure.width); + y += Math.sin(p.theta) * measure.width; + } else if (node.id == this.viz.root) { + x -= measure.width / 2; + } + } + ctx.save(); + ctx.translate(x, y); + ctx.rotate(thetap); + ctx.fillText(node.name, 0, 0); + ctx.restore(); + } + }); + + /* + Sunburst.Label.SVG + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + Sunburst.Label.SVG = new Class( { + Implements: Graph.Label.SVG, + + initialize: function(viz) { + this.viz = viz; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller) { + var pos = node.pos.getc(true), viz = this.viz, canvas = this.viz.canvas; + var radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x + radius.width / 2), + y: Math.round(pos.y + radius.height / 2) + }; + tag.setAttribute('x', labelPos.x); + tag.setAttribute('y', labelPos.y); + + var bb = tag.getBBox(); + if (bb) { + // center the label + var x = tag.getAttribute('x'); + var y = tag.getAttribute('y'); + // get polar coordinates + var p = node.pos.getp(true); + // get angle in degrees + var pi = Math.PI; + var cond = (p.theta > pi / 2 && p.theta < 3 * pi / 2); + if (cond) { + tag.setAttribute('x', x - bb.width); + tag.setAttribute('y', y - bb.height); + } else if (node.id == viz.root) { + tag.setAttribute('x', x - bb.width / 2); + } + + var thetap = cond ? p.theta + pi : p.theta; + if(node._depth) + tag.setAttribute('transform', 'rotate(' + thetap * 360 / (2 * pi) + ' ' + x + + ' ' + y + ')'); + } + + controller.onPlaceLabel(tag, node); +} + }); + + /* + Sunburst.Label.HTML + + Custom extension of . + + Extends: + + All methods. + + See also: + + + + */ + Sunburst.Label.HTML = new Class( { + Implements: Graph.Label.HTML, + + initialize: function(viz) { + this.viz = viz; + }, + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller) { + var pos = node.pos.clone(), + canvas = this.viz.canvas, + height = node.getData('height'), + ldist = ((height || node._depth == 0)? height : this.viz.config.levelDistance) /2, + radius = canvas.getSize(); + pos.rho += ldist; + pos = pos.getc(true); + + var labelPos = { + x: Math.round(pos.x + radius.width / 2), + y: Math.round(pos.y + radius.height / 2) + }; + + var style = tag.style; + style.left = labelPos.x + 'px'; + style.top = labelPos.y + 'px'; + style.display = this.fitsInCanvas(labelPos, canvas) ? '' : 'none'; + + controller.onPlaceLabel(tag, node); + } + }); + + /* + Class: Sunburst.Plot.NodeTypes + + This class contains a list of built-in types. + Node types implemented are 'none', 'pie', 'multipie', 'gradient-pie' and 'gradient-multipie'. + + You can add your custom node types, customizing your visualization to the extreme. + + Example: + + (start code js) + Sunburst.Plot.NodeTypes.implement({ + 'mySpecialType': { + 'render': function(node, canvas) { + //print your custom node to canvas + }, + //optional + 'contains': function(node, pos) { + //return true if pos is inside the node or false otherwise + } + } + }); + (end code) + + */ + Sunburst.Plot.NodeTypes = new Class( { + 'none': { + 'render': $.empty, + 'contains': $.lambda(false), + 'anglecontains': function(node, pos) { + var span = node.getData('span') / 2, theta = node.pos.theta; + var begin = theta - span, end = theta + span; + if (begin < 0) + begin += Math.PI * 2; + var atan = Math.atan2(pos.y, pos.x); + if (atan < 0) + atan += Math.PI * 2; + if (begin > end) { + return (atan > begin && atan <= Math.PI * 2) || atan < end; + } else { + return atan > begin && atan < end; + } + } + }, + + 'pie': { + 'render': function(node, canvas) { + var span = node.getData('span') / 2, theta = node.pos.theta; + var begin = theta - span, end = theta + span; + var polarNode = node.pos.getp(true); + var polar = new Polar(polarNode.rho, begin); + var p1coord = polar.getc(true); + polar.theta = end; + var p2coord = polar.getc(true); + + var ctx = canvas.getCtx(); + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(p1coord.x, p1coord.y); + ctx.moveTo(0, 0); + ctx.lineTo(p2coord.x, p2coord.y); + ctx.moveTo(0, 0); + ctx.arc(0, 0, polarNode.rho * node.getData('dim-quotient'), begin, end, + false); + ctx.fill(); + }, + 'contains': function(node, pos) { + if (this.nodeTypes['none'].anglecontains.call(this, node, pos)) { + var rho = Math.sqrt(pos.x * pos.x + pos.y * pos.y); + var ld = this.config.levelDistance, d = node._depth; + return (rho <= ld * d); + } + return false; + } + }, + 'multipie': { + 'render': function(node, canvas) { + var height = node.getData('height'); + var ldist = height? height : this.config.levelDistance; + var span = node.getData('span') / 2, theta = node.pos.theta; + var begin = theta - span, end = theta + span; + var polarNode = node.pos.getp(true); + + var polar = new Polar(polarNode.rho, begin); + var p1coord = polar.getc(true); + + polar.theta = end; + var p2coord = polar.getc(true); + + polar.rho += ldist; + var p3coord = polar.getc(true); + + polar.theta = begin; + var p4coord = polar.getc(true); + + var ctx = canvas.getCtx(); + ctx.moveTo(0, 0); + ctx.beginPath(); + ctx.arc(0, 0, polarNode.rho, begin, end, false); + ctx.arc(0, 0, polarNode.rho + ldist, end, begin, true); + ctx.moveTo(p1coord.x, p1coord.y); + ctx.lineTo(p4coord.x, p4coord.y); + ctx.moveTo(p2coord.x, p2coord.y); + ctx.lineTo(p3coord.x, p3coord.y); + ctx.fill(); + + if (node.collapsed) { + ctx.save(); + ctx.lineWidth = 2; + ctx.moveTo(0, 0); + ctx.beginPath(); + ctx.arc(0, 0, polarNode.rho + ldist + 5, end - 0.01, begin + 0.01, + true); + ctx.stroke(); + ctx.restore(); + } + }, + 'contains': function(node, pos) { + if (this.nodeTypes['none'].anglecontains.call(this, node, pos)) { + var rho = Math.sqrt(pos.x * pos.x + pos.y * pos.y); + var height = node.getData('height'); + var ldist = height? height : this.config.levelDistance; + var ld = this.config.levelDistance, d = node._depth; + return (rho >= ld * d) && (rho <= (ld * d + ldist)); + } + return false; + } + }, + + 'gradient-multipie': { + 'render': function(node, canvas) { + var ctx = canvas.getCtx(); + var height = node.getData('height'); + var ldist = height? height : this.config.levelDistance; + var radialGradient = ctx.createRadialGradient(0, 0, node.getPos().rho, + 0, 0, node.getPos().rho + ldist); + + var colorArray = $.hexToRgb(node.getData('color')), ans = []; + $.each(colorArray, function(i) { + ans.push(parseInt(i * 0.5, 10)); + }); + var endColor = $.rgbToHex(ans); + radialGradient.addColorStop(0, endColor); + radialGradient.addColorStop(1, node.getData('color')); + ctx.fillStyle = radialGradient; + this.nodeTypes['multipie'].render.call(this, node, canvas); + }, + 'contains': function(node, pos) { + return this.nodeTypes['multipie'].contains.call(this, node, pos); + } + }, + + 'gradient-pie': { + 'render': function(node, canvas) { + var ctx = canvas.getCtx(); + var radialGradient = ctx.createRadialGradient(0, 0, 0, 0, 0, node + .getPos().rho); + + var colorArray = $.hexToRgb(node.getData('color')), ans = []; + $.each(colorArray, function(i) { + ans.push(parseInt(i * 0.5, 10)); + }); + var endColor = $.rgbToHex(ans); + radialGradient.addColorStop(1, endColor); + radialGradient.addColorStop(0, node.getData('color')); + ctx.fillStyle = radialGradient; + this.nodeTypes['pie'].render.call(this, node, canvas); + }, + 'contains': function(node, pos) { + return this.nodeTypes['pie'].contains.call(this, node, pos); + } + } + }); + + /* + Class: Sunburst.Plot.EdgeTypes + + This class contains a list of built-in types. + Edge types implemented are 'none', 'line' and 'arrow'. + + You can add your custom edge types, customizing your visualization to the extreme. + + Example: + + (start code js) + Sunburst.Plot.EdgeTypes.implement({ + 'mySpecialType': { + 'render': function(adj, canvas) { + //print your custom edge to canvas + }, + //optional + 'contains': function(adj, pos) { + //return true if pos is inside the arc or false otherwise + } + } + }); + (end code) + + */ + Sunburst.Plot.EdgeTypes = new Class({ + 'none': $.empty, + 'line': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + this.edgeHelper.line.render(from, to, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + return this.edgeHelper.line.contains(from, to, pos, this.edge.epsilon); + } + }, + 'arrow': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true), + dim = adj.getData('dim'), + direction = adj.data.$direction, + inv = (direction && direction.length>1 && direction[0] != adj.nodeFrom.id); + this.edgeHelper.arrow.render(from, to, dim, inv, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + return this.edgeHelper.arrow.contains(from, to, pos, this.edge.epsilon); + } + }, + 'hyperline': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(), + to = adj.nodeTo.pos.getc(), + dim = Math.max(from.norm(), to.norm()); + this.edgeHelper.hyperline.render(from.$scale(1/dim), to.$scale(1/dim), dim, canvas); + }, + 'contains': $.lambda(false) //TODO(nico): Implement this! + } + }); + +})($jit.Sunburst); + + +/* + * File: PieChart.js + * +*/ + +$jit.Sunburst.Plot.NodeTypes.implement({ + 'piechart-stacked' : { + 'render' : function(node, canvas) { + var pos = node.pos.getp(true), + dimArray = node.getData('dimArray'), + valueArray = node.getData('valueArray'), + colorArray = node.getData('colorArray'), + colorLength = colorArray.length, + stringArray = node.getData('stringArray'), + span = node.getData('span') / 2, + theta = node.pos.theta, + begin = theta - span, + end = theta + span, + polar = new Polar; + + var ctx = canvas.getCtx(), + opt = {}, + gradient = node.getData('gradient'), + border = node.getData('border'), + config = node.getData('config'), + showLabels = config.showLabels, + resizeLabels = config.resizeLabels, + label = config.Label; + + var xpos = config.sliceOffset * Math.cos((begin + end) /2); + var ypos = config.sliceOffset * Math.sin((begin + end) /2); + + if (colorArray && dimArray && stringArray) { + for (var i=0, l=dimArray.length, acum=0, valAcum=0; i> 0; }), + endColor = $.rgbToHex(ans); + + radialGradient.addColorStop(0, colori); + radialGradient.addColorStop(0.5, colori); + radialGradient.addColorStop(1, endColor); + ctx.fillStyle = radialGradient; + } + + polar.rho = acum + config.sliceOffset; + polar.theta = begin; + var p1coord = polar.getc(true); + polar.theta = end; + var p2coord = polar.getc(true); + polar.rho += dimi; + var p3coord = polar.getc(true); + polar.theta = begin; + var p4coord = polar.getc(true); + + ctx.beginPath(); + //fixing FF arc method + fill + ctx.arc(xpos, ypos, acum + .01, begin, end, false); + ctx.arc(xpos, ypos, acum + dimi + .01, end, begin, true); + ctx.fill(); + if(border && border.name == stringArray[i]) { + opt.acum = acum; + opt.dimValue = dimArray[i]; + opt.begin = begin; + opt.end = end; + } + acum += (dimi || 0); + valAcum += (valueArray[i] || 0); + } + if(border) { + ctx.save(); + ctx.globalCompositeOperation = "source-over"; + ctx.lineWidth = 2; + ctx.strokeStyle = border.color; + var s = begin < end? 1 : -1; + ctx.beginPath(); + //fixing FF arc method + fill + ctx.arc(xpos, ypos, opt.acum + .01 + 1, opt.begin, opt.end, false); + ctx.arc(xpos, ypos, opt.acum + opt.dimValue + .01 - 1, opt.end, opt.begin, true); + ctx.closePath(); + ctx.stroke(); + ctx.restore(); + } + if(showLabels && label.type == 'Native') { + ctx.save(); + ctx.fillStyle = ctx.strokeStyle = label.color; + var scale = resizeLabels? node.getData('normalizedDim') : 1, + fontSize = (label.size * scale) >> 0; + fontSize = fontSize < +resizeLabels? +resizeLabels : fontSize; + + ctx.font = label.style + ' ' + fontSize + 'px ' + label.family; + ctx.textBaseline = 'middle'; + ctx.textAlign = 'center'; + + polar.rho = acum + config.labelOffset + config.sliceOffset; + polar.theta = node.pos.theta; + var cart = polar.getc(true); + + ctx.fillText(node.name, cart.x, cart.y); + ctx.restore(); + } + } + }, + 'contains': function(node, pos) { + if (this.nodeTypes['none'].anglecontains.call(this, node, pos)) { + var rho = Math.sqrt(pos.x * pos.x + pos.y * pos.y); + var ld = this.config.levelDistance, d = node._depth; + var config = node.getData('config'); + if(rho <=ld * d + config.sliceOffset) { + var dimArray = node.getData('dimArray'); + for(var i=0,l=dimArray.length,acum=config.sliceOffset; i= acum && rho <= acum + dimi) { + return { + name: node.getData('stringArray')[i], + color: node.getData('colorArray')[i], + value: node.getData('valueArray')[i], + label: node.name + }; + } + acum += dimi; + } + } + return false; + + } + return false; + } + } +}); + +/* + Class: PieChart + + A visualization that displays stacked bar charts. + + Constructor Options: + + See . + +*/ +$jit.PieChart = new Class({ + sb: null, + colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"], + selected: {}, + busy: false, + + initialize: function(opt) { + this.controller = this.config = + $.merge(Options("Canvas", "PieChart", "Label"), { + Label: { type: 'Native' } + }, opt); + this.initializeViz(); + }, + + initializeViz: function() { + var config = this.config, that = this; + var nodeType = config.type.split(":")[0]; + var delegate = new $jit.Sunburst({ + injectInto: config.injectInto, + width: config.width, + height: config.height, + useCanvas: config.useCanvas, + withLabels: config.Label.type != 'Native', + Label: { + type: config.Label.type + }, + Node: { + overridable: true, + type: 'piechart-' + nodeType, + width: 1, + height: 1 + }, + Edge: { + type: 'none' + }, + Tips: { + enable: config.Tips.enable, + type: 'Native', + force: true, + onShow: function(tip, node, contains) { + var elem = contains; + config.Tips.onShow(tip, elem, node); + } + }, + Events: { + enable: true, + type: 'Native', + onClick: function(node, eventInfo, evt) { + if(!config.Events.enable) return; + var elem = eventInfo.getContains(); + config.Events.onClick(elem, eventInfo, evt); + }, + onMouseMove: function(node, eventInfo, evt) { + if(!config.hoveredColor) return; + if(node) { + var elem = eventInfo.getContains(); + that.select(node.id, elem.name, elem.index); + } else { + that.select(false, false, false); + } + } + }, + onCreateLabel: function(domElement, node) { + var labelConf = config.Label; + if(config.showLabels) { + var style = domElement.style; + style.fontSize = labelConf.size + 'px'; + style.fontFamily = labelConf.family; + style.color = labelConf.color; + style.textAlign = 'center'; + domElement.innerHTML = node.name; + } + }, + onPlaceLabel: function(domElement, node) { + if(!config.showLabels) return; + var pos = node.pos.getp(true), + dimArray = node.getData('dimArray'), + span = node.getData('span') / 2, + theta = node.pos.theta, + begin = theta - span, + end = theta + span, + polar = new Polar; + + var showLabels = config.showLabels, + resizeLabels = config.resizeLabels, + label = config.Label; + + if (dimArray) { + for (var i=0, l=dimArray.length, acum=0; i> 0; + fontSize = fontSize < +resizeLabels? +resizeLabels : fontSize; + domElement.style.fontSize = fontSize + 'px'; + polar.rho = acum + config.labelOffset + config.sliceOffset; + polar.theta = (begin + end) / 2; + var pos = polar.getc(true); + var radius = that.canvas.getSize(); + var labelPos = { + x: Math.round(pos.x + radius.width / 2), + y: Math.round(pos.y + radius.height / 2) + }; + domElement.style.left = labelPos.x + 'px'; + domElement.style.top = labelPos.y + 'px'; + } + } + }); + + var size = delegate.canvas.getSize(), + min = Math.min; + delegate.config.levelDistance = min(size.width, size.height)/2 + - config.offset - config.sliceOffset; + this.delegate = delegate; + this.canvas = this.delegate.canvas; + this.canvas.getCtx().globalCompositeOperation = 'lighter'; + }, + + /* + Method: loadJSON + + Loads JSON data into the visualization. + + Parameters: + + json - The JSON data format. This format is described in . + + Example: + (start code js) + var pieChart = new $jit.PieChart(options); + pieChart.loadJSON(json); + (end code) + */ + loadJSON: function(json) { + var prefix = $.time(), + ch = [], + delegate = this.delegate, + name = $.splat(json.label), + nameLength = name.length, + color = $.splat(json.color || this.colors), + colorLength = color.length, + config = this.config, + gradient = !!config.type.split(":")[1], + animate = config.animate, + mono = nameLength == 1; + + for(var i=0, values=json.values, l=values.length; i. + onComplete - (object) A callback object to be called when the animation transition when updating the data end. + + Example: + + (start code js) + pieChart.updateJSON(json, { + onComplete: function() { + alert('update complete!'); + } + }); + (end code) + */ + updateJSON: function(json, onComplete) { + if(this.busy) return; + this.busy = true; + + var delegate = this.delegate; + var graph = delegate.graph; + var values = json.values; + var animate = this.config.animate; + var that = this; + $.each(values, function(v) { + var n = graph.getByName(v.label), + vals = $.splat(v.values); + if(n) { + n.setData('valueArray', vals); + n.setData('angularWidth', $.reduce(vals, function(x,y){return x+y;})); + if(json.label) { + n.setData('stringArray', $.splat(json.label)); + } + } + }); + this.normalizeDims(); + if(animate) { + delegate.compute('end'); + delegate.fx.animate({ + modes: ['node-property:dimArray:span', 'linear'], + duration:1500, + onComplete: function() { + that.busy = false; + onComplete && onComplete.onComplete(); + } + }); + } else { + delegate.refresh(); + } + }, + + //adds the little brown bar when hovering the node + select: function(id, name) { + if(!this.config.hoveredColor) return; + var s = this.selected; + if(s.id != id || s.name != name) { + s.id = id; + s.name = name; + s.color = this.config.hoveredColor; + this.delegate.graph.eachNode(function(n) { + if(id == n.id) { + n.setData('border', s); + } else { + n.setData('border', false); + } + }); + this.delegate.plot(); + } + }, + + /* + Method: getLegend + + Returns an object containing as keys the legend names and as values hex strings with color values. + + Example: + + (start code js) + var legend = pieChart.getLegend(); + (end code) + */ + getLegend: function() { + var legend = {}; + var n; + this.delegate.graph.getNode(this.delegate.root).eachAdjacency(function(adj) { + n = adj.nodeTo; + }); + var colors = n.getData('colorArray'), + len = colors.length; + $.each(n.getData('stringArray'), function(s, i) { + legend[s] = colors[i % len]; + }); + return legend; + }, + + /* + Method: getMaxValue + + Returns the maximum accumulated value for the stacks. This method is used for normalizing the graph heights according to the canvas height. + + Example: + + (start code js) + var ans = pieChart.getMaxValue(); + (end code) + + In some cases it could be useful to override this method to normalize heights for a group of PieCharts, like when doing small multiples. + + Example: + + (start code js) + //will return 100 for all PieChart instances, + //displaying all of them with the same scale + $jit.PieChart.implement({ + 'getMaxValue': function() { + return 100; + } + }); + (end code) + + */ + getMaxValue: function() { + var maxValue = 0; + this.delegate.graph.eachNode(function(n) { + var valArray = n.getData('valueArray'), + acum = 0; + $.each(valArray, function(v) { + acum += +v; + }); + maxValue = maxValue>acum? maxValue:acum; + }); + return maxValue; + }, + + normalizeDims: function() { + //number of elements + var root = this.delegate.graph.getNode(this.delegate.root), l=0; + root.eachAdjacency(function() { + l++; + }); + var maxValue = this.getMaxValue() || 1, + config = this.config, + animate = config.animate, + rho = this.delegate.config.levelDistance; + this.delegate.graph.eachNode(function(n) { + var acum = 0, animateValue = []; + $.each(n.getData('valueArray'), function(v) { + acum += +v; + animateValue.push(1); + }); + var stat = (animateValue.length == 1) && !config.updateHeights; + if(animate) { + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return stat? rho: (n * rho / maxValue); + }), 'end'); + var dimArray = n.getData('dimArray'); + if(!dimArray) { + n.setData('dimArray', animateValue); + } + } else { + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return stat? rho : (n * rho / maxValue); + })); + } + n.setData('normalizedDim', acum / maxValue); + }); + } +}); + + +/* + * Class: Layouts.TM + * + * Implements TreeMaps layouts (SliceAndDice, Squarified, Strip). + * + * Implemented By: + * + * + * + */ +Layouts.TM = {}; + +Layouts.TM.SliceAndDice = new Class({ + compute: function(prop) { + var root = this.graph.getNode(this.clickedNode && this.clickedNode.id || this.root); + this.controller.onBeforeCompute(root); + var size = this.canvas.getSize(), + config = this.config, + width = size.width, + height = size.height; + this.graph.computeLevels(this.root, 0, "ignore"); + //set root position and dimensions + root.getPos(prop).setc(-width/2, -height/2); + root.setData('width', width, prop); + root.setData('height', height + config.titleHeight, prop); + this.computePositions(root, root, this.layout.orientation, prop); + this.controller.onAfterCompute(root); + }, + + computePositions: function(par, ch, orn, prop) { + //compute children areas + var totalArea = 0; + par.eachSubnode(function(n) { + totalArea += n.getData('area', prop); + }); + + var config = this.config, + offst = config.offset, + width = par.getData('width', prop), + height = Math.max(par.getData('height', prop) - config.titleHeight, 0), + fact = par == ch? 1 : (ch.getData('area', prop) / totalArea); + + var otherSize, size, dim, pos, pos2, posth, pos2th; + var horizontal = (orn == "h"); + if(horizontal) { + orn = 'v'; + otherSize = height; + size = width * fact; + dim = 'height'; + pos = 'y'; + pos2 = 'x'; + posth = config.titleHeight; + pos2th = 0; + } else { + orn = 'h'; + otherSize = height * fact; + size = width; + dim = 'width'; + pos = 'x'; + pos2 = 'y'; + posth = 0; + pos2th = config.titleHeight; + } + var cpos = ch.getPos(prop); + ch.setData('width', size, prop); + ch.setData('height', otherSize, prop); + var offsetSize = 0, tm = this; + ch.eachSubnode(function(n) { + var p = n.getPos(prop); + p[pos] = offsetSize + cpos[pos] + posth; + p[pos2] = cpos[pos2] + pos2th; + tm.computePositions(ch, n, orn, prop); + offsetSize += n.getData(dim, prop); + }); + } + +}); + +Layouts.TM.Area = { + /* + Method: compute + + Called by loadJSON to calculate recursively all node positions and lay out the tree. + + Parameters: + + json - A JSON tree. See also . + coord - A coordinates object specifying width, height, left and top style properties. + */ + compute: function(prop) { + prop = prop || "current"; + var root = this.graph.getNode(this.clickedNode && this.clickedNode.id || this.root); + this.controller.onBeforeCompute(root); + var config = this.config, + size = this.canvas.getSize(), + width = size.width, + height = size.height, + offst = config.offset, + offwdth = width - offst, + offhght = height - offst; + this.graph.computeLevels(this.root, 0, "ignore"); + //set root position and dimensions + root.getPos(prop).setc(-width/2, -height/2); + root.setData('width', width, prop); + root.setData('height', height, prop); + //create a coordinates object + var coord = { + 'top': -height/2 + config.titleHeight, + 'left': -width/2, + 'width': offwdth, + 'height': offhght - config.titleHeight + }; + this.computePositions(root, coord, prop); + this.controller.onAfterCompute(root); + }, + + /* + Method: computeDim + + Computes dimensions and positions of a group of nodes + according to a custom layout row condition. + + Parameters: + + tail - An array of nodes. + initElem - An array of nodes (containing the initial node to be laid). + w - A fixed dimension where nodes will be layed out. + coord - A coordinates object specifying width, height, left and top style properties. + comp - A custom comparison function + */ + computeDim: function(tail, initElem, w, coord, comp, prop) { + if(tail.length + initElem.length == 1) { + var l = (tail.length == 1)? tail : initElem; + this.layoutLast(l, w, coord, prop); + return; + } + if(tail.length >= 2 && initElem.length == 0) { + initElem = [tail.shift()]; + } + if(tail.length == 0) { + if(initElem.length > 0) this.layoutRow(initElem, w, coord, prop); + return; + } + var c = tail[0]; + if(comp(initElem, w) >= comp([c].concat(initElem), w)) { + this.computeDim(tail.slice(1), initElem.concat([c]), w, coord, comp, prop); + } else { + var newCoords = this.layoutRow(initElem, w, coord, prop); + this.computeDim(tail, [], newCoords.dim, newCoords, comp, prop); + } + }, + + + /* + Method: worstAspectRatio + + Calculates the worst aspect ratio of a group of rectangles. + + See also: + + + + Parameters: + + ch - An array of nodes. + w - The fixed dimension where rectangles are being laid out. + + Returns: + + The worst aspect ratio. + + + */ + worstAspectRatio: function(ch, w) { + if(!ch || ch.length == 0) return Number.MAX_VALUE; + var areaSum = 0, maxArea = 0, minArea = Number.MAX_VALUE; + for(var i=0, l=ch.length; i area? maxArea : area; + } + var sqw = w * w, sqAreaSum = areaSum * areaSum; + return Math.max(sqw * maxArea / sqAreaSum, + sqAreaSum / (sqw * minArea)); + }, + + /* + Method: avgAspectRatio + + Calculates the average aspect ratio of a group of rectangles. + + See also: + + + + Parameters: + + ch - An array of nodes. + w - The fixed dimension where rectangles are being laid out. + + Returns: + + The average aspect ratio. + + + */ + avgAspectRatio: function(ch, w) { + if(!ch || ch.length == 0) return Number.MAX_VALUE; + var arSum = 0; + for(var i=0, l=ch.length; i h? w / h : h / w; + } + return arSum / l; + }, + + /* + layoutLast + + Performs the layout of the last computed sibling. + + Parameters: + + ch - An array of nodes. + w - A fixed dimension where nodes will be layed out. + coord - A coordinates object specifying width, height, left and top style properties. + */ + layoutLast: function(ch, w, coord, prop) { + var child = ch[0]; + child.getPos(prop).setc(coord.left, coord.top); + child.setData('width', coord.width, prop); + child.setData('height', coord.height, prop); + } +}; + + +Layouts.TM.Squarified = new Class({ + Implements: Layouts.TM.Area, + + computePositions: function(node, coord, prop) { + var config = this.config, + max = Math.max; + + if (coord.width >= coord.height) + this.layout.orientation = 'h'; + else + this.layout.orientation = 'v'; + + var ch = node.getSubnodes([1, 1], "ignore"); + if(ch.length > 0) { + this.processChildrenLayout(node, ch, coord, prop); + for(var i=0, l=ch.length; i. + coord - A coordinates object specifying width, height, left and top style properties. + */ + computePositions: function(node, coord, prop) { + var ch = node.getSubnodes([1, 1], "ignore"), + config = this.config, + max = Math.max; + if(ch.length > 0) { + this.processChildrenLayout(node, ch, coord, prop); + for(var i=0, l=ch.length; i + * + */ + +Layouts.Icicle = new Class({ + /* + * Method: compute + * + * Called by loadJSON to calculate all node positions. + * + * Parameters: + * + * posType - The nodes' position to compute. Either "start", "end" or + * "current". Defaults to "current". + */ + compute: function(posType) { + posType = posType || "current"; + + var root = this.graph.getNode(this.root), + config = this.config, + size = this.canvas.getSize(), + width = size.width, + height = size.height, + offset = config.offset, + levelsToShow = config.constrained ? config.levelsToShow : Number.MAX_VALUE; + + this.controller.onBeforeCompute(root); + + Graph.Util.computeLevels(this.graph, root.id, 0, "ignore"); + + var treeDepth = 0; + + Graph.Util.eachLevel(root, 0, false, function (n, d) { if(d > treeDepth) treeDepth = d; }); + + var startNode = this.graph.getNode(this.clickedNode && this.clickedNode.id || root.id); + var maxDepth = Math.min(treeDepth, levelsToShow-1); + var initialDepth = startNode._depth; + if(this.layout.horizontal()) { + this.computeSubtree(startNode, -width/2, -height/2, width/(maxDepth+1), height, initialDepth, maxDepth, posType); + } else { + this.computeSubtree(startNode, -width/2, -height/2, width, height/(maxDepth+1), initialDepth, maxDepth, posType); + } + }, + + computeSubtree: function (root, x, y, width, height, initialDepth, maxDepth, posType) { + root.getPos(posType).setc(x, y); + root.setData('width', width, posType); + root.setData('height', height, posType); + + var nodeLength, prevNodeLength = 0, totalDim = 0; + var children = Graph.Util.getSubnodes(root, [1, 1], 'ignore'); // next level from this node + + if(!children.length) + return; + + $.each(children, function(e) { totalDim += e.getData('dim'); }); + + for(var i=0, l=children.length; i < l; i++) { + if(this.layout.horizontal()) { + nodeLength = height * children[i].getData('dim') / totalDim; + this.computeSubtree(children[i], x+width, y, width, nodeLength, initialDepth, maxDepth, posType); + y += nodeLength; + } else { + nodeLength = width * children[i].getData('dim') / totalDim; + this.computeSubtree(children[i], x, y+height, nodeLength, height, initialDepth, maxDepth, posType); + x += nodeLength; + } + } + } +}); + + + +/* + * File: Icicle.js + * +*/ + +/* + Class: Icicle + + Icicle space filling visualization. + + Implements: + + All methods + + Constructor Options: + + Inherits options from + + - + - + - + - + - + - + - + - + - + + Additionally, there are other parameters and some default values changed + + orientation - (string) Default's *h*. Whether to set horizontal or vertical layouts. Possible values are 'h' and 'v'. + offset - (number) Default's *2*. Boxes offset. + constrained - (boolean) Default's *false*. Whether to show the entire tree when loaded or just the number of levels specified by _levelsToShow_. + levelsToShow - (number) Default's *3*. The number of levels to show for a subtree. This number is relative to the selected node. + animate - (boolean) Default's *false*. Whether to animate transitions. + Node.type - Described in . Default's *rectangle*. + Label.type - Described in . Default's *Native*. + duration - Described in . Default's *700*. + fps - Described in . Default's *45*. + + Instance Properties: + + canvas - Access a instance. + graph - Access a instance. + op - Access a instance. + fx - Access a instance. + labels - Access a interface implementation. + +*/ + +$jit.Icicle = new Class({ + Implements: [ Loader, Extras, Layouts.Icicle ], + + layout: { + orientation: "h", + vertical: function(){ + return this.orientation == "v"; + }, + horizontal: function(){ + return this.orientation == "h"; + }, + change: function(){ + this.orientation = this.vertical()? "h" : "v"; + } + }, + + initialize: function(controller) { + var config = { + animate: false, + orientation: "h", + offset: 2, + levelsToShow: Number.MAX_VALUE, + constrained: false, + Node: { + type: 'rectangle', + overridable: true + }, + Edge: { + type: 'none' + }, + Label: { + type: 'Native' + }, + duration: 700, + fps: 45 + }; + + var opts = Options("Canvas", "Node", "Edge", "Fx", "Tips", "NodeStyles", + "Events", "Navigation", "Controller", "Label"); + this.controller = this.config = $.merge(opts, config, controller); + this.layout.orientation = this.config.orientation; + + var canvasConfig = this.config; + if (canvasConfig.useCanvas) { + this.canvas = canvasConfig.useCanvas; + this.config.labelContainer = this.canvas.id + '-label'; + } else { + this.canvas = new Canvas(this, canvasConfig); + this.config.labelContainer = (typeof canvasConfig.injectInto == 'string'? canvasConfig.injectInto : canvasConfig.injectInto.id) + '-label'; + } + + this.graphOptions = { + 'klass': Complex, + 'Node': { + 'selected': false, + 'exist': true, + 'drawn': true + } + }; + + this.graph = new Graph( + this.graphOptions, this.config.Node, this.config.Edge, this.config.Label); + + this.labels = new $jit.Icicle.Label[this.config.Label.type](this); + this.fx = new $jit.Icicle.Plot(this, $jit.Icicle); + this.op = new $jit.Icicle.Op(this); + this.group = new $jit.Icicle.Group(this); + this.clickedNode = null; + + this.initializeExtras(); + }, + + /* + Method: refresh + + Computes positions and plots the tree. + */ + refresh: function(){ + var labelType = this.config.Label.type; + if(labelType != 'Native') { + var that = this; + this.graph.eachNode(function(n) { that.labels.hideLabel(n, false); }); + } + this.compute(); + this.plot(); + }, + + /* + Method: plot + + Plots the Icicle visualization. This is a shortcut to *fx.plot*. + + */ + plot: function(){ + this.fx.plot(this.config); + }, + + /* + Method: enter + + Sets the node as root. + + Parameters: + + node - (object) A . + + */ + enter: function (node) { + if (this.busy) + return; + this.busy = true; + + var that = this, + config = this.config; + + var callback = { + onComplete: function() { + //compute positions of newly inserted nodes + if(config.request) + that.compute(); + + if(config.animate) { + that.graph.nodeList.setDataset(['current', 'end'], { + 'alpha': [1, 0] //fade nodes + }); + + Graph.Util.eachSubgraph(node, function(n) { + n.setData('alpha', 1, 'end'); + }, "ignore"); + + that.fx.animate({ + duration: 500, + modes:['node-property:alpha'], + onComplete: function() { + that.clickedNode = node; + that.compute('end'); + + that.fx.animate({ + modes:['linear', 'node-property:width:height'], + duration: 1000, + onComplete: function() { + that.busy = false; + that.clickedNode = node; + } + }); + } + }); + } else { + that.clickedNode = node; + that.busy = false; + that.refresh(); + } + } + }; + + if(config.request) { + this.requestNodes(clickedNode, callback); + } else { + callback.onComplete(); + } + }, + + /* + Method: out + + Sets the parent node of the current selected node as root. + + */ + out: function(){ + if(this.busy) + return; + + var that = this, + GUtil = Graph.Util, + config = this.config, + graph = this.graph, + parents = GUtil.getParents(graph.getNode(this.clickedNode && this.clickedNode.id || this.root)), + parent = parents[0], + clickedNode = parent, + previousClickedNode = this.clickedNode; + + this.busy = true; + this.events.hoveredNode = false; + + if(!parent) { + this.busy = false; + return; + } + + //final plot callback + callback = { + onComplete: function() { + that.clickedNode = parent; + if(config.request) { + that.requestNodes(parent, { + onComplete: function() { + that.compute(); + that.plot(); + that.busy = false; + } + }); + } else { + that.compute(); + that.plot(); + that.busy = false; + } + } + }; + + //animate node positions + if(config.animate) { + this.clickedNode = clickedNode; + this.compute('end'); + //animate the visible subtree only + this.clickedNode = previousClickedNode; + this.fx.animate({ + modes:['linear', 'node-property:width:height'], + duration: 1000, + onComplete: function() { + //animate the parent subtree + that.clickedNode = clickedNode; + //change nodes alpha + graph.nodeList.setDataset(['current', 'end'], { + 'alpha': [0, 1] + }); + GUtil.eachSubgraph(previousClickedNode, function(node) { + node.setData('alpha', 1); + }, "ignore"); + that.fx.animate({ + duration: 500, + modes:['node-property:alpha'], + onComplete: function() { + callback.onComplete(); + } + }); + } + }); + } else { + callback.onComplete(); + } + }, + requestNodes: function(node, onComplete){ + var handler = $.merge(this.controller, onComplete), + levelsToShow = this.config.constrained ? this.config.levelsToShow : Number.MAX_VALUE; + + if (handler.request) { + var leaves = [], d = node._depth; + Graph.Util.eachLevel(node, 0, levelsToShow, function(n){ + if (n.drawn && !Graph.Util.anySubnode(n)) { + leaves.push(n); + n._level = n._depth - d; + if (this.config.constrained) + n._level = levelsToShow - n._level; + + } + }); + this.group.requestNodes(leaves, handler); + } else { + handler.onComplete(); + } + } +}); + +/* + Class: Icicle.Op + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ +$jit.Icicle.Op = new Class({ + + Implements: Graph.Op + +}); + +/* + * Performs operations on group of nodes. + */ +$jit.Icicle.Group = new Class({ + + initialize: function(viz){ + this.viz = viz; + this.canvas = viz.canvas; + this.config = viz.config; + }, + + /* + * Calls the request method on the controller to request a subtree for each node. + */ + requestNodes: function(nodes, controller){ + var counter = 0, len = nodes.length, nodeSelected = {}; + var complete = function(){ + controller.onComplete(); + }; + var viz = this.viz; + if (len == 0) + complete(); + for(var i = 0; i < len; i++) { + nodeSelected[nodes[i].id] = nodes[i]; + controller.request(nodes[i].id, nodes[i]._level, { + onComplete: function(nodeId, data){ + if (data && data.children) { + data.id = nodeId; + viz.op.sum(data, { + type: 'nothing' + }); + } + if (++counter == len) { + Graph.Util.computeLevels(viz.graph, viz.root, 0); + complete(); + } + } + }); + } + } +}); + +/* + Class: Icicle.Plot + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ +$jit.Icicle.Plot = new Class({ + Implements: Graph.Plot, + + plot: function(opt, animating){ + opt = opt || this.viz.controller; + var viz = this.viz, + graph = viz.graph, + root = graph.getNode(viz.clickedNode && viz.clickedNode.id || viz.root), + initialDepth = root._depth; + + viz.canvas.clear(); + this.plotTree(root, $.merge(opt, { + 'withLabels': true, + 'hideLabels': false, + 'plotSubtree': function(root, node) { + return !viz.config.constrained || + (node._depth - initialDepth < viz.config.levelsToShow); + } + }), animating); + } +}); + +/* + Class: Icicle.Label + + Custom extension of . + Contains custom , and extensions. + + Extends: + + All methods and subclasses. + + See also: + + , , , . + + */ +$jit.Icicle.Label = {}; + +/* + Icicle.Label.Native + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ +$jit.Icicle.Label.Native = new Class({ + Implements: Graph.Label.Native, + + renderLabel: function(canvas, node, controller) { + var ctx = canvas.getCtx(), + width = node.getData('width'), + height = node.getData('height'), + size = node.getLabelData('size'), + m = ctx.measureText(node.name); + + // Guess as much as possible if the label will fit in the node + if(height < (size * 1.5) || width < m.width) + return; + + var pos = node.pos.getc(true); + ctx.fillText(node.name, + pos.x + width / 2, + pos.y + height / 2); + } +}); + +/* + Icicle.Label.SVG + + Custom extension of . + + Extends: + + All methods + + See also: + + +*/ +$jit.Icicle.Label.SVG = new Class( { + Implements: Graph.Label.SVG, + + initialize: function(viz){ + this.viz = viz; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + */ + placeLabel: function(tag, node, controller){ + var pos = node.pos.getc(true), canvas = this.viz.canvas; + var radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x + radius.width / 2), + y: Math.round(pos.y + radius.height / 2) + }; + tag.setAttribute('x', labelPos.x); + tag.setAttribute('y', labelPos.y); + + controller.onPlaceLabel(tag, node); + } +}); + +/* + Icicle.Label.HTML + + Custom extension of . + + Extends: + + All methods. + + See also: + + + + */ +$jit.Icicle.Label.HTML = new Class( { + Implements: Graph.Label.HTML, + + initialize: function(viz){ + this.viz = viz; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + */ + placeLabel: function(tag, node, controller){ + var pos = node.pos.getc(true), canvas = this.viz.canvas; + var radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x + radius.width / 2), + y: Math.round(pos.y + radius.height / 2) + }; + + var style = tag.style; + style.left = labelPos.x + 'px'; + style.top = labelPos.y + 'px'; + style.display = ''; + + controller.onPlaceLabel(tag, node); + } +}); + +/* + Class: Icicle.Plot.NodeTypes + + This class contains a list of built-in types. + Node types implemented are 'none', 'rectangle'. + + You can add your custom node types, customizing your visualization to the extreme. + + Example: + + (start code js) + Icicle.Plot.NodeTypes.implement({ + 'mySpecialType': { + 'render': function(node, canvas) { + //print your custom node to canvas + }, + //optional + 'contains': function(node, pos) { + //return true if pos is inside the node or false otherwise + } + } + }); + (end code) + + */ +$jit.Icicle.Plot.NodeTypes = new Class( { + 'none': { + 'render': $.empty + }, + + 'rectangle': { + 'render': function(node, canvas, animating) { + var config = this.viz.config; + var offset = config.offset; + var width = node.getData('width'); + var height = node.getData('height'); + var border = node.getData('border'); + var pos = node.pos.getc(true); + var posx = pos.x + offset / 2, posy = pos.y + offset / 2; + var ctx = canvas.getCtx(); + + if(width - offset < 2 || height - offset < 2) return; + + if(config.cushion) { + var color = node.getData('color'); + var lg = ctx.createRadialGradient(posx + (width - offset)/2, + posy + (height - offset)/2, 1, + posx + (width-offset)/2, posy + (height-offset)/2, + width < height? height : width); + var colorGrad = $.rgbToHex($.map($.hexToRgb(color), + function(r) { return r * 0.3 >> 0; })); + lg.addColorStop(0, color); + lg.addColorStop(1, colorGrad); + ctx.fillStyle = lg; + } + + if (border) { + ctx.strokeStyle = border; + ctx.lineWidth = 3; + } + + ctx.fillRect(posx, posy, Math.max(0, width - offset), Math.max(0, height - offset)); + border && ctx.strokeRect(pos.x, pos.y, width, height); + }, + + 'contains': function(node, pos) { + if(this.viz.clickedNode && !$jit.Graph.Util.isDescendantOf(node, this.viz.clickedNode.id)) return false; + var npos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + return this.nodeHelper.rectangle.contains({x: npos.x + width/2, y: npos.y + height/2}, pos, width, height); + } + } +}); + +$jit.Icicle.Plot.EdgeTypes = new Class( { + 'none': $.empty +}); + + + +/* + * File: Layouts.ForceDirected.js + * +*/ + +/* + * Class: Layouts.ForceDirected + * + * Implements a Force Directed Layout. + * + * Implemented By: + * + * + * + * Credits: + * + * Marcus Cobden + * + */ +Layouts.ForceDirected = new Class({ + + getOptions: function(random) { + var s = this.canvas.getSize(); + var w = s.width, h = s.height; + //count nodes + var count = 0; + this.graph.eachNode(function(n) { + count++; + }); + var k2 = w * h / count, k = Math.sqrt(k2); + var l = this.config.levelDistance; + + return { + width: w, + height: h, + tstart: w * 0.1, + nodef: function(x) { return k2 / (x || 1); }, + edgef: function(x) { return /* x * x / k; */ k * (x - l); } + }; + }, + + compute: function(property, incremental) { + var prop = $.splat(property || ['current', 'start', 'end']); + var opt = this.getOptions(); + NodeDim.compute(this.graph, prop, this.config); + this.graph.computeLevels(this.root, 0, "ignore"); + this.graph.eachNode(function(n) { + $.each(prop, function(p) { + var pos = n.getPos(p); + if(pos.equals(Complex.KER)) { + pos.x = opt.width/5 * (Math.random() - 0.5); + pos.y = opt.height/5 * (Math.random() - 0.5); + } + //initialize disp vector + n.disp = {}; + $.each(prop, function(p) { + n.disp[p] = $C(0, 0); + }); + }); + }); + this.computePositions(prop, opt, incremental); + }, + + computePositions: function(property, opt, incremental) { + var times = this.config.iterations, i = 0, that = this; + if(incremental) { + (function iter() { + for(var total=incremental.iter, j=0; j= times) { + incremental.onComplete(); + return; + } + } + incremental.onStep(Math.round(i / (times -1) * 100)); + setTimeout(iter, 1); + })(); + } else { + for(; i < times; i++) { + opt.t = opt.tstart * (1 - i/(times -1)); + this.computePositionStep(property, opt); + } + } + }, + + computePositionStep: function(property, opt) { + var graph = this.graph; + var min = Math.min, max = Math.max; + var dpos = $C(0, 0); + //calculate repulsive forces + graph.eachNode(function(v) { + //initialize disp + $.each(property, function(p) { + v.disp[p].x = 0; v.disp[p].y = 0; + }); + graph.eachNode(function(u) { + if(u.id != v.id) { + $.each(property, function(p) { + var vp = v.getPos(p), up = u.getPos(p); + dpos.x = vp.x - up.x; + dpos.y = vp.y - up.y; + var norm = dpos.norm() || 1; + v.disp[p].$add(dpos + .$scale(opt.nodef(norm) / norm)); + }); + } + }); + }); + //calculate attractive forces + var T = !!graph.getNode(this.root).visited; + graph.eachNode(function(node) { + node.eachAdjacency(function(adj) { + var nodeTo = adj.nodeTo; + if(!!nodeTo.visited === T) { + $.each(property, function(p) { + var vp = node.getPos(p), up = nodeTo.getPos(p); + dpos.x = vp.x - up.x; + dpos.y = vp.y - up.y; + var norm = dpos.norm() || 1; + node.disp[p].$add(dpos.$scale(-opt.edgef(norm) / norm)); + nodeTo.disp[p].$add(dpos.$scale(-1)); + }); + } + }); + node.visited = !T; + }); + //arrange positions to fit the canvas + var t = opt.t, w2 = opt.width / 2, h2 = opt.height / 2; + graph.eachNode(function(u) { + $.each(property, function(p) { + var disp = u.disp[p]; + var norm = disp.norm() || 1; + var p = u.getPos(p); + p.$add($C(disp.x * min(Math.abs(disp.x), t) / norm, + disp.y * min(Math.abs(disp.y), t) / norm)); + p.x = min(w2, max(-w2, p.x)); + p.y = min(h2, max(-h2, p.y)); + }); + }); + } +}); + +/* + * File: ForceDirected.js + */ + +/* + Class: ForceDirected + + A visualization that lays graphs using a Force-Directed layout algorithm. + + Inspired by: + + Force-Directed Drawing Algorithms (Stephen G. Kobourov) + + Implements: + + All methods + + Constructor Options: + + Inherits options from + + - + - + - + - + - + - + - + - + - + + Additionally, there are two parameters + + levelDistance - (number) Default's *50*. The natural length desired for the edges. + iterations - (number) Default's *50*. The number of iterations for the spring layout simulation. Depending on the browser's speed you could set this to a more 'interesting' number, like *200*. + + Instance Properties: + + canvas - Access a instance. + graph - Access a instance. + op - Access a instance. + fx - Access a instance. + labels - Access a interface implementation. + +*/ + +$jit.ForceDirected = new Class( { + + Implements: [ Loader, Extras, Layouts.ForceDirected ], + + initialize: function(controller) { + var $ForceDirected = $jit.ForceDirected; + + var config = { + iterations: 50, + levelDistance: 50 + }; + + this.controller = this.config = $.merge(Options("Canvas", "Node", "Edge", + "Fx", "Tips", "NodeStyles", "Events", "Navigation", "Controller", "Label"), config, controller); + + var canvasConfig = this.config; + if(canvasConfig.useCanvas) { + this.canvas = canvasConfig.useCanvas; + this.config.labelContainer = this.canvas.id + '-label'; + } else { + if(canvasConfig.background) { + canvasConfig.background = $.merge({ + type: 'Circles' + }, canvasConfig.background); + } + this.canvas = new Canvas(this, canvasConfig); + this.config.labelContainer = (typeof canvasConfig.injectInto == 'string'? canvasConfig.injectInto : canvasConfig.injectInto.id) + '-label'; + } + + this.graphOptions = { + 'klass': Complex, + 'Node': { + 'selected': false, + 'exist': true, + 'drawn': true + } + }; + this.graph = new Graph(this.graphOptions, this.config.Node, + this.config.Edge); + this.labels = new $ForceDirected.Label[canvasConfig.Label.type](this); + this.fx = new $ForceDirected.Plot(this, $ForceDirected); + this.op = new $ForceDirected.Op(this); + this.json = null; + this.busy = false; + // initialize extras + this.initializeExtras(); + }, + + /* + Method: refresh + + Computes positions and plots the tree. + */ + refresh: function() { + this.compute(); + this.plot(); + }, + + reposition: function() { + this.compute('end'); + }, + +/* + Method: computeIncremental + + Performs the Force Directed algorithm incrementally. + + Description: + + ForceDirected algorithms can perform many computations and lead to JavaScript taking too much time to complete. + This method splits the algorithm into smaller parts allowing the user to track the evolution of the algorithm and + avoiding browser messages such as "This script is taking too long to complete". + + Parameters: + + opt - (object) The object properties are described below + + iter - (number) Default's *20*. Split the algorithm into pieces of _iter_ iterations. For example, if the _iterations_ configuration property + of your class is 100, then you could set _iter_ to 20 to split the main algorithm into 5 smaller pieces. + + property - (string) Default's *end*. Whether to update starting, current or ending node positions. Possible values are 'end', 'start', 'current'. + You can also set an array of these properties. If you'd like to keep the current node positions but to perform these + computations for final animation positions then you can just choose 'end'. + + onStep - (function) A callback function called when each "small part" of the algorithm completed. This function gets as first formal + parameter a percentage value. + + onComplete - A callback function called when the algorithm completed. + + Example: + + In this example I calculate the end positions and then animate the graph to those positions + + (start code js) + var fd = new $jit.ForceDirected(...); + fd.computeIncremental({ + iter: 20, + property: 'end', + onStep: function(perc) { + Log.write("loading " + perc + "%"); + }, + onComplete: function() { + Log.write("done"); + fd.animate(); + } + }); + (end code) + + In this example I calculate all positions and (re)plot the graph + + (start code js) + var fd = new ForceDirected(...); + fd.computeIncremental({ + iter: 20, + property: ['end', 'start', 'current'], + onStep: function(perc) { + Log.write("loading " + perc + "%"); + }, + onComplete: function() { + Log.write("done"); + fd.plot(); + } + }); + (end code) + + */ + computeIncremental: function(opt) { + opt = $.merge( { + iter: 20, + property: 'end', + onStep: $.empty, + onComplete: $.empty + }, opt || {}); + + this.config.onBeforeCompute(this.graph.getNode(this.root)); + this.compute(opt.property, opt); + }, + + /* + Method: plot + + Plots the ForceDirected graph. This is a shortcut to *fx.plot*. + */ + plot: function() { + this.fx.plot(); + }, + + /* + Method: animate + + Animates the graph from the current positions to the 'end' node positions. + */ + animate: function(opt) { + this.fx.animate($.merge( { + modes: [ 'linear' ] + }, opt || {})); + } +}); + +$jit.ForceDirected.$extend = true; + +(function(ForceDirected) { + + /* + Class: ForceDirected.Op + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + ForceDirected.Op = new Class( { + + Implements: Graph.Op + + }); + + /* + Class: ForceDirected.Plot + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + ForceDirected.Plot = new Class( { + + Implements: Graph.Plot + + }); + + /* + Class: ForceDirected.Label + + Custom extension of . + Contains custom , and extensions. + + Extends: + + All methods and subclasses. + + See also: + + , , , . + + */ + ForceDirected.Label = {}; + + /* + ForceDirected.Label.Native + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + ForceDirected.Label.Native = new Class( { + Implements: Graph.Label.Native + }); + + /* + ForceDirected.Label.SVG + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + ForceDirected.Label.SVG = new Class( { + Implements: Graph.Label.SVG, + + initialize: function(viz) { + this.viz = viz; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller) { + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x * sx + ox + radius.width / 2), + y: Math.round(pos.y * sy + oy + radius.height / 2) + }; + tag.setAttribute('x', labelPos.x); + tag.setAttribute('y', labelPos.y); + + controller.onPlaceLabel(tag, node); + } + }); + + /* + ForceDirected.Label.HTML + + Custom extension of . + + Extends: + + All methods. + + See also: + + + + */ + ForceDirected.Label.HTML = new Class( { + Implements: Graph.Label.HTML, + + initialize: function(viz) { + this.viz = viz; + }, + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller) { + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x * sx + ox + radius.width / 2), + y: Math.round(pos.y * sy + oy + radius.height / 2) + }; + var style = tag.style; + style.left = labelPos.x + 'px'; + style.top = labelPos.y + 'px'; + style.display = this.fitsInCanvas(labelPos, canvas) ? '' : 'none'; + + controller.onPlaceLabel(tag, node); + } + }); + + /* + Class: ForceDirected.Plot.NodeTypes + + This class contains a list of built-in types. + Node types implemented are 'none', 'circle', 'triangle', 'rectangle', 'star', 'ellipse' and 'square'. + + You can add your custom node types, customizing your visualization to the extreme. + + Example: + + (start code js) + ForceDirected.Plot.NodeTypes.implement({ + 'mySpecialType': { + 'render': function(node, canvas) { + //print your custom node to canvas + }, + //optional + 'contains': function(node, pos) { + //return true if pos is inside the node or false otherwise + } + } + }); + (end code) + + */ + ForceDirected.Plot.NodeTypes = new Class({ + 'none': { + 'render': $.empty, + 'contains': $.lambda(false) + }, + 'circle': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.circle.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.circle.contains(npos, pos, dim); + } + }, + 'ellipse': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + this.nodeHelper.ellipse.render('fill', pos, width, height, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + return this.nodeHelper.ellipse.contains(npos, pos, width, height); + } + }, + 'square': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.square.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.square.contains(npos, pos, dim); + } + }, + 'rectangle': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + this.nodeHelper.rectangle.render('fill', pos, width, height, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + return this.nodeHelper.rectangle.contains(npos, pos, width, height); + } + }, + 'triangle': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.triangle.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos) { + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.triangle.contains(npos, pos, dim); + } + }, + 'star': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.star.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos) { + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.star.contains(npos, pos, dim); + } + } + }); + + /* + Class: ForceDirected.Plot.EdgeTypes + + This class contains a list of built-in types. + Edge types implemented are 'none', 'line' and 'arrow'. + + You can add your custom edge types, customizing your visualization to the extreme. + + Example: + + (start code js) + ForceDirected.Plot.EdgeTypes.implement({ + 'mySpecialType': { + 'render': function(adj, canvas) { + //print your custom edge to canvas + }, + //optional + 'contains': function(adj, pos) { + //return true if pos is inside the arc or false otherwise + } + } + }); + (end code) + + */ + ForceDirected.Plot.EdgeTypes = new Class({ + 'none': $.empty, + 'line': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + this.edgeHelper.line.render(from, to, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + return this.edgeHelper.line.contains(from, to, pos, this.edge.epsilon); + } + }, + 'arrow': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true), + dim = adj.getData('dim'), + direction = adj.data.$direction, + inv = (direction && direction.length>1 && direction[0] != adj.nodeFrom.id); + this.edgeHelper.arrow.render(from, to, dim, inv, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + return this.edgeHelper.arrow.contains(from, to, pos, this.edge.epsilon); + } + } + }); + +})($jit.ForceDirected); + + +/* + * File: Treemap.js + * +*/ + +$jit.TM = {}; + +var TM = $jit.TM; + +$jit.TM.$extend = true; + +/* + Class: TM.Base + + Abstract class providing base functionality for , and visualizations. + + Implements: + + All methods + + Constructor Options: + + Inherits options from + + - + - + - + - + - + - + - + - + - + + Additionally, there are other parameters and some default values changed + + orientation - (string) Default's *h*. Whether to set horizontal or vertical layouts. Possible values are 'h' and 'v'. + titleHeight - (number) Default's *13*. The height of the title rectangle for inner (non-leaf) nodes. + offset - (number) Default's *2*. Boxes offset. + constrained - (boolean) Default's *false*. Whether to show the entire tree when loaded or just the number of levels specified by _levelsToShow_. + levelsToShow - (number) Default's *3*. The number of levels to show for a subtree. This number is relative to the selected node. + animate - (boolean) Default's *false*. Whether to animate transitions. + Node.type - Described in . Default's *rectangle*. + duration - Described in . Default's *700*. + fps - Described in . Default's *45*. + + Instance Properties: + + canvas - Access a instance. + graph - Access a instance. + op - Access a instance. + fx - Access a instance. + labels - Access a interface implementation. + + Inspired by: + + Squarified Treemaps (Mark Bruls, Kees Huizing, and Jarke J. van Wijk) + + Tree visualization with tree-maps: 2-d space-filling approach (Ben Shneiderman) + + Note: + + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the visualization described in the paper. + +*/ +TM.Base = { + layout: { + orientation: "h", + vertical: function(){ + return this.orientation == "v"; + }, + horizontal: function(){ + return this.orientation == "h"; + }, + change: function(){ + this.orientation = this.vertical()? "h" : "v"; + } + }, + + initialize: function(controller){ + var config = { + orientation: "h", + titleHeight: 13, + offset: 2, + levelsToShow: 0, + constrained: false, + animate: false, + Node: { + type: 'rectangle', + overridable: true, + //we all know why this is not zero, + //right, Firefox? + width: 3, + height: 3, + color: '#444' + }, + Label: { + textAlign: 'center', + textBaseline: 'top' + }, + Edge: { + type: 'none' + }, + duration: 700, + fps: 45 + }; + + this.controller = this.config = $.merge(Options("Canvas", "Node", "Edge", + "Fx", "Controller", "Tips", "NodeStyles", "Events", "Navigation", "Label"), config, controller); + this.layout.orientation = this.config.orientation; + + var canvasConfig = this.config; + if (canvasConfig.useCanvas) { + this.canvas = canvasConfig.useCanvas; + this.config.labelContainer = this.canvas.id + '-label'; + } else { + if(canvasConfig.background) { + canvasConfig.background = $.merge({ + type: 'Circles' + }, canvasConfig.background); + } + this.canvas = new Canvas(this, canvasConfig); + this.config.labelContainer = (typeof canvasConfig.injectInto == 'string'? canvasConfig.injectInto : canvasConfig.injectInto.id) + '-label'; + } + + this.graphOptions = { + 'klass': Complex, + 'Node': { + 'selected': false, + 'exist': true, + 'drawn': true + } + }; + this.graph = new Graph(this.graphOptions, this.config.Node, + this.config.Edge); + this.labels = new TM.Label[canvasConfig.Label.type](this); + this.fx = new TM.Plot(this); + this.op = new TM.Op(this); + this.group = new TM.Group(this); + this.geom = new TM.Geom(this); + this.clickedNode = null; + this.busy = false; + // initialize extras + this.initializeExtras(); + }, + + /* + Method: refresh + + Computes positions and plots the tree. + */ + refresh: function(){ + if(this.busy) return; + this.busy = true; + var that = this; + if(this.config.animate) { + this.compute('end'); + this.config.levelsToShow > 0 && this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode + && this.clickedNode.id || this.root)); + this.fx.animate($.merge(this.config, { + modes: ['linear', 'node-property:width:height'], + onComplete: function() { + that.busy = false; + } + })); + } else { + var labelType = this.config.Label.type; + if(labelType != 'Native') { + var that = this; + this.graph.eachNode(function(n) { that.labels.hideLabel(n, false); }); + } + this.busy = false; + this.compute(); + this.config.levelsToShow > 0 && this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode + && this.clickedNode.id || this.root)); + this.plot(); + } + }, + + /* + Method: plot + + Plots the TreeMap. This is a shortcut to *fx.plot*. + + */ + plot: function(){ + this.fx.plot(); + }, + + /* + Method: leaf + + Returns whether the node is a leaf. + + Parameters: + + n - (object) A . + + */ + leaf: function(n){ + return n.getSubnodes([ + 1, 1 + ], "ignore").length == 0; + }, + + /* + Method: enter + + Sets the node as root. + + Parameters: + + n - (object) A . + + */ + enter: function(n){ + if(this.busy) return; + this.busy = true; + + var that = this, + config = this.config, + graph = this.graph, + clickedNode = n, + previousClickedNode = this.clickedNode; + + var callback = { + onComplete: function() { + //ensure that nodes are shown for that level + if(config.levelsToShow > 0) { + that.geom.setRightLevelToShow(n); + } + //compute positions of newly inserted nodes + if(config.levelsToShow > 0 || config.request) that.compute(); + if(config.animate) { + //fade nodes + graph.nodeList.setData('alpha', 0, 'end'); + n.eachSubgraph(function(n) { + n.setData('alpha', 1, 'end'); + }, "ignore"); + that.fx.animate({ + duration: 500, + modes:['node-property:alpha'], + onComplete: function() { + //compute end positions + that.clickedNode = clickedNode; + that.compute('end'); + //animate positions + //TODO(nico) commenting this line didn't seem to throw errors... + that.clickedNode = previousClickedNode; + that.fx.animate({ + modes:['linear', 'node-property:width:height'], + duration: 1000, + onComplete: function() { + that.busy = false; + //TODO(nico) check comment above + that.clickedNode = clickedNode; + } + }); + } + }); + } else { + that.busy = false; + that.clickedNode = n; + that.refresh(); + } + } + }; + if(config.request) { + this.requestNodes(clickedNode, callback); + } else { + callback.onComplete(); + } + }, + + /* + Method: out + + Sets the parent node of the current selected node as root. + + */ + out: function(){ + if(this.busy) return; + this.busy = true; + this.events.hoveredNode = false; + var that = this, + config = this.config, + graph = this.graph, + parents = graph.getNode(this.clickedNode + && this.clickedNode.id || this.root).getParents(), + parent = parents[0], + clickedNode = parent, + previousClickedNode = this.clickedNode; + + //if no parents return + if(!parent) { + this.busy = false; + return; + } + //final plot callback + callback = { + onComplete: function() { + that.clickedNode = parent; + if(config.request) { + that.requestNodes(parent, { + onComplete: function() { + that.compute(); + that.plot(); + that.busy = false; + } + }); + } else { + that.compute(); + that.plot(); + that.busy = false; + } + } + }; + //prune tree + if (config.levelsToShow > 0) + this.geom.setRightLevelToShow(parent); + //animate node positions + if(config.animate) { + this.clickedNode = clickedNode; + this.compute('end'); + //animate the visible subtree only + this.clickedNode = previousClickedNode; + this.fx.animate({ + modes:['linear', 'node-property:width:height'], + duration: 1000, + onComplete: function() { + //animate the parent subtree + that.clickedNode = clickedNode; + //change nodes alpha + graph.eachNode(function(n) { + n.setDataset(['current', 'end'], { + 'alpha': [0, 1] + }); + }, "ignore"); + previousClickedNode.eachSubgraph(function(node) { + node.setData('alpha', 1); + }, "ignore"); + that.fx.animate({ + duration: 500, + modes:['node-property:alpha'], + onComplete: function() { + callback.onComplete(); + } + }); + } + }); + } else { + callback.onComplete(); + } + }, + + requestNodes: function(node, onComplete){ + var handler = $.merge(this.controller, onComplete), + lev = this.config.levelsToShow; + if (handler.request) { + var leaves = [], d = node._depth; + node.eachLevel(0, lev, function(n){ + var nodeLevel = lev - (n._depth - d); + if (n.drawn && !n.anySubnode() && nodeLevel > 0) { + leaves.push(n); + n._level = nodeLevel; + } + }); + this.group.requestNodes(leaves, handler); + } else { + handler.onComplete(); + } + }, + + reposition: function() { + this.compute('end'); + } +}; + +/* + Class: TM.Op + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ +TM.Op = new Class({ + Implements: Graph.Op, + + initialize: function(viz){ + this.viz = viz; + } +}); + +//extend level methods of Graph.Geom +TM.Geom = new Class({ + Implements: Graph.Geom, + + getRightLevelToShow: function() { + return this.viz.config.levelsToShow; + }, + + setRightLevelToShow: function(node) { + var level = this.getRightLevelToShow(), + fx = this.viz.labels; + node.eachLevel(0, level+1, function(n) { + var d = n._depth - node._depth; + if(d > level) { + n.drawn = false; + n.exist = false; + n.ignore = true; + fx.hideLabel(n, false); + } else { + n.drawn = true; + n.exist = true; + delete n.ignore; + } + }); + node.drawn = true; + delete node.ignore; + } +}); + +/* + +Performs operations on group of nodes. + +*/ +TM.Group = new Class( { + + initialize: function(viz){ + this.viz = viz; + this.canvas = viz.canvas; + this.config = viz.config; + }, + + /* + + Calls the request method on the controller to request a subtree for each node. + */ + requestNodes: function(nodes, controller){ + var counter = 0, len = nodes.length, nodeSelected = {}; + var complete = function(){ + controller.onComplete(); + }; + var viz = this.viz; + if (len == 0) + complete(); + for ( var i = 0; i < len; i++) { + nodeSelected[nodes[i].id] = nodes[i]; + controller.request(nodes[i].id, nodes[i]._level, { + onComplete: function(nodeId, data){ + if (data && data.children) { + data.id = nodeId; + viz.op.sum(data, { + type: 'nothing' + }); + } + if (++counter == len) { + viz.graph.computeLevels(viz.root, 0); + complete(); + } + } + }); + } + } +}); + +/* + Class: TM.Plot + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ +TM.Plot = new Class({ + + Implements: Graph.Plot, + + initialize: function(viz){ + this.viz = viz; + this.config = viz.config; + this.node = this.config.Node; + this.edge = this.config.Edge; + this.animation = new Animation; + this.nodeTypes = new TM.Plot.NodeTypes; + this.edgeTypes = new TM.Plot.EdgeTypes; + this.labels = viz.labels; + }, + + plot: function(opt, animating){ + var viz = this.viz, + graph = viz.graph; + viz.canvas.clear(); + this.plotTree(graph.getNode(viz.clickedNode && viz.clickedNode.id || viz.root), $.merge(viz.config, opt || {}, { + 'withLabels': true, + 'hideLabels': false, + 'plotSubtree': function(n, ch){ + return n.anySubnode("exist"); + } + }), animating); + } +}); + +/* + Class: TM.Label + + Custom extension of . + Contains custom , and extensions. + + Extends: + + All methods and subclasses. + + See also: + + , , , . + +*/ +TM.Label = {}; + +/* + TM.Label.Native + + Custom extension of . + + Extends: + + All methods + + See also: + + +*/ +TM.Label.Native = new Class({ + Implements: Graph.Label.Native, + + initialize: function(viz) { + this.config = viz.config; + this.leaf = viz.leaf; + }, + + renderLabel: function(canvas, node, controller){ + if(!this.leaf(node) && !this.config.titleHeight) return; + var pos = node.pos.getc(true), + ctx = canvas.getCtx(), + width = node.getData('width'), + height = node.getData('height'), + x = pos.x + width/2, + y = pos.y; + + ctx.fillText(node.name, x, y, width); + } +}); + +/* + TM.Label.SVG + + Custom extension of . + + Extends: + + All methods + + See also: + + +*/ +TM.Label.SVG = new Class( { + Implements: Graph.Label.SVG, + + initialize: function(viz){ + this.viz = viz; + this.leaf = viz.leaf; + this.config = viz.config; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller){ + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x * sx + ox + radius.width / 2), + y: Math.round(pos.y * sy + oy + radius.height / 2) + }; + tag.setAttribute('x', labelPos.x); + tag.setAttribute('y', labelPos.y); + + if(!this.leaf(node) && !this.config.titleHeight) { + tag.style.display = 'none'; + } + controller.onPlaceLabel(tag, node); + } +}); + +/* + TM.Label.HTML + + Custom extension of . + + Extends: + + All methods. + + See also: + + + +*/ +TM.Label.HTML = new Class( { + Implements: Graph.Label.HTML, + + initialize: function(viz){ + this.viz = viz; + this.leaf = viz.leaf; + this.config = viz.config; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller){ + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x * sx + ox + radius.width / 2), + y: Math.round(pos.y * sy + oy + radius.height / 2) + }; + + var style = tag.style; + style.left = labelPos.x + 'px'; + style.top = labelPos.y + 'px'; + style.width = node.getData('width') * sx + 'px'; + style.height = node.getData('height') * sy + 'px'; + style.zIndex = node._depth * 100; + style.display = ''; + + if(!this.leaf(node) && !this.config.titleHeight) { + tag.style.display = 'none'; + } + controller.onPlaceLabel(tag, node); + } +}); + +/* + Class: TM.Plot.NodeTypes + + This class contains a list of built-in types. + Node types implemented are 'none', 'rectangle'. + + You can add your custom node types, customizing your visualization to the extreme. + + Example: + + (start code js) + TM.Plot.NodeTypes.implement({ + 'mySpecialType': { + 'render': function(node, canvas) { + //print your custom node to canvas + }, + //optional + 'contains': function(node, pos) { + //return true if pos is inside the node or false otherwise + } + } + }); + (end code) + +*/ +TM.Plot.NodeTypes = new Class( { + 'none': { + 'render': $.empty + }, + + 'rectangle': { + 'render': function(node, canvas, animating){ + var leaf = this.viz.leaf(node), + config = this.config, + offst = config.offset, + titleHeight = config.titleHeight, + pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'), + border = node.getData('border'), + ctx = canvas.getCtx(), + posx = pos.x + offst / 2, + posy = pos.y + offst / 2; + if(width <= offst || height <= offst) return; + if (leaf) { + if(config.cushion) { + var lg = ctx.createRadialGradient(posx + (width-offst)/2, posy + (height-offst)/2, 1, + posx + (width-offst)/2, posy + (height-offst)/2, width < height? height : width); + var color = node.getData('color'); + var colorGrad = $.rgbToHex($.map($.hexToRgb(color), + function(r) { return r * 0.2 >> 0; })); + lg.addColorStop(0, color); + lg.addColorStop(1, colorGrad); + ctx.fillStyle = lg; + } + ctx.fillRect(posx, posy, width - offst, height - offst); + if(border) { + ctx.save(); + ctx.strokeStyle = border; + ctx.strokeRect(posx, posy, width - offst, height - offst); + ctx.restore(); + } + } else if(titleHeight > 0){ + ctx.fillRect(pos.x + offst / 2, pos.y + offst / 2, width - offst, + titleHeight - offst); + if(border) { + ctx.save(); + ctx.strokeStyle = border; + ctx.strokeRect(pos.x + offst / 2, pos.y + offst / 2, width - offst, + height - offst); + ctx.restore(); + } + } + }, + 'contains': function(node, pos) { + if(this.viz.clickedNode && !node.isDescendantOf(this.viz.clickedNode.id) || node.ignore) return false; + var npos = node.pos.getc(true), + width = node.getData('width'), + leaf = this.viz.leaf(node), + height = leaf? node.getData('height') : this.config.titleHeight; + return this.nodeHelper.rectangle.contains({x: npos.x + width/2, y: npos.y + height/2}, pos, width, height); + } + } +}); + +TM.Plot.EdgeTypes = new Class( { + 'none': $.empty +}); + +/* + Class: TM.SliceAndDice + + A slice and dice TreeMap visualization. + + Implements: + + All methods and properties. +*/ +TM.SliceAndDice = new Class( { + Implements: [ + Loader, Extras, TM.Base, Layouts.TM.SliceAndDice + ] +}); + +/* + Class: TM.Squarified + + A squarified TreeMap visualization. + + Implements: + + All methods and properties. +*/ +TM.Squarified = new Class( { + Implements: [ + Loader, Extras, TM.Base, Layouts.TM.Squarified + ] +}); + +/* + Class: TM.Strip + + A strip TreeMap visualization. + + Implements: + + All methods and properties. +*/ +TM.Strip = new Class( { + Implements: [ + Loader, Extras, TM.Base, Layouts.TM.Strip + ] +}); + + +/* + * File: RGraph.js + * + */ + +/* + Class: RGraph + + A radial graph visualization with advanced animations. + + Inspired by: + + Animated Exploration of Dynamic Graphs with Radial Layout (Ka-Ping Yee, Danyel Fisher, Rachna Dhamija, Marti Hearst) + + Note: + + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the visualization described in the paper. + + Implements: + + All methods + + Constructor Options: + + Inherits options from + + - + - + - + - + - + - + - + - + - + + Additionally, there are other parameters and some default values changed + + interpolation - (string) Default's *linear*. Describes the way nodes are interpolated. Possible values are 'linear' and 'polar'. + levelDistance - (number) Default's *100*. The distance between levels of the tree. + + Instance Properties: + + canvas - Access a instance. + graph - Access a instance. + op - Access a instance. + fx - Access a instance. + labels - Access a interface implementation. +*/ + +$jit.RGraph = new Class( { + + Implements: [ + Loader, Extras, Layouts.Radial + ], + + initialize: function(controller){ + var $RGraph = $jit.RGraph; + + var config = { + interpolation: 'linear', + levelDistance: 100 + }; + + this.controller = this.config = $.merge(Options("Canvas", "Node", "Edge", + "Fx", "Controller", "Tips", "NodeStyles", "Events", "Navigation", "Label"), config, controller); + + var canvasConfig = this.config; + if(canvasConfig.useCanvas) { + this.canvas = canvasConfig.useCanvas; + this.config.labelContainer = this.canvas.id + '-label'; + } else { + if(canvasConfig.background) { + canvasConfig.background = $.merge({ + type: 'Circles' + }, canvasConfig.background); + } + this.canvas = new Canvas(this, canvasConfig); + this.config.labelContainer = (typeof canvasConfig.injectInto == 'string'? canvasConfig.injectInto : canvasConfig.injectInto.id) + '-label'; + } + + this.graphOptions = { + 'klass': Polar, + 'Node': { + 'selected': false, + 'exist': true, + 'drawn': true + } + }; + this.graph = new Graph(this.graphOptions, this.config.Node, + this.config.Edge); + this.labels = new $RGraph.Label[canvasConfig.Label.type](this); + this.fx = new $RGraph.Plot(this, $RGraph); + this.op = new $RGraph.Op(this); + this.json = null; + this.root = null; + this.busy = false; + this.parent = false; + // initialize extras + this.initializeExtras(); + }, + + /* + + createLevelDistanceFunc + + Returns the levelDistance function used for calculating a node distance + to its origin. This function returns a function that is computed + per level and not per node, such that all nodes with the same depth will have the + same distance to the origin. The resulting function gets the + parent node as parameter and returns a float. + + */ + createLevelDistanceFunc: function(){ + var ld = this.config.levelDistance; + return function(elem){ + return (elem._depth + 1) * ld; + }; + }, + + /* + Method: refresh + + Computes positions and plots the tree. + + */ + refresh: function(){ + this.compute(); + this.plot(); + }, + + reposition: function(){ + this.compute('end'); + }, + + /* + Method: plot + + Plots the RGraph. This is a shortcut to *fx.plot*. + */ + plot: function(){ + this.fx.plot(); + }, + /* + getNodeAndParentAngle + + Returns the _parent_ of the given node, also calculating its angle span. + */ + getNodeAndParentAngle: function(id){ + var theta = false; + var n = this.graph.getNode(id); + var ps = n.getParents(); + var p = (ps.length > 0)? ps[0] : false; + if (p) { + var posParent = p.pos.getc(), posChild = n.pos.getc(); + var newPos = posParent.add(posChild.scale(-1)); + theta = Math.atan2(newPos.y, newPos.x); + if (theta < 0) + theta += 2 * Math.PI; + } + return { + parent: p, + theta: theta + }; + }, + /* + tagChildren + + Enumerates the children in order to maintain child ordering (second constraint of the paper). + */ + tagChildren: function(par, id){ + if (par.angleSpan) { + var adjs = []; + par.eachAdjacency(function(elem){ + adjs.push(elem.nodeTo); + }, "ignore"); + var len = adjs.length; + for ( var i = 0; i < len && id != adjs[i].id; i++) + ; + for ( var j = (i + 1) % len, k = 0; id != adjs[j].id; j = (j + 1) % len) { + adjs[j].dist = k++; + } + } + }, + /* + Method: onClick + + Animates the to center the node specified by *id*. + + Parameters: + + id - A id. + opt - (optional|object) An object containing some extra properties described below + hideLabels - (boolean) Default's *true*. Hide labels when performing the animation. + + Example: + + (start code js) + rgraph.onClick('someid'); + //or also... + rgraph.onClick('someid', { + hideLabels: false + }); + (end code) + + */ + onClick: function(id, opt){ + if (this.root != id && !this.busy) { + this.busy = true; + this.root = id; + var that = this; + this.controller.onBeforeCompute(this.graph.getNode(id)); + var obj = this.getNodeAndParentAngle(id); + + // second constraint + this.tagChildren(obj.parent, id); + this.parent = obj.parent; + this.compute('end'); + + // first constraint + var thetaDiff = obj.theta - obj.parent.endPos.theta; + this.graph.eachNode(function(elem){ + elem.endPos.set(elem.endPos.getp().add($P(thetaDiff, 0))); + }); + + var mode = this.config.interpolation; + opt = $.merge( { + onComplete: $.empty + }, opt || {}); + + this.fx.animate($.merge( { + hideLabels: true, + modes: [ + mode + ] + }, opt, { + onComplete: function(){ + that.busy = false; + opt.onComplete(); + } + })); + } + } +}); + +$jit.RGraph.$extend = true; + +(function(RGraph){ + + /* + Class: RGraph.Op + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + RGraph.Op = new Class( { + + Implements: Graph.Op + + }); + + /* + Class: RGraph.Plot + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + RGraph.Plot = new Class( { + + Implements: Graph.Plot + + }); + + /* + Object: RGraph.Label + + Custom extension of . + Contains custom , and extensions. + + Extends: + + All methods and subclasses. + + See also: + + , , , . + + */ + RGraph.Label = {}; + + /* + RGraph.Label.Native + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + RGraph.Label.Native = new Class( { + Implements: Graph.Label.Native + }); + + /* + RGraph.Label.SVG + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + RGraph.Label.SVG = new Class( { + Implements: Graph.Label.SVG, + + initialize: function(viz){ + this.viz = viz; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller){ + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x * sx + ox + radius.width / 2), + y: Math.round(pos.y * sy + oy + radius.height / 2) + }; + tag.setAttribute('x', labelPos.x); + tag.setAttribute('y', labelPos.y); + + controller.onPlaceLabel(tag, node); + } + }); + + /* + RGraph.Label.HTML + + Custom extension of . + + Extends: + + All methods. + + See also: + + + + */ + RGraph.Label.HTML = new Class( { + Implements: Graph.Label.HTML, + + initialize: function(viz){ + this.viz = viz; + }, + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller){ + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(); + var labelPos = { + x: Math.round(pos.x * sx + ox + radius.width / 2), + y: Math.round(pos.y * sy + oy + radius.height / 2) + }; + + var style = tag.style; + style.left = labelPos.x + 'px'; + style.top = labelPos.y + 'px'; + style.display = this.fitsInCanvas(labelPos, canvas)? '' : 'none'; + + controller.onPlaceLabel(tag, node); + } + }); + + /* + Class: RGraph.Plot.NodeTypes + + This class contains a list of built-in types. + Node types implemented are 'none', 'circle', 'triangle', 'rectangle', 'star', 'ellipse' and 'square'. + + You can add your custom node types, customizing your visualization to the extreme. + + Example: + + (start code js) + RGraph.Plot.NodeTypes.implement({ + 'mySpecialType': { + 'render': function(node, canvas) { + //print your custom node to canvas + }, + //optional + 'contains': function(node, pos) { + //return true if pos is inside the node or false otherwise + } + } + }); + (end code) + + */ + RGraph.Plot.NodeTypes = new Class({ + 'none': { + 'render': $.empty, + 'contains': $.lambda(false) + }, + 'circle': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.circle.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.circle.contains(npos, pos, dim); + } + }, + 'ellipse': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + this.nodeHelper.ellipse.render('fill', pos, width, height, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + return this.nodeHelper.ellipse.contains(npos, pos, width, height); + } + }, + 'square': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.square.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.square.contains(npos, pos, dim); + } + }, + 'rectangle': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + this.nodeHelper.rectangle.render('fill', pos, width, height, canvas); + }, + 'contains': function(node, pos){ + var npos = node.pos.getc(true), + width = node.getData('width'), + height = node.getData('height'); + return this.nodeHelper.rectangle.contains(npos, pos, width, height); + } + }, + 'triangle': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.triangle.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos) { + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.triangle.contains(npos, pos, dim); + } + }, + 'star': { + 'render': function(node, canvas){ + var pos = node.pos.getc(true), + dim = node.getData('dim'); + this.nodeHelper.star.render('fill', pos, dim, canvas); + }, + 'contains': function(node, pos) { + var npos = node.pos.getc(true), + dim = node.getData('dim'); + return this.nodeHelper.star.contains(npos, pos, dim); + } + } + }); + + /* + Class: RGraph.Plot.EdgeTypes + + This class contains a list of built-in types. + Edge types implemented are 'none', 'line' and 'arrow'. + + You can add your custom edge types, customizing your visualization to the extreme. + + Example: + + (start code js) + RGraph.Plot.EdgeTypes.implement({ + 'mySpecialType': { + 'render': function(adj, canvas) { + //print your custom edge to canvas + }, + //optional + 'contains': function(adj, pos) { + //return true if pos is inside the arc or false otherwise + } + } + }); + (end code) + + */ + RGraph.Plot.EdgeTypes = new Class({ + 'none': $.empty, + 'line': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + this.edgeHelper.line.render(from, to, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + return this.edgeHelper.line.contains(from, to, pos, this.edge.epsilon); + } + }, + 'arrow': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true), + dim = adj.getData('dim'), + direction = adj.data.$direction, + inv = (direction && direction.length>1 && direction[0] != adj.nodeFrom.id); + this.edgeHelper.arrow.render(from, to, dim, inv, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true); + return this.edgeHelper.arrow.contains(from, to, pos, this.edge.epsilon); + } + } + }); + +})($jit.RGraph); + + +/* + * File: Hypertree.js + * +*/ + +/* + Complex + + A multi-purpose Complex Class with common methods. Extended for the Hypertree. + +*/ +/* + moebiusTransformation + + Calculates a moebius transformation for this point / complex. + For more information go to: + http://en.wikipedia.org/wiki/Moebius_transformation. + + Parameters: + + c - An initialized Complex instance representing a translation Vector. +*/ + +Complex.prototype.moebiusTransformation = function(c) { + var num = this.add(c); + var den = c.$conjugate().$prod(this); + den.x++; + return num.$div(den); +}; + +/* + moebiusTransformation + + Calculates a moebius transformation for the hyperbolic tree. + + + + Parameters: + + graph - A instance. + pos - A . + prop - A property array. + theta - Rotation angle. + startPos - _optional_ start position. +*/ +Graph.Util.moebiusTransformation = function(graph, pos, prop, startPos, flags) { + this.eachNode(graph, function(elem) { + for ( var i = 0; i < prop.length; i++) { + var p = pos[i].scale(-1), property = startPos ? startPos : prop[i]; + elem.getPos(prop[i]).set(elem.getPos(property).getc().moebiusTransformation(p)); + } + }, flags); +}; + +/* + Class: Hypertree + + A Hyperbolic Tree/Graph visualization. + + Inspired by: + + A Focus+Context Technique Based on Hyperbolic Geometry for Visualizing Large Hierarchies (John Lamping, Ramana Rao, and Peter Pirolli). + + + Note: + + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the Hypertree described in the paper. + + Implements: + + All methods + + Constructor Options: + + Inherits options from + + - + - + - + - + - + - + - + - + - + + Additionally, there are other parameters and some default values changed + + radius - (string|number) Default's *auto*. The radius of the disc to plot the in. 'auto' will take the smaller value from the width and height canvas dimensions. You can also set this to a custom value, for example *250*. + offset - (number) Default's *0*. A number in the range [0, 1) that will be substracted to each node position to make a more compact . This will avoid placing nodes too far from each other when a there's a selected node. + fps - Described in . It's default value has been changed to *35*. + duration - Described in . It's default value has been changed to *1500*. + Edge.type - Described in . It's default value has been changed to *hyperline*. + + Instance Properties: + + canvas - Access a instance. + graph - Access a instance. + op - Access a instance. + fx - Access a instance. + labels - Access a interface implementation. + +*/ + +$jit.Hypertree = new Class( { + + Implements: [ Loader, Extras, Layouts.Radial ], + + initialize: function(controller) { + var $Hypertree = $jit.Hypertree; + + var config = { + radius: "auto", + offset: 0, + Edge: { + type: 'hyperline' + }, + duration: 1500, + fps: 35 + }; + this.controller = this.config = $.merge(Options("Canvas", "Node", "Edge", + "Fx", "Tips", "NodeStyles", "Events", "Navigation", "Controller", "Label"), config, controller); + + var canvasConfig = this.config; + if(canvasConfig.useCanvas) { + this.canvas = canvasConfig.useCanvas; + this.config.labelContainer = this.canvas.id + '-label'; + } else { + if(canvasConfig.background) { + canvasConfig.background = $.merge({ + type: 'Circles' + }, canvasConfig.background); + } + this.canvas = new Canvas(this, canvasConfig); + this.config.labelContainer = (typeof canvasConfig.injectInto == 'string'? canvasConfig.injectInto : canvasConfig.injectInto.id) + '-label'; + } + + this.graphOptions = { + 'klass': Polar, + 'Node': { + 'selected': false, + 'exist': true, + 'drawn': true + } + }; + this.graph = new Graph(this.graphOptions, this.config.Node, + this.config.Edge); + this.labels = new $Hypertree.Label[canvasConfig.Label.type](this); + this.fx = new $Hypertree.Plot(this, $Hypertree); + this.op = new $Hypertree.Op(this); + this.json = null; + this.root = null; + this.busy = false; + // initialize extras + this.initializeExtras(); + }, + + /* + + createLevelDistanceFunc + + Returns the levelDistance function used for calculating a node distance + to its origin. This function returns a function that is computed + per level and not per node, such that all nodes with the same depth will have the + same distance to the origin. The resulting function gets the + parent node as parameter and returns a float. + + */ + createLevelDistanceFunc: function() { + // get max viz. length. + var r = this.getRadius(); + // get max depth. + var depth = 0, max = Math.max, config = this.config; + this.graph.eachNode(function(node) { + depth = max(node._depth, depth); + }, "ignore"); + depth++; + // node distance generator + var genDistFunc = function(a) { + return function(node) { + node.scale = r; + var d = node._depth + 1; + var acum = 0, pow = Math.pow; + while (d) { + acum += pow(a, d--); + } + return acum - config.offset; + }; + }; + // estimate better edge length. + for ( var i = 0.51; i <= 1; i += 0.01) { + var valSeries = (1 - Math.pow(i, depth)) / (1 - i); + if (valSeries >= 2) { return genDistFunc(i - 0.01); } + } + return genDistFunc(0.75); + }, + + /* + Method: getRadius + + Returns the current radius of the visualization. If *config.radius* is *auto* then it + calculates the radius by taking the smaller size of the widget. + + See also: + + + + */ + getRadius: function() { + var rad = this.config.radius; + if (rad !== "auto") { return rad; } + var s = this.canvas.getSize(); + return Math.min(s.width, s.height) / 2; + }, + + /* + Method: refresh + + Computes positions and plots the tree. + + Parameters: + + reposition - (optional|boolean) Set this to *true* to force all positions (current, start, end) to match. + + */ + refresh: function(reposition) { + if (reposition) { + this.reposition(); + this.graph.eachNode(function(node) { + node.startPos.rho = node.pos.rho = node.endPos.rho; + node.startPos.theta = node.pos.theta = node.endPos.theta; + }); + } else { + this.compute(); + } + this.plot(); + }, + + /* + reposition + + Computes nodes' positions and restores the tree to its previous position. + + For calculating nodes' positions the root must be placed on its origin. This method does this + and then attemps to restore the hypertree to its previous position. + + */ + reposition: function() { + this.compute('end'); + var vector = this.graph.getNode(this.root).pos.getc().scale(-1); + Graph.Util.moebiusTransformation(this.graph, [ vector ], [ 'end' ], + 'end', "ignore"); + this.graph.eachNode(function(node) { + if (node.ignore) { + node.endPos.rho = node.pos.rho; + node.endPos.theta = node.pos.theta; + } + }); + }, + + /* + Method: plot + + Plots the . This is a shortcut to *fx.plot*. + + */ + plot: function() { + this.fx.plot(); + }, + + /* + Method: onClick + + Animates the to center the node specified by *id*. + + Parameters: + + id - A id. + opt - (optional|object) An object containing some extra properties described below + hideLabels - (boolean) Default's *true*. Hide labels when performing the animation. + + Example: + + (start code js) + ht.onClick('someid'); + //or also... + ht.onClick('someid', { + hideLabels: false + }); + (end code) + + */ + onClick: function(id, opt) { + var pos = this.graph.getNode(id).pos.getc(true); + this.move(pos, opt); + }, + + /* + Method: move + + Translates the tree to the given position. + + Parameters: + + pos - (object) A *x, y* coordinate object where x, y in [0, 1), to move the tree to. + opt - This object has been defined in + + Example: + + (start code js) + ht.move({ x: 0, y: 0.7 }, { + hideLabels: false + }); + (end code) + + */ + move: function(pos, opt) { + var versor = $C(pos.x, pos.y); + if (this.busy === false && versor.norm() < 1) { + this.busy = true; + var root = this.graph.getClosestNodeToPos(versor), that = this; + this.graph.computeLevels(root.id, 0); + this.controller.onBeforeCompute(root); + opt = $.merge( { + onComplete: $.empty + }, opt || {}); + this.fx.animate($.merge( { + modes: [ 'moebius' ], + hideLabels: true + }, opt, { + onComplete: function() { + that.busy = false; + opt.onComplete(); + } + }), versor); + } + } +}); + +$jit.Hypertree.$extend = true; + +(function(Hypertree) { + + /* + Class: Hypertree.Op + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + Hypertree.Op = new Class( { + + Implements: Graph.Op + + }); + + /* + Class: Hypertree.Plot + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + Hypertree.Plot = new Class( { + + Implements: Graph.Plot + + }); + + /* + Object: Hypertree.Label + + Custom extension of . + Contains custom , and extensions. + + Extends: + + All methods and subclasses. + + See also: + + , , , . + + */ + Hypertree.Label = {}; + + /* + Hypertree.Label.Native + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + Hypertree.Label.Native = new Class( { + Implements: Graph.Label.Native, + + initialize: function(viz) { + this.viz = viz; + }, + + renderLabel: function(canvas, node, controller) { + var ctx = canvas.getCtx(); + var coord = node.pos.getc(true); + var s = this.viz.getRadius(); + ctx.fillText(node.name, coord.x * s, coord.y * s); + } + }); + + /* + Hypertree.Label.SVG + + Custom extension of . + + Extends: + + All methods + + See also: + + + + */ + Hypertree.Label.SVG = new Class( { + Implements: Graph.Label.SVG, + + initialize: function(viz) { + this.viz = viz; + }, + + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller) { + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(), + r = this.viz.getRadius(); + var labelPos = { + x: Math.round((pos.x * sx) * r + ox + radius.width / 2), + y: Math.round((pos.y * sy) * r + oy + radius.height / 2) + }; + tag.setAttribute('x', labelPos.x); + tag.setAttribute('y', labelPos.y); + controller.onPlaceLabel(tag, node); + } + }); + + /* + Hypertree.Label.HTML + + Custom extension of . + + Extends: + + All methods. + + See also: + + + + */ + Hypertree.Label.HTML = new Class( { + Implements: Graph.Label.HTML, + + initialize: function(viz) { + this.viz = viz; + }, + /* + placeLabel + + Overrides abstract method placeLabel in . + + Parameters: + + tag - A DOM label element. + node - A . + controller - A configuration/controller object passed to the visualization. + + */ + placeLabel: function(tag, node, controller) { + var pos = node.pos.getc(true), + canvas = this.viz.canvas, + ox = canvas.translateOffsetX, + oy = canvas.translateOffsetY, + sx = canvas.scaleOffsetX, + sy = canvas.scaleOffsetY, + radius = canvas.getSize(), + r = this.viz.getRadius(); + var labelPos = { + x: Math.round((pos.x * sx) * r + ox + radius.width / 2), + y: Math.round((pos.y * sy) * r + oy + radius.height / 2) + }; + var style = tag.style; + style.left = labelPos.x + 'px'; + style.top = labelPos.y + 'px'; + style.display = this.fitsInCanvas(labelPos, canvas) ? '' : 'none'; + + controller.onPlaceLabel(tag, node); + } + }); + + /* + Class: Hypertree.Plot.NodeTypes + + This class contains a list of built-in types. + Node types implemented are 'none', 'circle', 'triangle', 'rectangle', 'star', 'ellipse' and 'square'. + + You can add your custom node types, customizing your visualization to the extreme. + + Example: + + (start code js) + Hypertree.Plot.NodeTypes.implement({ + 'mySpecialType': { + 'render': function(node, canvas) { + //print your custom node to canvas + }, + //optional + 'contains': function(node, pos) { + //return true if pos is inside the node or false otherwise + } + } + }); + (end code) + + */ + Hypertree.Plot.NodeTypes = new Class({ + 'none': { + 'render': $.empty, + 'contains': $.lambda(false) + }, + 'circle': { + 'render': function(node, canvas) { + var nconfig = this.node, + dim = node.getData('dim'), + p = node.pos.getc(); + dim = nconfig.transform? dim * (1 - p.squaredNorm()) : dim; + p.$scale(node.scale); + if (dim > 0.2) { + this.nodeHelper.circle.render('fill', p, dim, canvas); + } + }, + 'contains': function(node, pos) { + var dim = node.getData('dim'), + npos = node.pos.getc().$scale(node.scale); + return this.nodeHelper.circle.contains(npos, pos, dim); + } + }, + 'ellipse': { + 'render': function(node, canvas) { + var pos = node.pos.getc().$scale(node.scale), + width = node.getData('width'), + height = node.getData('height'); + this.nodeHelper.ellipse.render('fill', pos, width, height, canvas); + }, + 'contains': function(node, pos) { + var width = node.getData('width'), + height = node.getData('height'), + npos = node.pos.getc().$scale(node.scale); + return this.nodeHelper.circle.contains(npos, pos, width, height); + } + }, + 'square': { + 'render': function(node, canvas) { + var nconfig = this.node, + dim = node.getData('dim'), + p = node.pos.getc(); + dim = nconfig.transform? dim * (1 - p.squaredNorm()) : dim; + p.$scale(node.scale); + if (dim > 0.2) { + this.nodeHelper.square.render('fill', p, dim, canvas); + } + }, + 'contains': function(node, pos) { + var dim = node.getData('dim'), + npos = node.pos.getc().$scale(node.scale); + return this.nodeHelper.square.contains(npos, pos, dim); + } + }, + 'rectangle': { + 'render': function(node, canvas) { + var nconfig = this.node, + width = node.getData('width'), + height = node.getData('height'), + pos = node.pos.getc(); + width = nconfig.transform? width * (1 - pos.squaredNorm()) : width; + height = nconfig.transform? height * (1 - pos.squaredNorm()) : height; + pos.$scale(node.scale); + if (width > 0.2 && height > 0.2) { + this.nodeHelper.rectangle.render('fill', pos, width, height, canvas); + } + }, + 'contains': function(node, pos) { + var width = node.getData('width'), + height = node.getData('height'), + npos = node.pos.getc().$scale(node.scale); + return this.nodeHelper.rectangle.contains(npos, pos, width, height); + } + }, + 'triangle': { + 'render': function(node, canvas) { + var nconfig = this.node, + dim = node.getData('dim'), + p = node.pos.getc(); + dim = nconfig.transform? dim * (1 - p.squaredNorm()) : dim; + p.$scale(node.scale); + if (dim > 0.2) { + this.nodeHelper.triangle.render('fill', p, dim, canvas); + } + }, + 'contains': function(node, pos) { + var dim = node.getData('dim'), + npos = node.pos.getc().$scale(node.scale); + return this.nodeHelper.triangle.contains(npos, pos, dim); + } + }, + 'star': { + 'render': function(node, canvas) { + var nconfig = this.node, + dim = node.getData('dim'), + p = node.pos.getc(); + dim = nconfig.transform? dim * (1 - p.squaredNorm()) : dim; + p.$scale(node.scale); + if (dim > 0.2) { + this.nodeHelper.star.render('fill', p, dim, canvas); + } + }, + 'contains': function(node, pos) { + var dim = node.getData('dim'), + npos = node.pos.getc().$scale(node.scale); + return this.nodeHelper.star.contains(npos, pos, dim); + } + } + }); + + /* + Class: Hypertree.Plot.EdgeTypes + + This class contains a list of built-in types. + Edge types implemented are 'none', 'line', 'arrow' and 'hyperline'. + + You can add your custom edge types, customizing your visualization to the extreme. + + Example: + + (start code js) + Hypertree.Plot.EdgeTypes.implement({ + 'mySpecialType': { + 'render': function(adj, canvas) { + //print your custom edge to canvas + }, + //optional + 'contains': function(adj, pos) { + //return true if pos is inside the arc or false otherwise + } + } + }); + (end code) + + */ + Hypertree.Plot.EdgeTypes = new Class({ + 'none': $.empty, + 'line': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true), + r = adj.nodeFrom.scale; + this.edgeHelper.line.render({x:from.x*r, y:from.y*r}, {x:to.x*r, y:to.y*r}, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true), + r = adj.nodeFrom.scale; + this.edgeHelper.line.contains({x:from.x*r, y:from.y*r}, {x:to.x*r, y:to.y*r}, pos, this.edge.epsilon); + } + }, + 'arrow': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true), + r = adj.nodeFrom.scale, + dim = adj.getData('dim'), + direction = adj.data.$direction, + inv = (direction && direction.length>1 && direction[0] != adj.nodeFrom.id); + this.edgeHelper.arrow.render({x:from.x*r, y:from.y*r}, {x:to.x*r, y:to.y*r}, dim, inv, canvas); + }, + 'contains': function(adj, pos) { + var from = adj.nodeFrom.pos.getc(true), + to = adj.nodeTo.pos.getc(true), + r = adj.nodeFrom.scale; + this.edgeHelper.arrow.contains({x:from.x*r, y:from.y*r}, {x:to.x*r, y:to.y*r}, pos, this.edge.epsilon); + } + }, + 'hyperline': { + 'render': function(adj, canvas) { + var from = adj.nodeFrom.pos.getc(), + to = adj.nodeTo.pos.getc(), + dim = this.viz.getRadius(); + this.edgeHelper.hyperline.render(from, to, dim, canvas); + }, + 'contains': $.lambda(false) + } + }); + +})($jit.Hypertree); + + + + + })(); \ No newline at end of file diff --git a/frontend_knowledge/js/script.js b/frontend_knowledge/js/script.js new file mode 100644 index 0000000..88f39ff --- /dev/null +++ b/frontend_knowledge/js/script.js @@ -0,0 +1,554 @@ +var labelType, useGradients, nativeTextSupport, animate; + +(function() { + var ua = navigator.userAgent, + iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i), + typeOfCanvas = typeof HTMLCanvasElement, + nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'), + textSupport = nativeCanvasSupport + && (typeof document.createElement('canvas').getContext('2d').fillText == 'function'); + //I'm setting this based on the fact that ExCanvas provides text support for IE + //and that as of today iPhone/iPad current text support is lame + labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML'; + nativeTextSupport = labelType == 'Native'; + useGradients = nativeCanvasSupport; + animate = !(iStuff || !nativeCanvasSupport); +})(); + +var Log = { + elem: false, + write: function(text){ + if (!this.elem) + this.elem = document.getElementById('log'); + this.elem.innerHTML = text; + this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px'; + } +}; + + +function init(){ + //init data + var json = { + "id": "000", + "name": "前端工程师", + "children": [{ + "id": "001", + "name": "Web服务", + "children": [{ + "id": "001_01", + "name": "YQL/Company Open Platform" + }, + { + "id": "001_02", + "name": "APP Engine/Cloud" + }, + { + "id": "001_03", + "name": "Google Open API/Github" + }] + }, + {"id": "002", + "name": "前沿技术社区/会议", + "children": [{ + "id": "002_01", + "name": "YDN/YUIConf/JSConf" + }, + { + "id": "002_02", + "name": "QCon/Velocity" + }, + { + "id": "002_03", + "name": "D2/WebRebuild" + }, + { + "id": "002_04", + "name": "NodeParty/HTML5研究小组" + }, + { + "id": "002_05", + "name": "UED Teams" + }] + }, + {"id": "003", + "name": "移动终端", + "children": [{ + "id": "003_02", + "name": "jQueryMobile" + }, + { + "id": "003_03", + "name": "HTML5" + }, + { + "id": "003_04", + "name": "CSS3" + }, + { + "id": "003_05", + "name": "iOs/android" + }, + { + "id": "003_06", + "name": "responsive UI Design" + }] + }, + {"id": "004", + "name": "安全", + "children": [{ + "id": "004_01", + "name": "CSRF/XSS" + }, + { + "id": "004_02", + "name": "ADsafe" + }, + { + "id": "004_03", + "name": "Caja" + }, + { + "id": "004_04", + "name": "FBJS" + }, + { + "id": "004_05", + "name": "Sandbox" + }] + }, + {"id": "005", + "name": "软技能", + "children": [{ + "id": "005_01", + "name": "知识管理/总结分享" + },{ + "id": "005_02", + "name": "沟通技巧/团队开发" + },{ + "id": "005_03", + "name": "需求管理/PM" + },{ + "id": "005_04", + "name": "代码模块化开发/代码版本管理" + },{ + "id": "005_05", + "name": "交互设计/可用性" + },{ + "id": "005_06", + "name": "可访问性知识" + }] + }, + {"id": "006", + "name": "开发流程/部署", + "children": [{ + "id": "006_01", + "name": "JSLint" + },{ + "id": "006_02", + "name": "CSSLint" + },{ + "id": "006_03", + "name": "YUICompressor" + },{ + "id": "006_04", + "name": "JSMin" + },{ + "id": "006_05", + "name": "TPacker-minifier" + },{ + "id": "006_06", + "name": "Ant" + },{ + "id": "006_07", + "name": "Make" + },{ + "id": "006_08", + "name": "JSDoc" + },{ + "id": "006_09", + "name": "YUIDoc" + },{ + "id": "006_10", + "name": "LAMP" + }] + }, + {"id": "007", + "name": "前端框架/库", + "children": [{ + "id": "007_01", + "name": "jQuery" + },{ + "id": "007_02", + "name": "YUI2/YUI3" + },{ + "id": "007_03", + "name": "Prototype" + },{ + "id": "007_04", + "name": "Mootools" + },{ + "id": "007_05", + "name": "ExtJS" + },{ + "id": "007_06", + "name": "Smarty" + },{ + "id": "007_07", + "name": "Django" + },{ + "id": "007_08", + "name": "Zend" + },{ + "id": "007_09", + "name": "YUITest" + },{ + "id": "007_10", + "name": "Quint" + },{ + "id": "007_11", + "name": "Jasmine" + },{ + "id": "007_12", + "name": "前端测试" + },{ + "id": "007_13", + "name": "前端MVC" + }] + }, + {"id": "008", + "name": "浏览器兼容性", + "children": [{ + "id": "008_01", + "name": "IE6/7/8/9" + },{ + "id": "008_02", + "name": "Firfox" + },{ + "id": "008_03", + "name": "Chrome" + },{ + "id": "008_04", + "name": "Opera" + },{ + "id": "008_05", + "name": "Safari" + }] + }, + {"id": "009", + "name": "切页面", + "children": [{ + "id": "009_01", + "name": "HTML" + },{ + "id": "009_02", + "name": "CSS" + },{ + "id": "009_03", + "name": "PhotoShop" + }] + }, + {"id": "010", + "name": "编程语言", + "children": [{ + "id": "010_01", + "name": "JavaScript" + },{ + "id": "010_02", + "name": "PHP" + },{ + "id": "010_03", + "name": "Python" + },{ + "id": "010_04", + "name": "Perl" + },{ + "id": "010_05", + "name": "Python" + },{ + "id": "010_06", + "name": "Ruby" + }] + }, + {"id": "011", + "name": "调试工具", + "children": [{ + "id": "011_01", + "name": "Firebug" + },{ + "id": "011_02", + "name": "Firebug-lite" + },{ + "id": "011_03", + "name": "Web Inspector" + },{ + "id": "011_04", + "name": "YSlow" + },{ + "id": "011_05", + "name": "Smushi" + },{ + "id": "011_06", + "name": "IEDeveloperToolBar" + },{ + "id": "011_07", + "name": "IETester" + },{ + "id": "011_08", + "name": "SuperPreview" + },{ + "id": "011_09", + "name": "JsBeautifier" + },{ + "id": "011_10", + "name": "Fiddler" + },{ + "id": "011_11", + "name": "WireShark" + },{ + "id": "011_12", + "name": "tcpdump" + }] + }, + {"id": "012", + "name": "开发工具", + "children": [{ + "id": "012_01", + "name": "VIM" + },{ + "id": "012_02", + "name": "Aptana" + },{ + "id": "012_03", + "name": "Notepad++" + },{ + "id": "012_04", + "name": "EditPlus" + },{ + "id": "012_05", + "name": "Sublime Text" + },{ + "id": "012_06", + "name": "WebStorm" + },{ + "id": "012_07", + "name": "svn" + },{ + "id": "012_08", + "name": "git" + }] + }, + {"id": "013", + "name": "计算机知识储备", + "children": [{ + "id": "013_01", + "name": "编程原理" + },{ + "id": "013_02", + "name": "计算机网络" + },{ + "id": "013_03", + "name": "操作系统" + },{ + "id": "013_04", + "name": "算法原理" + },{ + "id": "013_05", + "name": "软件工程" + },{ + "id": "013_06", + "name": "软件测试原理" + }] + }, + {"id": "014", + "name": "前端标准/规范", + "children": [{ + "id": "014_01", + "name": "w3c" + },{ + "id": "014_02", + "name": "DOM/BOM" + },{ + "id": "014_03", + "name": "XHTML" + },{ + "id": "014_04", + "name": "XML" + },{ + "id": "014_05", + "name": "JSON" + },{ + "id": "014_06", + "name": "JONP" + },{ + "id": "014_07", + "name": "HTML5" + },{ + "id": "014_08", + "name": "CSS3" + },{ + "id": "014_09", + "name": "ECMAScript3" + },{ + "id": "014_10", + "name": "ECMAScript5" + },{ + "id": "014_11", + "name": "CommonJS" + },{ + "id": "014_12", + "name": "AMD" + },{ + "id": "014_13", + "name": "HTTP1.1" + }] + }, + {"id": "015", + "name": "性能", + "children": [{ + "id": "015_01", + "name": "WebPageTest" + },{ + "id": "015_02", + "name": "ShowSlow" + },{ + "id": "015_03", + "name": "YSlow" + },{ + "id": "015_04", + "name": "34Rule" + },{ + "id": "015_05", + "name": "PageSpeed" + },{ + "id": "015_06", + "name": "HttpWatch" + },{ + "id": "015_07", + "name": "DynaTrace's Ajax" + }] + }, + {"id": "016", + "name": "编程知识储备", + "children": [{ + "id": "016_01", + "name": "数据结构" + },{ + "id": "016_02", + "name": "MVC" + },{ + "id": "016_03", + "name": "面向对象" + },{ + "id": "016_04", + "name": "切面编程" + },{ + "id": "016_05", + "name": "函数式编程" + },{ + "id": "016_06", + "name": "JavaScript设计模式" + },{ + "id": "016_07", + "name": "JavaScript编程模式" + }] + }] + }; + //end + var infovis = document.getElementById('infovis'); + var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50; + + //init Hypertree + var ht = new $jit.Hypertree({ + //id of the visualization container + injectInto: 'infovis', + //canvas width and height + width: w, + height: h, + //Change node and edge styles such as + //color, width and dimensions. + Node: { + dim: 9, + color: "#f00" + }, + Edge: { + lineWidth: 2, + color: "#088" + }, + onBeforeCompute: function(node){ + Log.write("centering"); + }, + //Attach event handlers and add text to the + //labels. This method is only triggered on label + //creation + onCreateLabel: function(domElement, node){ + domElement.innerHTML = node.name; + $jit.util.addEvent(domElement, 'click', function () { + ht.onClick(node.id, { + onComplete: function() { + ht.controller.onComplete(); + } + }); + }); + }, + //Change node styles when labels are placed + //or moved. + onPlaceLabel: function(domElement, node){ + var style = domElement.style; + style.display = ''; + style.cursor = 'pointer'; + if (node._depth <= 1) { + style.fontSize = "0.8em"; + style.color = "#ddd"; + + } else if(node._depth == 2){ + style.fontSize = "0.7em"; + style.color = "#555"; + + } else { + style.display = 'none'; + } + + var left = parseInt(style.left); + var w = domElement.offsetWidth; + style.left = (left - w / 2) + 'px'; + }, + + onComplete: function(){ + Log.write("done"); + + //Build the right column relations list. + //This is done by collecting the information (stored in the data property) + //for all the nodes adjacent to the centered node. + var node = ht.graph.getClosestNodeToOrigin("current"); + var html = "

" + node.name + "

关系列表:"; + html += "
    "; + node.eachAdjacency(function(adj){ + var child = adj.nodeTo; + if (child.data) { + var rel = (child.data.band == node.name) ? child.data.relation : node.data.relation; + html += "
  • " + child.name + "
  • "; + } + }); + html += "
"; + $jit.id('inner-details').innerHTML = html; + } + }); + //load JSON data. + ht.loadJSON(json); + //compute positions and plot. + ht.refresh(); + //end + ht.controller.onComplete(); +} + +function toggleDuoshuoComments(container, id, url){ + if(jQuery(container).has("div").length>0){ + jQuery(container).empty(); + return; + } + var el = document.createElement('div'); + el.setAttribute('data-thread-key', id); + el.setAttribute('data-url', url); + DUOSHUO.EmbedThread(el); + jQuery(container).append(el); +} From 6f9f333cd8392e0f2672616fc71e82ccc14bf9fa Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Fri, 24 Oct 2014 19:04:45 +0800 Subject: [PATCH 064/107] Add generate script for json --- Makefile | 2 + README.md | 9 +- bin/generate.js | 85 + frontend_knowledge/f2e.json | 684 +++++ frontend_knowledge/index.html | 74 +- frontend_knowledge/js/jit.js | 4272 +++++++++++++++---------------- frontend_knowledge/js/script.js | 593 +---- 7 files changed, 3033 insertions(+), 2686 deletions(-) create mode 100644 Makefile create mode 100644 bin/generate.js create mode 100644 frontend_knowledge/f2e.json diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..d4030a5 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +all: + node ./bin/generate.js diff --git a/README.md b/README.md index 9aec671..67b5839 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,6 @@ Frontend Knowledge Structure 图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个GitHub项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 -尽管会变成文字的方式来维护这些内容,但是我承诺写一个小工具帮大家生成更好玩的图形(基于DataV项目)。 - ## 前端开发知识结构 - 前端工程师 - 浏览器 @@ -79,10 +77,10 @@ Frontend Knowledge Structure - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) - [Semantic Web](http://semanticweb.org/) - - [MicroData](http://schema.org) + - [MicroData](http://schema.org) - [RDFa](http://www.w3.org/TR/rdfa-core/) - [Web Accessibility](http://www.w3.org/TR/WAI-WEBCONTENT/) - - [Role Attribute](http://www.w3.org/TR/role-attribute/) + - [Role Attribute](http://www.w3.org/TR/role-attribute/) - [WAI-ARIA](http://www.w3.org/TR/wai-aria/) - 性能 - [JSPerf](http://jsperf.com/) @@ -164,6 +162,7 @@ Frontend Knowledge Structure - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) - WebGL(http://zh.wikipedia.org/wiki/WebGL):[Three.JS](http://threejs.org/) + - 后端工程师 - 编程语言 - C/C++/Java/PHP/Ruby/Python/... @@ -267,7 +266,7 @@ Frontend Knowledge Structure active : 53 days commits : 108 files : 4 - authors : + authors : 56 Jackson Tian 51.9% 9 吴晓兰 8.3% 5 liyinkan 4.6% diff --git a/bin/generate.js b/bin/generate.js new file mode 100644 index 0000000..96199bf --- /dev/null +++ b/bin/generate.js @@ -0,0 +1,85 @@ +var fs = require('fs'); +var path = require('path'); + +var readme = fs.readFileSync(path.join(__dirname, '../README.md'), 'utf8'); + +var getItems = function (str) { + var patt = /([ ]*)-(.*)/g; + var result; + + var list = []; + while ((result = patt.exec(str)) != null) { + list.push({level: result[1].length / 4, content: result[2].trim()}); + } + return list; +}; + +var filter = function (list) { + var j = 0; + var f2e = []; + for (var i = 0; i < list.length; i++) { + var item = list[i]; + if (item.level === 0) { + j = j + 1; + if (j === 2) { + break; + } + } + + f2e.push(item); + } + return f2e; +}; + +var format = function (list) { + var result = []; + for (var i = 0; i < list.length; i++) { + var item = list[i]; + var data = { + id: '' + i, + name: item.content, + level: item.level + }; + result.push(data); + } + return result; +}; + +var items = getItems(readme); +var f2e = filter(items); +var formated = format(f2e); + +var buildTree = function (list) { + var root = null; + for (var i = 0; i < list.length; i++) { + var item = list[i]; + if (root === null) { + root = item; + root.children = []; + } + + var lastLevel0 = root.children; + if (item.level === 1) { + delete item.level; + lastLevel0.push(item); + } + + if (item.level === 2) { + var lastLevel1 = lastLevel0[lastLevel0.length - 1]; + lastLevel1.children = lastLevel1.children || []; + lastLevel1.children.push(item); + } + + if (item.level === 3) { + var lastLevel1Child = lastLevel0[lastLevel0.length - 1].children; + var lastLevel2 = lastLevel1Child[lastLevel1Child.length - 1]; + lastLevel2.children = lastLevel2.children || []; + lastLevel2.children.push(item); + } + delete item.level; + } + return root; +}; + +var tree = buildTree(formated); +fs.writeFileSync(path.join(__dirname, '../frontend_knowledge/f2e.json'), JSON.stringify(tree, null, ' ')); diff --git a/frontend_knowledge/f2e.json b/frontend_knowledge/f2e.json new file mode 100644 index 0000000..8e3c016 --- /dev/null +++ b/frontend_knowledge/f2e.json @@ -0,0 +1,684 @@ +{ + "id": "0", + "name": "前端工程师", + "children": [ + { + "id": "1", + "name": "浏览器", + "children": [ + { + "id": "2", + "name": "IE6/[7](http://www.microsoft.com/en-US/download/details.aspx?id=2)/[8](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/en-US/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/en-US/internet-explorer/ie-11-worldwide-languages) (Trident)" + }, + { + "id": "3", + "name": "[Firefox](http://www.mozilla.org/en-US/) (Gecko)" + }, + { + "id": "4", + "name": "[Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) (Blink)" + }, + { + "id": "5", + "name": "[Safari](http://www.apple.com/safari/) (WebKit)" + }, + { + "id": "6", + "name": "[Opera](http://www.opera.com/) (Blink)" + } + ] + }, + { + "id": "7", + "name": "编程语言", + "children": [ + { + "id": "8", + "name": "[JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/)" + }, + { + "id": "9", + "name": "[CoffeeScript](http://coffeescript.org/)" + }, + { + "id": "10", + "name": "[TypeScript](http://www.typescriptlang.org/)" + } + ] + }, + { + "id": "11", + "name": "切页面", + "children": [ + { + "id": "12", + "name": "[HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/)" + }, + { + "id": "13", + "name": "[CSS/CSS3](http://www.w3.org/Style/CSS/)" + }, + { + "id": "14", + "name": "[PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/)" + } + ] + }, + { + "id": "15", + "name": "开发工具", + "children": [ + { + "id": "16", + "name": "编辑器和IDE", + "children": [ + { + "id": "17", + "name": "[VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/)" + }, + { + "id": "18", + "name": "[Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/)" + }, + { + "id": "19", + "name": "[WebStorm](http://www.jetbrains.com/webstorm/)" + }, + { + "id": "20", + "name": "[Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org)" + }, + { + "id": "21", + "name": "[Brackets](http://brackets.io)" + }, + { + "id": "22", + "name": "[Komodo IDE / Edit](http://www.activestate.com/komodo-edit)" + }, + { + "id": "23", + "name": "[Eclipse](http://www.eclipse.org/)" + }, + { + "id": "24", + "name": "[Visual Studio](http://www.visualstudio.com/)" + }, + { + "id": "25", + "name": "[NetBeans](https://netbeans.org/)" + }, + { + "id": "26", + "name": "[Cloud9 IDE](http://c9.io/)" + } + ] + }, + { + "id": "27", + "name": "调试工具", + "children": [ + { + "id": "28", + "name": "[Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/)" + }, + { + "id": "29", + "name": "[YSlow](http://developer.yahoo.com/yslow/)" + }, + { + "id": "30", + "name": "[IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage)" + }, + { + "id": "31", + "name": "[Fiddler](http://www.fiddler2.com/fiddler2/)" + }, + { + "id": "32", + "name": "[Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/)" + }, + { + "id": "33", + "name": "[Dragonfly](http://www.opera.com/dragonfly/)" + }, + { + "id": "34", + "name": "[DebugBar](http://www.debugbar.com/)" + }, + { + "id": "35", + "name": "[Venkman](https://developer.mozilla.org/en-US/docs/Venkman)" + } + ] + }, + { + "id": "36", + "name": "版本管理", + "children": [ + { + "id": "37", + "name": "[Git](git-scm.com/)/[SVN](http://subversion.apache.org/)/[Mercurial](http://mercurial.selenic.com/)" + }, + { + "id": "38", + "name": "[Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/)" + } + ] + } + ] + }, + { + "id": "39", + "name": "代码质量", + "children": [ + { + "id": "40", + "name": "Coding style", + "children": [ + { + "id": "41", + "name": "[JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs)" + }, + { + "id": "42", + "name": "[CSSLint](http://csslint.net/)" + }, + { + "id": "43", + "name": "[Markup Validation Service](http://validator.w3.org/)" + } + ] + }, + { + "id": "44", + "name": "单元测试", + "children": [ + { + "id": "45", + "name": "[QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/)" + }, + { + "id": "46", + "name": "[Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/)" + }, + { + "id": "47", + "name": "[Unit JS](http://unitjs.com/)" + } + ] + }, + { + "id": "48", + "name": "自动化测试", + "children": [ + { + "id": "49", + "name": "[WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/)" + }, + { + "id": "50", + "name": "[phantomjs](http://phantomjs.org/)" + } + ] + } + ] + }, + { + "id": "51", + "name": "前端库/框架", + "children": [ + { + "id": "52", + "name": "[jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/)" + }, + { + "id": "53", + "name": "[YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/)" + }, + { + "id": "54", + "name": "[Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/)" + }, + { + "id": "55", + "name": "[AngularJS](http://angularjs.org/)", + "children": [ + { + "id": "56", + "name": "[Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk)" + } + ] + }, + { + "id": "57", + "name": "[Bootstrap](http://getbootstrap.com/)" + }, + { + "id": "58", + "name": "[Semantic UI](http://www.semantic-ui.com/)" + }, + { + "id": "59", + "name": "[Juice UI](http://juiceui.com/)" + }, + { + "id": "60", + "name": "[Web Atoms](http://webatomsjs.neurospeech.com/)" + }, + { + "id": "61", + "name": "[Polymer](http://docs.polymerchina.org/)" + } + ] + }, + { + "id": "62", + "name": "前端标准/规范", + "children": [ + { + "id": "63", + "name": "[HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html)" + }, + { + "id": "64", + "name": "[ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm)" + }, + { + "id": "65", + "name": "[W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/)" + }, + { + "id": "66", + "name": "[CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)" + }, + { + "id": "67", + "name": "[HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html)" + }, + { + "id": "68", + "name": "[Semantic Web](http://semanticweb.org/)", + "children": [ + { + "id": "69", + "name": "[MicroData](http://schema.org)" + }, + { + "id": "70", + "name": "[RDFa](http://www.w3.org/TR/rdfa-core/)" + } + ] + }, + { + "id": "71", + "name": "[Web Accessibility](http://www.w3.org/TR/WAI-WEBCONTENT/)", + "children": [ + { + "id": "72", + "name": "[Role Attribute](http://www.w3.org/TR/role-attribute/)" + }, + { + "id": "73", + "name": "[WAI-ARIA](http://www.w3.org/TR/wai-aria/)" + } + ] + } + ] + }, + { + "id": "74", + "name": "性能", + "children": [ + { + "id": "75", + "name": "[JSPerf](http://jsperf.com/)" + }, + { + "id": "76", + "name": "[YSlow 35 rules](http://developer.yahoo.com/performance/rules.html)" + }, + { + "id": "77", + "name": "[PageSpeed](https://developers.google.com/speed/pagespeed/)" + }, + { + "id": "78", + "name": "[HTTPWatch](http://www.httpwatch.com/)" + }, + { + "id": "79", + "name": "[DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html)" + }, + { + "id": "80", + "name": "[高性能JavaScript](http://book.douban.com/subject/5362856/)" + } + ] + }, + { + "id": "81", + "name": "SEO" + }, + { + "id": "82", + "name": "编程知识储备", + "children": [ + { + "id": "83", + "name": "[数据结构](http://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84)" + }, + { + "id": "84", + "name": "OOP/AOP" + }, + { + "id": "85", + "name": "[原型链](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/作用域链" + }, + { + "id": "86", + "name": "[闭包](http://www.jibbering.com/faq/notes/closures/)" + }, + { + "id": "87", + "name": "[编程范型](http://zh.wikipedia.org/wiki/%E7%BC%96%E7%A8%8B%E8%8C%83%E5%9E%8B)" + }, + { + "id": "88", + "name": "[设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/)" + }, + { + "id": "89", + "name": "[Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html)" + } + ] + }, + { + "id": "90", + "name": "部署流程", + "children": [ + { + "id": "91", + "name": "压缩合并", + "children": [ + { + "id": "92", + "name": "[YUI Compressor](http://developer.yahoo.com/yui/compressor/)" + }, + { + "id": "93", + "name": "[Google Clousure Complier](https://developers.google.com/closure/compiler/)" + }, + { + "id": "94", + "name": "[UglifyJS](https://github.com/mishoo/UglifyJS)" + }, + { + "id": "95", + "name": "[CleanCSS](https://github.com/GoalSmashers/clean-css)" + } + ] + }, + { + "id": "96", + "name": "文档输出", + "children": [ + { + "id": "97", + "name": "[JSDoc](https://github.com/jsdoc3/jsdoc)" + }, + { + "id": "98", + "name": "[Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate)/[Grunt-Doxmate](https://github.com/luozhihua/grunt-doxmate)" + } + ] + }, + { + "id": "99", + "name": "项目构建工具", + "children": [ + { + "id": "100", + "name": "[make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/)" + }, + { + "id": "101", + "name": "[GYP](http://code.google.com/p/gyp/)" + }, + { + "id": "102", + "name": "[Grunt](http://gruntjs.com/)" + }, + { + "id": "103", + "name": "[Gulp](http://gulpjs.com/)" + }, + { + "id": "104", + "name": "[Yeoman](http://yeoman.io/)" + }, + { + "id": "105", + "name": "[FIS](http://fis.baidu.com/)" + }, + { + "id": "106", + "name": "[Mod](https://github.com/modulejs/modjs)" + } + ] + } + ] + }, + { + "id": "107", + "name": "代码组织", + "children": [ + { + "id": "108", + "name": "类库模块化", + "children": [ + { + "id": "109", + "name": "[CommonJS](http://www.commonjs.org/)/AMD" + }, + { + "id": "110", + "name": "[YUI3模块](http://yuilibrary.com/projects/yui3/)" + } + ] + }, + { + "id": "111", + "name": "业务逻辑模块化", + "children": [ + { + "id": "112", + "name": "[bower](https://github.com/twitter/bower)/[component](https://github.com/component/component)" + } + ] + }, + { + "id": "113", + "name": "文件加载", + "children": [ + { + "id": "114", + "name": "[LABjs](http://labjs.com/)" + }, + { + "id": "115", + "name": "[SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/)" + } + ] + }, + { + "id": "116", + "name": "模块化预处理器", + "children": [ + { + "id": "117", + "name": "[Browserify](https://github.com/substack/node-browserify)" + } + ] + } + ] + }, + { + "id": "118", + "name": "安全", + "children": [ + { + "id": "119", + "name": "[CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting)" + }, + { + "id": "120", + "name": "ADsafe/Caja/Sandbox" + } + ] + }, + { + "id": "121", + "name": "移动Web", + "children": [ + { + "id": "122", + "name": "HTML5/CSS3" + }, + { + "id": "123", + "name": "[响应式网页设计](http://zh.wikipedia.org/wiki/%E5%93%8D%E5%BA%94%E5%BC%8F%E7%BD%91%E9%A1%B5%E8%AE%BE%E8%AE%A1)" + }, + { + "id": "124", + "name": "[Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll)" + }, + { + "id": "125", + "name": "V5/[Sencha Touch](http://www.sencha.com/products/touch)" + }, + { + "id": "126", + "name": "[PhoneGap](http://phonegap.com/)" + }, + { + "id": "127", + "name": "[jQuery Mobile](http://jquerymobile.com/)" + } + ] + }, + { + "id": "128", + "name": "前沿技术社区/会议", + "children": [ + { + "id": "129", + "name": "[D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/)" + }, + { + "id": "130", + "name": "NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂](http://www.html5dw.com)" + }, + { + "id": "131", + "name": "[JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn)" + }, + { + "id": "132", + "name": "QCon/Velocity/SDCC" + }, + { + "id": "133", + "name": "[JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/)" + }, + { + "id": "134", + "name": "[CSSConf](http://cssconf.com/)" + }, + { + "id": "135", + "name": "YDN/YUIConf" + }, + { + "id": "136", + "name": "HybridApp" + }, + { + "id": "137", + "name": "[WHATWG](http://whatwg.org/)" + } + ] + }, + { + "id": "138", + "name": "计算机知识储备", + "children": [ + { + "id": "139", + "name": "编译原理" + }, + { + "id": "140", + "name": "[计算机网络](http://zh.wikipedia.org/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C)" + }, + { + "id": "141", + "name": "[操作系统](http://zh.wikipedia.org/wiki/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F)" + }, + { + "id": "142", + "name": "算法原理" + }, + { + "id": "143", + "name": "软件工程/软件测试原理" + } + ] + }, + { + "id": "144", + "name": "软技能", + "children": [ + { + "id": "145", + "name": "知识管理/总结分享" + }, + { + "id": "146", + "name": "沟通技巧/团队协作" + }, + { + "id": "147", + "name": "需求管理/PM" + }, + { + "id": "148", + "name": "交互设计/可用性/可访问性知识" + } + ] + }, + { + "id": "149", + "name": "可视化", + "children": [ + { + "id": "150", + "name": "SVG/Canvas/VML" + }, + { + "id": "151", + "name": "SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/)" + }, + { + "id": "152", + "name": "Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/)" + }, + { + "id": "153", + "name": "WebGL(http://zh.wikipedia.org/wiki/WebGL):[Three.JS](http://threejs.org/)" + } + ] + } + ] +} \ No newline at end of file diff --git a/frontend_knowledge/index.html b/frontend_knowledge/index.html index 3f98a57..27d9e51 100644 --- a/frontend_knowledge/index.html +++ b/frontend_knowledge/index.html @@ -1,7 +1,7 @@ - + - + 前端知识结构图 @@ -9,45 +9,45 @@ - + - + -
-
-
-

- 前端知识结构图 -

- 这是一个前端知识结构图。

- 点击一个节点,可以将这个节点移动到中央查看。

- 此外中央节点的关系也可以从右侧的列表中查看。

- -

- 项目来源 -
-
-
-
-
-
-
-
-
-
-
- - - - - - - +
+
+
+

+ 前端知识结构图 +

+ 这是一个前端知识结构图。

+ 点击一个节点,可以将这个节点移动到中央查看。

+ 此外中央节点的关系也可以从右侧的列表中查看。

+ +

+ 项目来源 +
+
+
+
+
+
+
+
+
+
+
+ + + + + + + diff --git a/frontend_knowledge/js/jit.js b/frontend_knowledge/js/jit.js index 9bf6e9e..f144bcc 100644 --- a/frontend_knowledge/js/jit.js +++ b/frontend_knowledge/js/jit.js @@ -20,7 +20,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - (function () { + (function () { /* File: Core.js @@ -29,9 +29,9 @@ THE SOFTWARE. /* Object: $jit - - Defines the namespace for all library Classes and Objects. - This variable is the *only* global variable defined in the Toolkit. + + Defines the namespace for all library Classes and Objects. + This variable is the *only* global variable defined in the Toolkit. There are also other interesting properties attached to this variable described below. */ window.$jit = function(w) { @@ -46,9 +46,9 @@ window.$jit = function(w) { $jit.version = '2.0.1'; /* Object: $jit.id - + Works just like *document.getElementById* - + Example: (start code js) var element = $jit.id('elementId'); @@ -58,17 +58,17 @@ $jit.version = '2.0.1'; /* Object: $jit.util - + Contains utility functions. - - Some of the utility functions and the Class system were based in the MooTools Framework - . Copyright (c) 2006-2010 Valerio Proietti, . + + Some of the utility functions and the Class system were based in the MooTools Framework + . Copyright (c) 2006-2010 Valerio Proietti, . MIT license . - + These methods are generally also implemented in DOM manipulation frameworks like JQuery, MooTools and Prototype. - I'd suggest you to use the functions from those libraries instead of using these, since their functions + I'd suggest you to use the functions from those libraries instead of using these, since their functions are widely used and tested in many different platforms/browsers. Use these functions only if you have to. - + */ var $ = function(d) { return document.getElementById(d); @@ -79,14 +79,14 @@ $.empty = function() { /* Method: extend - + Augment an object by appending another object's properties. - + Parameters: - + original - (object) The object to be extended. extended - (object) An object which properties are going to be appended to the original object. - + Example: (start code js) $jit.util.extend({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 4 }); //{ 'a':1, 'b': 3, 'c': 4 } @@ -110,13 +110,13 @@ $.time = Date.now || function() { /* Method: splat - + Returns an array wrapping *obj* if *obj* is not an array. Returns *obj* otherwise. - + Parameters: - + obj - (mixed) The object to be wrapped in an array. - + Example: (start code js) $jit.util.splat(3); //[3] @@ -138,14 +138,14 @@ $.type.s = Object.prototype.toString; /* Method: each - + Iterates through an iterable applying *f*. - + Parameters: - + iterable - (array) The original array. fn - (function) The function to apply to the array elements. - + Example: (start code js) $jit.util.each([3, 4, 5], function(n) { alert('number ' + n); }); @@ -172,14 +172,14 @@ $.indexOf = function(array, item) { /* Method: map - + Maps or collects an array by applying *f*. - + Parameters: - + array - (array) The original array. f - (function) The function to apply to the array elements. - + Example: (start code js) $jit.util.map([3, 4, 5], function(n) { return n*n; }); //[9, 16, 25] @@ -195,15 +195,15 @@ $.map = function(array, f) { /* Method: reduce - + Iteratively applies the binary function *f* storing the result in an accumulator. - + Parameters: - + array - (array) The original array. f - (function) The function to apply to the array elements. opt - (optional|mixed) The starting value for the acumulator. - + Example: (start code js) $jit.util.reduce([3, 4, 5], function(x, y) { return x + y; }, 0); //12 @@ -221,13 +221,13 @@ $.reduce = function(array, f, opt) { /* Method: merge - + Merges n-objects and their sub-objects creating a new, fresh object. - + Parameters: - + An arbitrary number of objects. - + Example: (start code js) $jit.util.merge({ 'a': 1, 'b': 2 }, { 'b': 3, 'c': 4 }); //{ 'a':1, 'b': 3, 'c': 4 } @@ -280,13 +280,13 @@ $.zip = function() { /* Method: rgbToHex - + Converts an RGB array into a Hex string. - + Parameters: - + srcArray - (array) An array with R, G and B values - + Example: (start code js) $jit.util.rgbToHex([255, 255, 255]); //'#ffffff' @@ -307,13 +307,13 @@ $.rgbToHex = function(srcArray, array) { /* Method: hexToRgb - + Converts an Hex color string into an RGB array. - + Parameters: - + hex - (string) A color hex string. - + Example: (start code js) $jit.util.hexToRgb('#fff'); //[255, 255, 255] @@ -355,15 +355,15 @@ $.clean = function(elem) { /* Method: addEvent - + Cross-browser add event listener. - + Parameters: - + obj - (obj) The Element to attach the listener to. type - (string) The listener type. For example 'click', or 'mousemove'. fn - (function) The callback function to be used when the event is fired. - + Example: (start code js) $jit.util.addEvent(elem, 'click', function(){ alert('hello'); }); @@ -568,19 +568,19 @@ $jit.Class = Class; /* Object: $jit.json - + Provides JSON utility functions. - + Most of these functions are JSON-tree traversal and manipulation functions. */ $jit.json = { /* Method: prune - + Clears all tree nodes having depth greater than maxLevel. - + Parameters: - + tree - (object) A JSON tree object. For more information please see . maxLevel - (number) An integer specifying the maximum level allowed for this tree. All nodes having depth greater than max level will be deleted. @@ -595,18 +595,18 @@ $jit.json = { }, /* Method: getParent - + Returns the parent node of the node having _id_ as id. - + Parameters: - + tree - (object) A JSON tree object. See also . id - (string) The _id_ of the child node whose parent will be returned. Returns: A tree JSON node if any, or false otherwise. - + */ getParent: function(tree, id) { if (tree.id == id) @@ -627,16 +627,16 @@ $jit.json = { }, /* Method: getSubtree - + Returns the subtree that matches the given id. - + Parameters: - + tree - (object) A JSON tree object. See also . id - (string) A node *unique* identifier. - + Returns: - + A subtree having a root node matching the given id. Returns null if no subtree matching the id is found. */ @@ -652,16 +652,16 @@ $jit.json = { }, /* Method: eachLevel - + Iterates on tree nodes with relative depth less or equal than a specified level. - + Parameters: - + tree - (object) A JSON tree or subtree. See also . initLevel - (number) An integer specifying the initial relative level. Usually zero. toLevel - (number) An integer specifying a top level. This method will iterate only through nodes with depth less than or equal this number. action - (function) A function that receives a node and an integer specifying the actual level of the node. - + Example: (start code js) $jit.json.eachLevel(tree, 0, 3, function(node, depth) { @@ -680,11 +680,11 @@ $jit.json = { }, /* Method: each - + A JSON tree iterator. - + Parameters: - + tree - (object) A JSON tree or subtree. See also . action - (function) A function that receives a node. @@ -694,7 +694,7 @@ $jit.json = { alert(node.name); }); (end code) - + */ each: function(tree, action) { this.eachLevel(tree, 0, Number.MAX_VALUE, action); @@ -703,12 +703,12 @@ $jit.json = { /* - An object containing multiple type of transformations. + An object containing multiple type of transformations. */ $jit.Trans = { $extend: true, - + linear: function(p){ return p; } @@ -799,9 +799,9 @@ var Trans = $jit.Trans; Used by: - + Based on: - + The Animation class is based in the MooTools Framework . Copyright (c) 2006-2009 Valerio Proietti, . MIT license . */ @@ -893,7 +893,7 @@ var Options = function() { if(opt.$extend) { $.extend(ans, opt); } else { - ans[args[i]] = opt; + ans[args[i]] = opt; } } return ans; @@ -906,12 +906,12 @@ var Options = function() { /* Object: Options.AreaChart - - options. + + options. Other options included in the AreaChart are , , , and . - + Syntax: - + (start code js) Options.AreaChart = { @@ -924,11 +924,11 @@ var Options = function() { filterOnClick: false, restoreOnRightClick: false }; - + (end code) - + Example: - + (start code js) var areaChart = new $jit.AreaChart({ @@ -938,11 +938,11 @@ var Options = function() { filterOnClick: true, restoreOnRightClick: true }); - + (end code) Parameters: - + animate - (boolean) Default's *true*. Whether to add animated transitions when filtering/restoring stacks. labelOffset - (number) Default's *3*. Adds margin between the label and the default place where it should be drawn. type - (string) Default's *'stacked'*. Stack style. Posible values are 'stacked', 'stacked:gradient' to add gradients. @@ -951,9 +951,9 @@ var Options = function() { showLabels - (boolean, function) Default's *true*. Display the name of the slots. Can also be a function that returns *true* or *false* to display or not each label. filterOnClick - (boolean) Default's *true*. Select the clicked stack by hiding all other stacks. restoreOnRightClick - (boolean) Default's *true*. Show all stacks by right clicking. - + */ - + Options.AreaChart = { $extend: true, @@ -983,11 +983,11 @@ Options.AreaChart = { /* Object: Options.Margin - - Canvas drawing margins. - + + Canvas drawing margins. + Syntax: - + (start code js) Options.Margin = { @@ -996,11 +996,11 @@ Options.AreaChart = { right: 0, bottom: 0 }; - + (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ @@ -1009,21 +1009,21 @@ Options.AreaChart = { bottom: 20 } }); - + (end code) Parameters: - + top - (number) Default's *0*. Top margin. left - (number) Default's *0*. Left margin. right - (number) Default's *0*. Right margin. bottom - (number) Default's *0*. Bottom margin. - + */ Options.Margin = { $extend: false, - + top: 0, left: 0, right: 0, @@ -1037,12 +1037,12 @@ Options.Margin = { /* Object: Options.Canvas - - These are Canvas general options, like where to append it in the DOM, its dimensions, background, + + These are Canvas general options, like where to append it in the DOM, its dimensions, background, and other more advanced options. - + Syntax: - + (start code js) Options.Canvas = { @@ -1053,11 +1053,11 @@ Options.Margin = { useCanvas: false, withLabels: true, background: false - }; + }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ injectInto: 'someContainerId', @@ -1065,9 +1065,9 @@ Options.Margin = { height: 700 }); (end code) - + Parameters: - + injectInto - *required* (string|element) The id of the DOM container for the visualization. It can also be an Element provided that it has an id. type - (string) Context type. Default's 2D but can be 3D for webGL enabled browsers. width - (number) Default's to the *container's offsetWidth*. The width of the canvas. @@ -1079,7 +1079,7 @@ Options.Margin = { Options.Canvas = { $extend: true, - + injectInto: 'id', type: '2D', width: false, @@ -1087,7 +1087,7 @@ Options.Canvas = { useCanvas: false, withLabels: true, background: false, - + Scene: { Lighting: { enable: false, @@ -1107,11 +1107,11 @@ Options.Canvas = { /* Object: Options.Tree - + Options related to (strict) Tree layout algorithms. These options are used by the visualization. - + Syntax: - + (start code js) Options.Tree = { orientation: "left", @@ -1122,9 +1122,9 @@ Options.Canvas = { align:"center" }; (end code) - + Example: - + (start code js) var st = new $jit.ST({ orientation: 'left', @@ -1135,18 +1135,18 @@ Options.Canvas = { (end code) Parameters: - + subtreeOffset - (number) Default's 8. Separation offset between subtrees. siblingOffset - (number) Default's 5. Separation offset between siblings. orientation - (string) Default's 'left'. Tree orientation layout. Possible values are 'left', 'top', 'right', 'bottom'. align - (string) Default's *center*. Whether the tree alignment is 'left', 'center' or 'right'. indent - (number) Default's 10. Used when *align* is left or right and shows an indentation between parent and children. multitree - (boolean) Default's *false*. Used with the node $orn data property for creating multitrees. - + */ Options.Tree = { $extend: true, - + orientation: "left", subtreeOffset: 8, siblingOffset: 5, @@ -1167,7 +1167,7 @@ Options.Tree = { Provides Node rendering options for Tree and Graph based visualizations. Syntax: - + (start code js) Options.Node = { overridable: false, @@ -1187,9 +1187,9 @@ Options.Tree = { CanvasStyles: {} }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ Node: { @@ -1200,7 +1200,7 @@ Options.Tree = { } }); (end code) - + Parameters: overridable - (boolean) Default's *false*. Determine whether or not general node properties can be overridden by a particular . @@ -1222,7 +1222,7 @@ Options.Tree = { */ Options.Node = { $extend: false, - + overridable: false, type: 'circle', color: '#ccb', @@ -1255,7 +1255,7 @@ Options.Node = { Provides Edge rendering options for Tree and Graph based visualizations. Syntax: - + (start code js) Options.Edge = { overridable: false, @@ -1267,9 +1267,9 @@ Options.Node = { CanvasStyles: {} }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ Edge: { @@ -1283,9 +1283,9 @@ Options.Node = { } }); (end code) - + Parameters: - + overridable - (boolean) Default's *false*. Determine whether or not general edges properties can be overridden by a particular . type - (string) Default's 'line'. Edge styles include 'line', 'hyperline', 'arrow'. The default Edge type might vary in each visualization. You can also implement custom Edge types. color - (string) Default's '#ccb'. Edge color. @@ -1296,12 +1296,12 @@ Options.Node = { CanvasStyles - (object) Default's an empty object (i.e. {}). Attach any other canvas specific property that you'd set to the canvas context before plotting an Edge. See also: - + If you want to know more about how to customize Node/Edge data per element, in the JSON or programmatically, take a look at this article. */ Options.Edge = { $extend: false, - + overridable: false, type: 'line', color: '#ccb', @@ -1325,10 +1325,10 @@ Options.Edge = { /* Object: Options.Fx - Provides animation options like duration of the animations, frames per second and animation transitions. + Provides animation options like duration of the animations, frames per second and animation transitions. Syntax: - + (start code js) Options.Fx = { fps:40, @@ -1337,9 +1337,9 @@ Options.Edge = { clearCanvas: true }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ duration: 1000, @@ -1347,16 +1347,16 @@ Options.Edge = { transition: $jit.Trans.linear }); (end code) - + Parameters: - + clearCanvas - (boolean) Default's *true*. Whether to clear the frame/canvas when the viz is plotted or animated. duration - (number) Default's *2500*. Duration of the animation in milliseconds. fps - (number) Default's *40*. Frames per second. transition - (object) Default's *$jit.Trans.Quart.easeInOut*. The transition used for the animations. See below for a more detailed explanation. - + Object: $jit.Trans - + This object is used for specifying different animation transitions in all visualizations. There are many different type of animation transitions. @@ -1366,7 +1366,7 @@ Options.Edge = { Displays a linear transition >Trans.linear - + (see Linear.png) Quad: @@ -1376,7 +1376,7 @@ Options.Edge = { >Trans.Quad.easeIn >Trans.Quad.easeOut >Trans.Quad.easeInOut - + (see Quad.png) Cubic: @@ -1466,16 +1466,16 @@ Options.Edge = { >Trans.Elastic.easeInOut (see Elastic.png) - + Based on: - + Easing and Transition animation methods are based in the MooTools Framework . Copyright (c) 2006-2010 Valerio Proietti, . MIT license . */ Options.Fx = { $extend: true, - + fps:40, duration: 2500, transition: $jit.Trans.Quart.easeInOut, @@ -1489,10 +1489,10 @@ Options.Fx = { /* Object: Options.Label - Provides styling for Labels such as font size, family, etc. Also sets Node labels as HTML, SVG or Native canvas elements. + Provides styling for Labels such as font size, family, etc. Also sets Node labels as HTML, SVG or Native canvas elements. Syntax: - + (start code js) Options.Label = { overridable: false, @@ -1505,9 +1505,9 @@ Options.Fx = { color: '#fff' }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ Label: { @@ -1517,9 +1517,9 @@ Options.Fx = { } }); (end code) - + Parameters: - + overridable - (boolean) Default's *false*. Determine whether or not general label properties can be overridden by a particular . type - (string) Default's *HTML*. The type for the labels. Can be 'HTML', 'SVG' or 'Native' canvas labels. style - (string) Default's *empty string*. Can be 'italic' or 'bold'. This parameter is only taken into account when using 'Native' canvas labels. For DOM based labels the className *node* is added to the DOM element for styling via CSS. You can also use methods to style individual labels. @@ -1529,7 +1529,7 @@ Options.Fx = { */ Options.Label = { $extend: false, - + overridable: false, type: 'HTML', //'SVG', 'Native' style: ' ', @@ -1548,11 +1548,11 @@ Options.Label = { /* Object: Options.Tips - + Tips options - + Syntax: - + (start code js) Options.Tips = { enable: false, @@ -1563,9 +1563,9 @@ Options.Label = { onHide: $.empty }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ Tips: { @@ -1582,7 +1582,7 @@ Options.Label = { Parameters: - enable - (boolean) Default's *false*. If *true*, a tooltip will be shown when a node is hovered. The tooltip is a div DOM element having "tip" as CSS class. + enable - (boolean) Default's *false*. If *true*, a tooltip will be shown when a node is hovered. The tooltip is a div DOM element having "tip" as CSS class. type - (string) Default's *auto*. Defines where to attach the MouseEnter/Leave tooltip events. Possible values are 'Native' to attach them to the canvas or 'HTML' to attach them to DOM label elements (if defined). 'auto' sets this property to the value of 's *type* property. offsetX - (number) Default's *20*. An offset added to the current tooltip x-position (which is the same as the current mouse position). Default's 20. offsetY - (number) Default's *20*. An offset added to the current tooltip y-position (which is the same as the current mouse position). Default's 20. @@ -1592,7 +1592,7 @@ Options.Label = { */ Options.Tips = { $extend: false, - + enable: false, type: 'auto', offsetX: 20, @@ -1610,11 +1610,11 @@ Options.Tips = { /* Object: Options.NodeStyles - + Apply different styles when a node is hovered or selected. - + Syntax: - + (start code js) Options.NodeStyles = { enable: false, @@ -1623,9 +1623,9 @@ Options.Tips = { stylesClick: false }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ NodeStyles: { @@ -1641,7 +1641,7 @@ Options.Tips = { (end code) Parameters: - + enable - (boolean) Default's *false*. Whether to enable this option. type - (string) Default's *auto*. Use this to attach the hover/click events in the nodes or the nodes labels (if they have been defined as DOM elements: 'HTML' or 'SVG', see for more details). The default 'auto' value will set NodeStyles to the same type defined for . stylesHover - (boolean|object) Default's *false*. An object with node styles just like the ones defined for or *false* otherwise. @@ -1650,7 +1650,7 @@ Options.Tips = { Options.NodeStyles = { $extend: false, - + enable: false, type: 'auto', stylesHover: false, @@ -1665,11 +1665,11 @@ Options.NodeStyles = { /* Object: Options.Events - + Configuration for adding mouse/touch event handlers to Nodes. - + Syntax: - + (start code js) Options.Events = { enable: false, @@ -1691,9 +1691,9 @@ Options.NodeStyles = { onMouseWheel: $.empty }; (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ Events: { @@ -1710,31 +1710,31 @@ Options.NodeStyles = { } }); (end code) - + Parameters: - + enable - (boolean) Default's *false*. Whether to enable the Event system. enableForEdges - (boolean) Default's *false*. Whether to track events also in arcs. If *true* the same callbacks -described below- are used for nodes *and* edges. A simple duck type check for edges is to check for *node.nodeFrom*. type - (string) Default's 'auto'. Whether to attach the events onto the HTML labels (via event delegation) or to use the custom 'Native' canvas Event System of the library. 'auto' is set when you let the *type* parameter decide this. - onClick(node, eventInfo, e) - Triggered when a user performs a click in the canvas. *node* is the clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onRightClick(node, eventInfo, e) - Triggered when a user performs a right click in the canvas. *node* is the right clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onClick(node, eventInfo, e) - Triggered when a user performs a click in the canvas. *node* is the clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onRightClick(node, eventInfo, e) - Triggered when a user performs a right click in the canvas. *node* is the right clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onMouseMove(node, eventInfo, e) - Triggered when the user moves the mouse. *node* is the under the cursor as it's moving over the canvas or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onMouseEnter(node, eventInfo, e) - Triggered when a user moves the mouse over a node. *node* is the that the mouse just entered. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onMouseLeave(node, eventInfo, e) - Triggered when the user mouse-outs a node. *node* is the 'mouse-outed'. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onDragStart(node, eventInfo, e) - Triggered when the user mouse-downs over a node. *node* is the being pressed. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onDragMove(node, eventInfo, e) - Triggered when a user, after pressing the mouse button over a node, moves the mouse around. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onDragEnd(node, eventInfo, e) - Triggered when a user finished dragging a node. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onDragCancel(node, eventInfo, e) - Triggered when the user releases the mouse button over a that wasn't dragged (i.e. the user didn't perform any mouse movement after pressing the mouse button). *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. - onTouchStart(node, eventInfo, e) - Behaves just like onDragStart. - onTouchMove(node, eventInfo, e) - Behaves just like onDragMove. - onTouchEnd(node, eventInfo, e) - Behaves just like onDragEnd. + onMouseEnter(node, eventInfo, e) - Triggered when a user moves the mouse over a node. *node* is the that the mouse just entered. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onMouseLeave(node, eventInfo, e) - Triggered when the user mouse-outs a node. *node* is the 'mouse-outed'. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragStart(node, eventInfo, e) - Triggered when the user mouse-downs over a node. *node* is the being pressed. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragMove(node, eventInfo, e) - Triggered when a user, after pressing the mouse button over a node, moves the mouse around. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragEnd(node, eventInfo, e) - Triggered when a user finished dragging a node. *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onDragCancel(node, eventInfo, e) - Triggered when the user releases the mouse button over a that wasn't dragged (i.e. the user didn't perform any mouse movement after pressing the mouse button). *node* is the being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. + onTouchStart(node, eventInfo, e) - Behaves just like onDragStart. + onTouchMove(node, eventInfo, e) - Behaves just like onDragMove. + onTouchEnd(node, eventInfo, e) - Behaves just like onDragEnd. onTouchCancel(node, eventInfo, e) - Behaves just like onDragCancel. onMouseWheel(delta, e) - Triggered when the user uses the mouse scroll over the canvas. *delta* is 1 or -1 depending on the sense of the mouse scroll. */ Options.Events = { $extend: false, - + enable: false, enableForEdges: false, type: 'auto', @@ -1760,12 +1760,12 @@ Options.Events = { /* Object: Options.Navigation - - Panning and zooming options for Graph/Tree based visualizations. These options are implemented + + Panning and zooming options for Graph/Tree based visualizations. These options are implemented by all visualizations except charts (, and ). - + Syntax: - + (start code js) Options.Navigation = { @@ -1774,11 +1774,11 @@ Options.Events = { panning: false, //true, 'avoid nodes' zooming: false }; - + (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ Navigation: { @@ -1788,19 +1788,19 @@ Options.Events = { } }); (end code) - + Parameters: - + enable - (boolean) Default's *false*. Whether to enable Navigation capabilities. type - (string) Default's 'auto'. Whether to attach the navigation events onto the HTML labels (via event delegation) or to use the custom 'Native' canvas Event System of the library. When 'auto' set when you let the *type* parameter decide this. panning - (boolean|string) Default's *false*. Set this property to *true* if you want to add Drag and Drop panning support to the visualization. You can also set this parameter to 'avoid nodes' to enable DnD panning but disable it if the DnD is taking place over a node. This is useful when some other events like Drag & Drop for nodes are added to . zooming - (boolean|number) Default's *false*. Set this property to a numeric value to turn mouse-scroll zooming on. The number will be proportional to the mouse-scroll sensitivity. - + */ Options.Navigation = { $extend: false, - + enable: false, type: 'auto', panning: false, //true | 'avoid nodes' @@ -1814,16 +1814,16 @@ Options.Navigation = { /* Object: Options.Controller - - Provides controller methods. Controller methods are callback functions that get called at different stages + + Provides controller methods. Controller methods are callback functions that get called at different stages of the animation, computing or plotting of the visualization. - + Implemented by: - + All visualizations except charts (, and ). - + Syntax: - + (start code js) Options.Controller = { @@ -1838,11 +1838,11 @@ Options.Navigation = { onAfterPlotNode: $.empty, request: false }; - + (end code) - + Example: - + (start code js) var viz = new $jit.Viz({ onBeforePlotNode: function(node) { @@ -1864,7 +1864,7 @@ Options.Navigation = { } }); (end code) - + Parameters: onBeforeCompute(node) - This method is called right before performing all computations and animations. The selected is passed as parameter. @@ -1877,13 +1877,13 @@ Options.Navigation = { onAfterPlotLine(adj) - This method is triggered right after plotting a . *Used in , and visualizations* - - request(nodeId, level, onComplete) - This method is used for buffering information into the visualization. When clicking on an empty node, the visualization will make a request for this node's subtrees, specifying a given level for this subtree (defined by _levelsToShow_). Once the request is completed, the onComplete callback should be called with the given result. This is useful to provide on-demand information into the visualizations withought having to load the entire information from start. The parameters used by this method are _nodeId_, which is the id of the root of the subtree to request, _level_ which is the depth of the subtree to be requested (0 would mean just the root node). _onComplete_ is an object having the callback method _onComplete.onComplete(json)_ that should be called once the json has been retrieved. - + + request(nodeId, level, onComplete) - This method is used for buffering information into the visualization. When clicking on an empty node, the visualization will make a request for this node's subtrees, specifying a given level for this subtree (defined by _levelsToShow_). Once the request is completed, the onComplete callback should be called with the given result. This is useful to provide on-demand information into the visualizations withought having to load the entire information from start. The parameters used by this method are _nodeId_, which is the id of the root of the subtree to request, _level_ which is the depth of the subtree to be requested (0 would mean just the root node). _onComplete_ is an object having the callback method _onComplete.onComplete(json)_ that should be called once the json has been retrieved. + */ Options.Controller = { $extend: true, - + onBeforeCompute: $.empty, onAfterCompute: $.empty, onCreateLabel: $.empty, @@ -1899,23 +1899,23 @@ Options.Controller = { /* * File: Extras.js - * + * * Provides Extras such as Tips and Style Effects. - * + * * Description: - * + * * Provides the and classes and functions. * */ /* * Manager for mouse events (clicking and mouse moving). - * + * * This class is used for registering objects implementing onClick * and onMousemove methods. These methods are called when clicking or * moving the mouse around the Canvas. * For now, and are classes implementing these methods. - * + * */ var ExtrasInitializer = { initialize: function(className, viz) { @@ -1939,7 +1939,7 @@ var ExtrasInitializer = { target = e.target || e.srcElement, related = e.relatedTarget; if(group) { - return related && related == this.viz.canvas.getCtx().canvas + return related && related == this.viz.canvas.getCtx().canvas && !!target && this.isDescendantOf(target, labelContainer); } else { return this.isDescendantOf(target, labelContainer); @@ -1977,21 +1977,21 @@ var MouseEventsManager = new Class({ this.registeredObjects = []; this.attachEvents(); }, - + attachEvents: function() { - var htmlCanvas = this.canvas.getElement(), + var htmlCanvas = this.canvas.getElement(), that = this; htmlCanvas.oncontextmenu = $.lambda(false); $.addEvents(htmlCanvas, { 'mouseup': function(e, win) { var event = $.event.get(e, win); - that.handleEvent('MouseUp', e, win, - that.makeEventObject(e, win), + that.handleEvent('MouseUp', e, win, + that.makeEventObject(e, win), $.event.isRightClick(event)); }, 'mousedown': function(e, win) { var event = $.event.get(e, win); - that.handleEvent('MouseDown', e, win, that.makeEventObject(e, win), + that.handleEvent('MouseDown', e, win, that.makeEventObject(e, win), $.event.isRightClick(event)); }, 'mousemove': function(e, win) { @@ -2026,11 +2026,11 @@ var MouseEventsManager = new Class({ htmlCanvas.addEventListener('DOMMouseScroll', handleMouseWheel, false); } }, - + register: function(obj) { this.registeredObjects.push(obj); }, - + handleEvent: function() { var args = Array.prototype.slice.call(arguments), type = args.shift(); @@ -2038,7 +2038,7 @@ var MouseEventsManager = new Class({ regs[i]['on' + type].apply(regs[i], args); } }, - + makeEventObject: function(e, win) { var that = this, graph = this.viz.graph, @@ -2112,8 +2112,8 @@ var MouseEventsManager = new Class({ } }); -/* - * Provides the initialization function for and implemented +/* + * Provides the initialization function for and implemented * by all main visualizations. * */ @@ -2129,36 +2129,36 @@ var Extras = { that[k.toLowerCase()] = obj; } }); - } + } }; Extras.Classes = {}; /* Class: Events - + This class defines an Event API to be accessed by the user. The methods implemented are the ones defined in the object. */ Extras.Classes.Events = new Class({ Implements: [ExtrasInitializer, EventsInterface], - + initializePost: function() { this.fx = this.viz.fx; this.ntypes = this.viz.fx.nodeTypes; this.etypes = this.viz.fx.edgeTypes; - + this.hovered = false; this.pressed = false; this.touched = false; this.touchMoved = false; this.moved = false; - + }, - + setAsProperty: $.lambda(true), - + onMouseUp: function(e, win, event, isRightClick) { var evt = $.event.get(e, win); if(!this.moved) { @@ -2200,7 +2200,7 @@ Extras.Classes.Events = new Class({ this.hovered = false; } }, - + onMouseOver: function(e, win, event) { //mouseover a label var evt = $.event.get(e, win), label; @@ -2210,7 +2210,7 @@ Extras.Classes.Events = new Class({ event, evt); } }, - + onMouseMove: function(e, win, event) { var label, evt = $.event.get(e, win); if(this.pressed) { @@ -2225,7 +2225,7 @@ Extras.Classes.Events = new Class({ if(this.hovered) { var hn = this.hovered; var geom = hn.nodeFrom? this.etypes[hn.getData('type')] : this.ntypes[hn.getData('type')]; - var contains = geom && geom.contains + var contains = geom && geom.contains && geom.contains.call(this.fx, hn, event.getPos()); if(contains) { this.config.onMouseMove(hn, event, evt); @@ -2242,11 +2242,11 @@ Extras.Classes.Events = new Class({ } } }, - + onMouseWheel: function(e, win, delta) { this.config.onMouseWheel(delta, $.event.get(e, win)); }, - + onMouseDown: function(e, win, event) { var evt = $.event.get(e, win), label; if(this.dom) { @@ -2258,7 +2258,7 @@ Extras.Classes.Events = new Class({ } this.pressed && this.config.onDragStart(this.pressed, event, evt); }, - + onTouchStart: function(e, win, event) { var evt = $.event.get(e, win), label; if(this.dom && (label = this.isLabel(e, win))) { @@ -2268,7 +2268,7 @@ Extras.Classes.Events = new Class({ } this.touched && this.config.onTouchStart(this.touched, event, evt); }, - + onTouchMove: function(e, win, event) { var evt = $.event.get(e, win); if(this.touched) { @@ -2276,7 +2276,7 @@ Extras.Classes.Events = new Class({ this.config.onTouchMove(this.touched, event, evt); } }, - + onTouchEnd: function(e, win, event) { var evt = $.event.get(e, win); if(this.touched) { @@ -2292,21 +2292,21 @@ Extras.Classes.Events = new Class({ /* Class: Tips - + A class containing tip related functions. This class is used internally. - + Used by: - + , , , , , , - + See also: - + */ Extras.Classes.Tips = new Class({ Implements: [ExtrasInitializer, EventsInterface], - + initializePost: function() { //add DOM tooltip if(document.body) { @@ -2323,9 +2323,9 @@ Extras.Classes.Tips = new Class({ this.node = false; } }, - + setAsProperty: $.lambda(true), - + onMouseOut: function(e, win) { //mouseout a label var evt = $.event.get(e, win); @@ -2342,7 +2342,7 @@ Extras.Classes.Tips = new Class({ } this.hide(false); }, - + onMouseOver: function(e, win) { //mouseover a label var label; @@ -2351,7 +2351,7 @@ Extras.Classes.Tips = new Class({ this.config.onShow(this.tip, this.node, label); } }, - + onMouseMove: function(e, win, opt) { if(this.dom && this.isLabel(e, win)) { this.setTooltipPosition($.event.getPos(e, win)); @@ -2369,10 +2369,10 @@ Extras.Classes.Tips = new Class({ this.setTooltipPosition($.event.getPos(e, win)); } }, - + setTooltipPosition: function(pos) { - var tip = this.tip, - style = tip.style, + var tip = this.tip, + style = tip.style, cont = this.config; style.display = ''; //get window dimensions @@ -2383,16 +2383,16 @@ Extras.Classes.Tips = new Class({ //get tooltip dimensions var obj = { 'width': tip.offsetWidth, - 'height': tip.offsetHeight + 'height': tip.offsetHeight }; //set tooltip position var x = cont.offsetX, y = cont.offsetY; - style.top = ((pos.y + y + obj.height > win.height)? + style.top = ((pos.y + y + obj.height > win.height)? (pos.y - obj.height - y) : pos.y + y) + 'px'; - style.left = ((pos.x + obj.width + x > win.width)? + style.left = ((pos.x + obj.width + x > win.width)? (pos.x - obj.width - x) : pos.x + x) + 'px'; }, - + hide: function(triggerCallback) { this.tip.style.display = 'none'; triggerCallback && this.config.onHide(); @@ -2401,20 +2401,20 @@ Extras.Classes.Tips = new Class({ /* Class: NodeStyles - + Change node styles when clicking or hovering a node. This class is used internally. - + Used by: - + , , , , , , - + See also: - + */ Extras.Classes.NodeStyles = new Class({ Implements: [ExtrasInitializer, EventsInterface], - + initializePost: function() { this.fx = this.viz.fx; this.types = this.viz.fx.nodeTypes; @@ -2423,11 +2423,11 @@ Extras.Classes.NodeStyles = new Class({ this.nodeStylesOnClick = this.nStyles.stylesClick; this.hoveredNode = false; this.fx.nodeFxAnimation = new Animation(); - + this.down = false; this.move = false; }, - + onMouseOut: function(e, win) { this.down = this.move = false; if(!this.hoveredNode) return; @@ -2445,7 +2445,7 @@ Extras.Classes.NodeStyles = new Class({ this.toggleStylesOnHover(this.hoveredNode, false); this.hoveredNode = false; }, - + onMouseOver: function(e, win) { //mouseover a label var label; @@ -2456,7 +2456,7 @@ Extras.Classes.NodeStyles = new Class({ this.toggleStylesOnHover(this.hoveredNode, true); } }, - + onMouseDown: function(e, win, event, isRightClick) { if(isRightClick) return; var label; @@ -2467,7 +2467,7 @@ Extras.Classes.NodeStyles = new Class({ } this.move = false; }, - + onMouseUp: function(e, win, event, isRightClick) { if(isRightClick) return; if(!this.move) { @@ -2475,16 +2475,16 @@ Extras.Classes.NodeStyles = new Class({ } this.down = this.move = false; }, - + getRestoredStyles: function(node, type) { - var restoredStyles = {}, + var restoredStyles = {}, nStyles = this['nodeStylesOn' + type]; for(var prop in nStyles) { restoredStyles[prop] = node.styles['$' + prop]; } return restoredStyles; }, - + toggleStylesOnHover: function(node, set) { if(this.nodeStylesOnHover) { this.toggleStylesOn('Hover', node, set); @@ -2496,7 +2496,7 @@ Extras.Classes.NodeStyles = new Class({ this.toggleStylesOn('Click', node, set); } }, - + toggleStylesOn: function(type, node, set) { var viz = this.viz; var nStyles = this.nStyles; @@ -2508,7 +2508,7 @@ Extras.Classes.NodeStyles = new Class({ for(var s in this['nodeStylesOn' + type]) { var $s = '$' + s; if(!($s in node.styles)) { - node.styles[$s] = node.getData(s); + node.styles[$s] = node.getData(s); } } viz.fx.nodeFx($.extend({ @@ -2559,7 +2559,7 @@ Extras.Classes.NodeStyles = new Class({ this.hoveredNode = false; } }, - + onMouseMove: function(e, win, event) { //if mouse button is down and moving set move=true if(this.down) this.move = true; @@ -2567,11 +2567,11 @@ Extras.Classes.NodeStyles = new Class({ if(this.dom && this.isLabel(e, win)) return; var nStyles = this.nodeStylesOnHover; if(!nStyles) return; - + if(!this.dom) { if(this.hoveredNode) { var geom = this.types[this.hoveredNode.getData('type')]; - var contains = geom && geom.contains && geom.contains.call(this.fx, + var contains = geom && geom.contains && geom.contains.call(this.fx, this.hoveredNode, event.getPos()); if(contains) return; } @@ -2611,12 +2611,12 @@ Extras.Classes.NodeStyles = new Class({ Extras.Classes.Navigation = new Class({ Implements: [ExtrasInitializer, EventsInterface], - + initializePost: function() { this.pos = false; this.pressed = false; }, - + onMouseWheel: function(e, win, scroll) { if(!this.config.zooming) return; $.event.stop($.event.get(e, win)); @@ -2624,7 +2624,7 @@ Extras.Classes.Navigation = new Class({ ans = 1 + scroll * val; this.canvas.scale(ans, ans); }, - + onMouseDown: function(e, win, eventInfo) { if(!this.config.panning) return; if(this.config.panning == 'avoid nodes' && (this.dom? this.isLabel(e, win) : eventInfo.getNode())) return; @@ -2640,12 +2640,12 @@ Extras.Classes.Navigation = new Class({ this.pos.y *= sy; this.pos.y += oy; }, - + onMouseMove: function(e, win, eventInfo) { if(!this.config.panning) return; if(!this.pressed) return; if(this.config.panning == 'avoid nodes' && (this.dom? this.isLabel(e, win) : eventInfo.getNode())) return; - var thispos = this.pos, + var thispos = this.pos, currentPos = eventInfo.getPos(), canvas = this.canvas, ox = canvas.translateOffsetX, @@ -2661,7 +2661,7 @@ Extras.Classes.Navigation = new Class({ this.pos = currentPos; this.canvas.translate(x * 1/sx, y * 1/sy); }, - + onMouseUp: function(e, win, eventInfo, isRightClick) { if(!this.config.panning) return; this.pressed = false; @@ -2676,28 +2676,28 @@ Extras.Classes.Navigation = new Class({ /* Class: Canvas - - A canvas widget used by all visualizations. The canvas object can be accessed by doing *viz.canvas*. If you want to + + A canvas widget used by all visualizations. The canvas object can be accessed by doing *viz.canvas*. If you want to know more about options take a look at . - - A canvas widget is a set of DOM elements that wrap the native canvas DOM Element providing a consistent API and behavior + + A canvas widget is a set of DOM elements that wrap the native canvas DOM Element providing a consistent API and behavior across all browsers. It can also include Elements to add DOM (SVG or HTML) label support to all visualizations. - + Example: - + Suppose we have this HTML - + (start code xml)
(end code) - + Now we create a new Visualization - + (start code js) var viz = new $jit.Viz({ //Where to inject the canvas. Any div container will do. 'injectInto':'infovis', - //width and height for canvas. + //width and height for canvas. //Default's to the container offsetWidth and Height. 'width': 900, 'height':500 @@ -2705,7 +2705,7 @@ Extras.Classes.Navigation = new Class({ (end code) The generated HTML will look like this - + (start code xml)
@@ -2717,7 +2717,7 @@ Extras.Classes.Navigation = new Class({
(end code) - + As you can see, the generated HTML consists of a canvas DOM Element of id *infovis-canvas* and a div label container of id *infovis-label*, wrapped in a main div container of id *infovis-canvaswidget*. */ @@ -2752,14 +2752,14 @@ var Canvas; translateOffsetY: 0, scaleOffsetX: 1, scaleOffsetY: 1, - + initialize: function(viz, opt) { this.viz = viz; this.opt = this.config = opt; - var id = $.type(opt.injectInto) == 'string'? + var id = $.type(opt.injectInto) == 'string'? opt.injectInto:opt.injectInto.id, type = opt.type, - idLabel = id + "-label", + idLabel = id + "-label", wrapper = $(id), width = opt.width || wrapper.offsetWidth, height = opt.height || wrapper.offsetHeight; @@ -2780,7 +2780,7 @@ var Canvas; } }); //create label container - this.labelContainer = this.createLabelContainer(opt.Label.type, + this.labelContainer = this.createLabelContainer(opt.Label.type, idLabel, canvasOptions); //create primary canvas this.canvases.push(new Canvas.Base[type]({ @@ -2819,11 +2819,11 @@ var Canvas; }, /* Method: getCtx - + Returns the main canvas context object - + Example: - + (start code js) var ctx = canvas.getCtx(); //Now I can use the native canvas context @@ -2836,11 +2836,11 @@ var Canvas; }, /* Method: getConfig - + Returns the current Configuration for this Canvas Widget. - + Example: - + (start code js) var config = canvas.getConfig(); (end code) @@ -2852,9 +2852,9 @@ var Canvas; Method: getElement Returns the main Canvas DOM wrapper - + Example: - + (start code js) var wrapper = canvas.getElement(); //Returns
...
as element @@ -2865,13 +2865,13 @@ var Canvas; }, /* Method: getSize - + Returns canvas dimensions. - + Returns: - + An object with *width* and *height* properties. - + Example: (start code js) canvas.getSize(); //returns { width: 900, height: 500 } @@ -2882,20 +2882,20 @@ var Canvas; }, /* Method: resize - + Resizes the canvas. - + Parameters: - + width - New canvas width. height - New canvas height. - + Example: - + (start code js) canvas.resize(width, height); (end code) - + */ resize: function(width, height) { this.getPos(true); @@ -2912,21 +2912,21 @@ var Canvas; }, /* Method: translate - + Applies a translation to the canvas. - + Parameters: - + x - (number) x offset. y - (number) y offset. disablePlot - (boolean) Default's *false*. Set this to *true* if you don't want to refresh the visualization. - + Example: - + (start code js) canvas.translate(30, 30); (end code) - + */ translate: function(x, y, disablePlot) { this.translateOffsetX += x*this.scaleOffsetX; @@ -2937,21 +2937,21 @@ var Canvas; }, /* Method: scale - + Scales the canvas. - + Parameters: - + x - (number) scale value. y - (number) scale value. disablePlot - (boolean) Default's *false*. Set this to *true* if you don't want to refresh the visualization. - + Example: - + (start code js) canvas.scale(0.5, 0.5); (end code) - + */ scale: function(x, y, disablePlot) { var px = this.scaleOffsetX * x, @@ -2967,17 +2967,17 @@ var Canvas; }, /* Method: getPos - + Returns the canvas position as an *x, y* object. - + Parameters: - + force - (boolean) Default's *false*. Set this to *true* if you want to recalculate the position without using any cache information. - + Returns: - + An object with *x* and *y* properties. - + Example: (start code js) canvas.getPos(true); //returns { x: 900, y: 500 } @@ -2991,13 +2991,13 @@ var Canvas; }, /* Method: clear - + Clears the canvas. */ clear: function(i){ this.canvases[i||0].clear(); }, - + path: function(type, action){ var ctx = this.canvases[0].getCtx(); ctx.beginPath(); @@ -3005,7 +3005,7 @@ var Canvas; ctx[type](); ctx.closePath(); }, - + createLabelContainer: function(type, idLabel, dim) { var NS = 'http://www.w3.org/2000/svg'; if(type == 'HTML' || type == 'Native') { @@ -3071,7 +3071,7 @@ var Canvas; }); }, getCtx: function() { - if(!this.ctx) + if(!this.ctx) return this.ctx = this.canvas.getContext('2d'); return this.ctx; }, @@ -3108,7 +3108,7 @@ var Canvas; } this.translateOffsetX = this.translateOffsetY = 0; - this.scaleOffsetX = + this.scaleOffsetX = this.scaleOffsetY = 1; this.clear(); this.viz.resize(width, height, this); @@ -3133,8 +3133,8 @@ var Canvas; oy = this.translateOffsetY, sx = this.scaleOffsetX, sy = this.scaleOffsetY; - this.getCtx().clearRect((-size.width / 2 - ox) * 1/sx, - (-size.height / 2 - oy) * 1/sy, + this.getCtx().clearRect((-size.width / 2 - ox) * 1/sx, + (-size.height / 2 - oy) * 1/sy, size.width * 1/sx, size.height * 1/sy); }, plot: function() { @@ -3182,7 +3182,7 @@ var Canvas; /* * File: Polar.js - * + * * Defines the class. * * Description: @@ -3201,13 +3201,13 @@ var Canvas; A multi purpose polar representation. Description: - + The class, just like the class, is used by the , and as a 2D point representation. - + See also: - + - + Parameters: theta - An angle. @@ -3224,15 +3224,15 @@ $jit.Polar = Polar; Polar.prototype = { /* Method: getc - + Returns a complex number. - + Parameters: simple - _optional_ If *true*, this method will return only an object holding x and y properties and not a instance. Default's *false*. Returns: - + A complex number. */ getc: function(simple) { @@ -3241,11 +3241,11 @@ Polar.prototype = { /* Method: getp - + Returns a representation. - + Returns: - + A variable in polar coordinates. */ getp: function() { @@ -3255,13 +3255,13 @@ Polar.prototype = { /* Method: set - + Sets a number. Parameters: v - A or instance. - + */ set: function(v) { v = v.getp(); @@ -3270,14 +3270,14 @@ Polar.prototype = { /* Method: setc - + Sets a number. Parameters: x - A number real part. y - A number imaginary part. - + */ setc: function(x, y) { this.rho = Math.sqrt(x * x + y * y); @@ -3287,27 +3287,27 @@ Polar.prototype = { /* Method: setp - + Sets a polar number. Parameters: theta - A number angle property. rho - A number rho property. - + */ setp: function(theta, rho) { - this.theta = theta; + this.theta = theta; this.rho = rho; }, /* Method: clone - + Returns a copy of the current object. - + Returns: - + A copy of the real object. */ clone: function() { @@ -3316,15 +3316,15 @@ Polar.prototype = { /* Method: toComplex - + Translates from polar to cartesian coordinates and returns a new instance. - + Parameters: simple - _optional_ If *true* this method will only return an object with x and y properties (and not the whole instance). Default's *false*. - + Returns: - + A new instance. */ toComplex: function(simple) { @@ -3336,41 +3336,41 @@ Polar.prototype = { /* Method: add - + Adds two instances. - + Parameters: polar - A number. Returns: - + A new Polar instance. */ add: function(polar) { return new Polar(this.theta + polar.theta, this.rho + polar.rho); }, - + /* Method: scale - + Scales a polar norm. - + Parameters: number - A scale factor. - + Returns: - + A new Polar instance. */ scale: function(number) { return new Polar(this.theta, this.rho * number); }, - + /* Method: equals - + Comparison method. Returns *true* if the theta and rho properties are equal. @@ -3386,18 +3386,18 @@ Polar.prototype = { equals: function(c) { return this.theta == c.theta && this.rho == c.rho; }, - + /* Method: $add - + Adds two instances affecting the current object. - + Paramters: polar - A instance. Returns: - + The changed object. */ $add: function(polar) { @@ -3407,15 +3407,15 @@ Polar.prototype = { /* Method: $madd - + Adds two instances affecting the current object. The resulting theta angle is modulo 2pi. - + Parameters: polar - A instance. Returns: - + The changed object. */ $madd: function(polar) { @@ -3423,30 +3423,30 @@ Polar.prototype = { return this; }, - + /* Method: $scale - + Scales a polar instance affecting the object. - + Parameters: number - A scaling factor. Returns: - + The changed object. */ $scale: function(number) { this.rho *= number; return this; }, - + /* Method: isZero - + Returns *true* if the number is zero. - + */ isZero: function () { var almostZero = 0.0001, abs = Math.abs; @@ -3455,16 +3455,16 @@ Polar.prototype = { /* Method: interpolate - + Calculates a polar interpolation between two points at a given delta moment. Parameters: - + elem - A instance. delta - A delta factor ranging [0, 1]. - + Returns: - + A new instance representing an interpolation between _this_ and _elem_ */ interpolate: function(elem, delta) { @@ -3487,7 +3487,7 @@ Polar.prototype = { } else { sum = ch((et - pi2 + (tt - (et - pi2)) * delta)); } - } else { + } else { sum = ch((et + (tt - et) * delta)) ; } var r = (this.rho - elem.rho) * delta + elem.rho; @@ -3507,7 +3507,7 @@ Polar.KER = $P(0, 0); /* * File: Complex.js - * + * * Defines the class. * * Description: @@ -3522,22 +3522,22 @@ Polar.KER = $P(0, 0); /* Class: Complex - + A multi-purpose Complex Class with common methods. - + Description: - + The class, just like the class, is used by the , and as a 2D point representation. - + See also: - + Parameters: x - _optional_ A Complex number real part. y - _optional_ A Complex number imaginary part. - + */ var Complex = function(x, y) { @@ -3550,11 +3550,11 @@ $jit.Complex = Complex; Complex.prototype = { /* Method: getc - + Returns a complex number. - + Returns: - + A complex number. */ getc: function() { @@ -3563,15 +3563,15 @@ Complex.prototype = { /* Method: getp - + Returns a representation of this number. - + Parameters: simple - _optional_ If *true*, this method will return only an object holding theta and rho properties and not a instance. Default's *false*. Returns: - + A variable in coordinates. */ getp: function(simple) { @@ -3581,46 +3581,46 @@ Complex.prototype = { /* Method: set - + Sets a number. Parameters: c - A or instance. - + */ set: function(c) { c = c.getc(true); - this.x = c.x; + this.x = c.x; this.y = c.y; }, /* Method: setc - + Sets a complex number. Parameters: x - A number Real part. y - A number Imaginary part. - + */ setc: function(x, y) { - this.x = x; + this.x = x; this.y = y; }, /* Method: setp - + Sets a polar number. Parameters: theta - A number theta property. rho - A number rho property. - + */ setp: function(theta, rho) { this.x = Math.cos(theta) * rho; @@ -3629,11 +3629,11 @@ Complex.prototype = { /* Method: clone - + Returns a copy of the current object. - + Returns: - + A copy of the real object. */ clone: function() { @@ -3642,18 +3642,18 @@ Complex.prototype = { /* Method: toPolar - + Transforms cartesian to polar coordinates. - + Parameters: simple - _optional_ If *true* this method will only return an object with theta and rho properties (and not the whole instance). Default's *false*. - + Returns: - + A new instance. */ - + toPolar: function(simple) { var rho = this.norm(); var atan = Math.atan2(this.y, this.x); @@ -3663,24 +3663,24 @@ Complex.prototype = { }, /* Method: norm - + Calculates a number norm. - + Returns: - + A real number representing the complex norm. */ norm: function () { return Math.sqrt(this.squaredNorm()); }, - + /* Method: squaredNorm - + Calculates a number squared norm. - + Returns: - + A real number representing the complex squared norm. */ squaredNorm: function () { @@ -3689,17 +3689,17 @@ Complex.prototype = { /* Method: add - + Returns the result of adding two complex numbers. - + Does not alter the original object. Parameters: - + pos - A instance. - + Returns: - + The result of adding two complex numbers. */ add: function(pos) { @@ -3708,17 +3708,17 @@ Complex.prototype = { /* Method: prod - + Returns the result of multiplying two numbers. - + Does not alter the original object. Parameters: - + pos - A instance. - + Returns: - + The result of multiplying two complex numbers. */ prod: function(pos) { @@ -3727,13 +3727,13 @@ Complex.prototype = { /* Method: conjugate - + Returns the conjugate of this number. Does not alter the original object. Returns: - + The conjugate of this number. */ conjugate: function() { @@ -3743,17 +3743,17 @@ Complex.prototype = { /* Method: scale - + Returns the result of scaling a instance. - + Does not alter the original object. Parameters: - + factor - A scale factor. - + Returns: - + The result of scaling this complex to a factor. */ scale: function(factor) { @@ -3762,7 +3762,7 @@ Complex.prototype = { /* Method: equals - + Comparison method. Returns *true* if both real and imaginary parts are equal. @@ -3781,37 +3781,37 @@ Complex.prototype = { /* Method: $add - + Returns the result of adding two numbers. - + Alters the original object. Parameters: - + pos - A instance. - + Returns: - + The result of adding two complex numbers. */ $add: function(pos) { this.x += pos.x; this.y += pos.y; - return this; + return this; }, - + /* Method: $prod - + Returns the result of multiplying two numbers. - + Alters the original object. Parameters: - + pos - A instance. - + Returns: - + The result of multiplying two complex numbers. */ $prod:function(pos) { @@ -3820,56 +3820,56 @@ Complex.prototype = { this.y = y*pos.x + x*pos.y; return this; }, - + /* Method: $conjugate - + Returns the conjugate for this . - + Alters the original object. Returns: - + The conjugate for this complex. */ $conjugate: function() { this.y = -this.y; return this; }, - + /* Method: $scale - + Returns the result of scaling a instance. - + Alters the original object. Parameters: - + factor - A scale factor. - + Returns: - + The result of scaling this complex to a factor. */ $scale: function(factor) { this.x *= factor; this.y *= factor; return this; }, - + /* Method: $div - + Returns the division of two numbers. - + Alters the original object. Parameters: - + pos - A number. - + Returns: - + The result of scaling this complex to a factor. */ $div: function(pos) { @@ -3881,9 +3881,9 @@ Complex.prototype = { /* Method: isZero - + Returns *true* if the number is zero. - + */ isZero: function () { var almostZero = 0.0001, abs = Math.abs; @@ -3908,7 +3908,7 @@ Complex.KER = $C(0, 0); A Graph Class that provides useful manipulation functions. You can find more manipulation methods in the object. An instance of this class can be accessed by using the *graph* parameter of any tree or graph visualization. - + Example: (start code js) @@ -3919,11 +3919,11 @@ Complex.KER = $C(0, 0); //access model viz.graph; // instance (end code) - + Implements: - + The following methods are implemented in - + - - - @@ -3931,8 +3931,8 @@ Complex.KER = $C(0, 0); - - - - -*/ + +*/ $jit.Graph = new Class({ @@ -3947,7 +3947,7 @@ $jit.Graph = new Class({ this.opt = $.merge(innerOptions, opt || {}); this.nodes = {}; this.edges = {}; - + //add nodeList methods var that = this; this.nodeList = {}; @@ -3966,7 +3966,7 @@ $jit.Graph = new Class({ /* Method: getNode - + Returns a by *id*. Parameters: @@ -3978,7 +3978,7 @@ $jit.Graph = new Class({ (start code js) var node = graph.getNode('nodeId'); (end code) -*/ +*/ getNode: function(id) { if(this.hasNode(id)) return this.nodes[id]; return false; @@ -3986,38 +3986,38 @@ $jit.Graph = new Class({ /* Method: get - + An alias for . Returns a node by *id*. - + Parameters: - + id - (string) A id. - + Example: - + (start code js) var node = graph.get('nodeId'); (end code) -*/ +*/ get: function(id) { return this.getNode(id); }, /* Method: getByName - + Returns a by *name*. - + Parameters: - + name - (string) A name. - + Example: - + (start code js) var node = graph.getByName('someName'); (end code) - */ + */ getByName: function(name) { for(var id in this.nodes) { var n = this.nodes[id]; @@ -4028,14 +4028,14 @@ $jit.Graph = new Class({ /* Method: getAdjacence - + Returns a object connecting nodes with ids *id* and *id2*. Parameters: id - (string) A id. id2 - (string) A id. -*/ +*/ getAdjacence: function (id, id2) { if(id in this.edges) { return this.edges[id][id2]; @@ -4045,11 +4045,11 @@ $jit.Graph = new Class({ /* Method: addNode - + Adds a node. - + Parameters: - + obj - An object with the properties described below id - (string) A node id @@ -4059,31 +4059,31 @@ $jit.Graph = new Class({ See also: - */ - addNode: function(obj) { - if(!this.nodes[obj.id]) { + */ + addNode: function(obj) { + if(!this.nodes[obj.id]) { var edges = this.edges[obj.id] = {}; this.nodes[obj.id] = new Graph.Node($.extend({ 'id': obj.id, 'name': obj.name, 'data': $.merge(obj.data || {}, {}), - 'adjacencies': edges - }, this.opt.Node), - this.opt.klass, - this.Node, + 'adjacencies': edges + }, this.opt.Node), + this.opt.klass, + this.Node, this.Edge, this.Label); } return this.nodes[obj.id]; }, - + /* Method: addAdjacence - + Connects nodes specified by *obj* and *obj2*. If not found, nodes are created. - + Parameters: - + obj - (object) A object. obj2 - (object) Another object. data - (object) A data object. Used to store some extra information in the object created. @@ -4091,7 +4091,7 @@ $jit.Graph = new Class({ See also: , - */ + */ addAdjacence: function (obj, obj2, data) { if(!this.hasNode(obj.id)) { this.addNode(obj); } if(!this.hasNode(obj2.id)) { this.addNode(obj2); } @@ -4107,14 +4107,14 @@ $jit.Graph = new Class({ /* Method: removeNode - + Removes a matching the specified *id*. Parameters: id - (string) A node's id. - */ + */ removeNode: function(id) { if(this.hasNode(id)) { delete this.nodes[id]; @@ -4125,17 +4125,17 @@ $jit.Graph = new Class({ delete this.edges[id]; } }, - + /* Method: removeAdjacence - + Removes a matching *id1* and *id2*. Parameters: id1 - (string) A id. id2 - (string) A id. -*/ +*/ removeAdjacence: function(id1, id2) { delete this.edges[id1][id2]; delete this.edges[id2][id1]; @@ -4143,17 +4143,17 @@ $jit.Graph = new Class({ /* Method: hasNode - + Returns a boolean indicating if the node belongs to the or not. - + Parameters: - + id - (string) Node id. - */ + */ hasNode: function(id) { return id in this.nodes; }, - + /* Method: empty @@ -4168,9 +4168,9 @@ var Graph = $jit.Graph; /* Object: Accessors - + Defines a set of methods for data, canvas and label styles manipulation implemented by and instances. - + */ var Accessors; @@ -4241,7 +4241,7 @@ var Accessors; prop - (string) The name of the property. The dollar sign is not needed. For example *getData(width)* will return *data.$width*. - type - (string) The type of the data property queried. Default's "current". You can access *start* and *end* + type - (string) The type of the data property queried. Default's "current". You can access *start* and *end* data properties also. These properties are used when making animations. force - (boolean) Whether to obtain the true value of the property (equivalent to *data.$prop*) or to check for *node.overridable = true* first. @@ -4276,13 +4276,13 @@ var Accessors; can also be "start" or "end". Example: - + (start code js) node.setData('width', 30); (end code) - + If we were to make an animation of a node/edge width then we could do - + (start code js) var node = viz.getNode('nodeId'); //set start and end values @@ -4303,9 +4303,9 @@ var Accessors; Method: setDataset Convenience method to set multiple data values at once. - + Parameters: - + types - (array|string) A set of 'current', 'end' or 'start' values. obj - (object) A hash containing the names and values of the properties to be altered. @@ -4321,11 +4321,11 @@ var Accessors; 'color': '#ccc' }); (end code) - - See also: - + + See also: + - + */ setDataset: function(types, obj) { types = $.splat(types); @@ -4335,7 +4335,7 @@ var Accessors; } } }, - + /* Method: removeData @@ -4365,16 +4365,16 @@ var Accessors; prop - (string) The name of the property. The dollar sign is not needed. For example *getCanvasStyle(shadowBlur)* will return *data[$canvas-shadowBlur]*. - type - (string) The type of the data property queried. Default's *current*. You can access *start* and *end* + type - (string) The type of the data property queried. Default's *current*. You can access *start* and *end* data properties also. - + Example: (start code js) node.getCanvasStyle('shadowBlur'); (end code) - + See also: - + */ getCanvasStyle: function(prop, type, force) { @@ -4387,21 +4387,21 @@ var Accessors; Sets the canvas style data property with some specific value. This method is only useful for reserved (dollar prefixed) properties. - + Parameters: - + prop - (string) Name of the property. Can be any canvas property like 'shadowBlur', 'shadowColor', 'strokeStyle', etc. value - (mixed) The value to set to the property. type - (string) Default's *current*. Whether to set *start*, *current* or *end* type properties. - + Example: - + (start code js) node.setCanvasStyle('shadowBlur', 30); (end code) - + If we were to make an animation of a node/edge shadowBlur canvas style then we could do - + (start code js) var node = viz.getNode('nodeId'); //set start and end values @@ -4413,9 +4413,9 @@ var Accessors; duration: 1000 }); (end code) - + See also: - + . */ setCanvasStyle: function(prop, value, type) { @@ -4428,12 +4428,12 @@ var Accessors; Convenience method to set multiple styles at once. Parameters: - + types - (array|string) A set of 'current', 'end' or 'start' values. obj - (object) A hash containing the names and values of the properties to be altered. See also: - + . */ setCanvasStyles: function(types, obj) { @@ -4451,11 +4451,11 @@ var Accessors; Remove canvas style properties from data. Parameters: - + A variable number of canvas style strings. See also: - + . */ removeCanvasStyle: function() { @@ -4473,11 +4473,11 @@ var Accessors; prop - (string) The name of the property. The dollar sign prefix is not needed. For example *getLabelData(size)* will return *data[$label-size]*. - type - (string) The type of the data property queried. Default's *current*. You can access *start* and *end* + type - (string) The type of the data property queried. Default's *current*. You can access *start* and *end* data properties also. - + See also: - + . */ getLabelData: function(prop, type, force) { @@ -4492,19 +4492,19 @@ var Accessors; This method is only useful for reserved (dollar prefixed) properties. Parameters: - + prop - (string) Name of the property. Can be any canvas property like 'shadowBlur', 'shadowColor', 'strokeStyle', etc. value - (mixed) The value to set to the property. type - (string) Default's *current*. Whether to set *start*, *current* or *end* type properties. - + Example: - + (start code js) node.setLabelData('size', 30); (end code) - + If we were to make an animation of a node label size then we could do - + (start code js) var node = viz.getNode('nodeId'); //set start and end values @@ -4516,9 +4516,9 @@ var Accessors; duration: 1000 }); (end code) - + See also: - + . */ setLabelData: function(prop, value, type) { @@ -4531,12 +4531,12 @@ var Accessors; Convenience function to set multiple label data at once. Parameters: - + types - (array|string) A set of 'current', 'end' or 'start' values. obj - (object) A hash containing the names and values of the properties to be altered. See also: - + . */ setLabelDataset: function(types, obj) { @@ -4552,13 +4552,13 @@ var Accessors; Method: removeLabelData Remove label properties from data. - + Parameters: - + A variable number of label property strings. See also: - + . */ removeLabelData: function() { @@ -4571,13 +4571,13 @@ var Accessors; Class: Graph.Node A node. - + Implements: - + methods. - + The following methods are implemented by - + - - - @@ -4585,10 +4585,10 @@ var Accessors; - - - - - + - */ Graph.Node = new Class({ - + initialize: function(opt, klass, Node, Edge, Label) { var innerOptions = { 'id': '', @@ -4611,7 +4611,7 @@ Graph.Node = new Class({ 'startPos': new klass, 'endPos': new klass }; - + $.extend(this, $.extend(innerOptions, opt)); this.Config = this.Node = Node; this.Edge = Edge; @@ -4620,13 +4620,13 @@ Graph.Node = new Class({ /* Method: adjacentTo - + Indicates if the node is adjacent to the node specified by id Parameters: - + id - (string) A node id. - + Example: (start code js) node.adjacentTo('nodeId') == true; @@ -4638,30 +4638,30 @@ Graph.Node = new Class({ /* Method: getAdjacency - + Returns a object connecting the current and the node having *id* as id. Parameters: - + id - (string) A node id. - */ + */ getAdjacency: function(id) { return this.adjacencies[id]; }, /* Method: getPos - + Returns the position of the node. - + Parameters: - + type - (string) Default's *current*. Possible values are "start", "end" or "current". - + Returns: - + A or instance. - + Example: (start code js) var pos = node.getPos('end'); @@ -4679,14 +4679,14 @@ Graph.Node = new Class({ }, /* Method: setPos - + Sets the node's position. - + Parameters: - + value - (object) A or instance. type - (string) Default's *current*. Possible values are "start", "end" or "current". - + Example: (start code js) node.setPos(new $jit.Complex(0, 0), 'end'); @@ -4712,9 +4712,9 @@ Graph.Node.implement(Accessors); Class: Graph.Adjacence A adjacence (or edge) connecting two . - + Implements: - + methods. See also: @@ -4722,13 +4722,13 @@ Graph.Node.implement(Accessors); , Properties: - + nodeFrom - A connected by this edge. nodeTo - Another connected by this edge. data - Node data property containing a hash (i.e {}) with custom options. */ Graph.Adjacence = new Class({ - + initialize: function(nodeFrom, nodeTo, data, Edge, Label) { this.nodeFrom = nodeFrom; this.nodeTo = nodeTo; @@ -4746,24 +4746,24 @@ Graph.Adjacence.implement(Accessors); Object: Graph.Util traversal and processing utility object. - + Note: - + For your convenience some of these methods have also been appended to and classes. */ Graph.Util = { /* filter - + For internal use only. Provides a filtering function based on flags. */ filter: function(param) { if(!param || !($.type(param) == 'string')) return function() { return true; }; var props = param.split(" "); return function(elem) { - for(var i=0; i by *id*. - + Also implemented by: - + Parameters: @@ -4794,14 +4794,14 @@ Graph.Util = { getNode: function(graph, id) { return graph.nodes[id]; }, - + /* Method: eachNode - + Iterates over nodes performing an *action*. - + Also implemented by: - + . Parameters: @@ -4824,23 +4824,23 @@ Graph.Util = { var filter = this.filter(flags); for(var i in graph.nodes) { if(filter(graph.nodes[i])) action(graph.nodes[i]); - } + } }, - + /* Method: each - + Iterates over nodes performing an *action*. It's an alias for . - + Also implemented by: - + . - + Parameters: - + graph - (object) A instance. action - (function) A callback function having a as first formal parameter. - + Example: (start code js) $jit.Graph.Util.each(graph, function(node) { @@ -4853,16 +4853,16 @@ Graph.Util = { (end code) */ each: function(graph, action, flags) { - this.eachNode(graph, action, flags); + this.eachNode(graph, action, flags); }, /* Method: eachAdjacency - + Iterates over adjacencies applying the *action* function. - + Also implemented by: - + . Parameters: @@ -4898,16 +4898,16 @@ Graph.Util = { /* Method: computeLevels - + Performs a BFS traversal setting the correct depth for each node. - + Also implemented by: - + . - + Note: - - The depth of each node can then be accessed by + + The depth of each node can then be accessed by >node._depth Parameters: @@ -4942,11 +4942,11 @@ Graph.Util = { /* Method: eachBFS - + Performs a BFS traversal applying *action* to each . - + Also implemented by: - + . Parameters: @@ -4983,18 +4983,18 @@ Graph.Util = { }, flags); } }, - + /* Method: eachLevel - + Iterates over a node's subgraph applying *action* to the nodes of relative depth between *levelBegin* and *levelEnd*. - + Also implemented by: - + . Parameters: - + node - (object) A . levelBegin - (number) A relative level value. levelEnd - (number) A relative level value. @@ -5013,16 +5013,16 @@ Graph.Util = { if(n._depth > d) loopLevel(n, levelBegin, levelEnd); }); } - })(node, levelBegin + d, levelEnd + d); + })(node, levelBegin + d, levelEnd + d); }, /* Method: eachSubgraph - + Iterates over a node's children recursively. - + Also implemented by: - + . Parameters: @@ -5046,13 +5046,13 @@ Graph.Util = { /* Method: eachSubnode - + Iterates over a node's children (without deeper recursion). - + Also implemented by: - + . - + Parameters: node - (object) A . action - (function) A callback function having a as first formal parameter. @@ -5074,11 +5074,11 @@ Graph.Util = { /* Method: anySubnode - + Returns *true* if any subnode matches the given condition. - + Also implemented by: - + . Parameters: @@ -5101,15 +5101,15 @@ Graph.Util = { }, flags); return flag; }, - + /* Method: getSubnodes - - Collects all subnodes for a specified node. - The *level* parameter filters nodes having relative depth of *level* from the root node. - + + Collects all subnodes for a specified node. + The *level* parameter filters nodes having relative depth of *level* from the root node. + Also implemented by: - + . Parameters: @@ -5136,15 +5136,15 @@ Graph.Util = { }, flags); return ans; }, - - + + /* Method: getParents - + Returns an Array of which are parents of the given node. - + Also implemented by: - + . Parameters: @@ -5158,7 +5158,7 @@ Graph.Util = { var pars = $jit.Graph.Util.getParents(node); //or... var pars = node.getParents(); - + if(pars.length > 0) { //do stuff with parents } @@ -5172,17 +5172,17 @@ Graph.Util = { }); return ans; }, - + /* Method: isDescendantOf - - Returns a boolean indicating if some node is descendant of the node with the given id. + + Returns a boolean indicating if some node is descendant of the node with the given id. Also implemented by: - + . - - + + Parameters: node - (object) A . id - (string) A id. @@ -5205,52 +5205,52 @@ Graph.Util = { /* Method: clean - + Cleans flags from nodes. Also implemented by: - + . - + Parameters: graph - A instance. */ clean: function(graph) { this.eachNode(graph, function(elem) { elem._flag = false; }); }, - - /* - Method: getClosestNodeToOrigin - + + /* + Method: getClosestNodeToOrigin + Returns the closest node to the center of canvas. - + Also implemented by: - + . - + Parameters: - + graph - (object) A instance. prop - (optional|string) Default's 'current'. A position property. Possible properties are 'start', 'current' or 'end'. - + */ getClosestNodeToOrigin: function(graph, prop, flags) { return this.getClosestNodeToPos(graph, Polar.KER, prop, flags); }, - - /* + + /* Method: getClosestNodeToPos - + Returns the closest node to the given position. - + Also implemented by: - + . - + Parameters: - + graph - (object) A instance. pos - (object) A or instance. prop - (optional|string) Default's *current*. A position property. Possible properties are 'start', 'current' or 'end'. - + */ getClosestNodeToPos: function(graph, pos, prop, flags) { var node = null; @@ -5265,7 +5265,7 @@ Graph.Util = { node.getPos(prop).getc(true), pos)) ? elem : node; }, flags); return node; - } + } }; //Append graph methods to @@ -5290,7 +5290,7 @@ $.each(['eachAdjacency', 'eachLevel', 'eachSubgraph', 'eachSubnode', 'anySubnode /* Object: Graph.Op - Perform operations like adding/removing or , + Perform operations like adding/removing or , morphing a into another , contracting or expanding subtrees, etc. */ @@ -5302,19 +5302,19 @@ Graph.Op = { hideLabels: true, fps:30 }, - + initialize: function(viz) { this.viz = viz; }, /* Method: removeNode - - Removes one or more from the visualization. + + Removes one or more from the visualization. It can also perform several animations like fading sequentially, fading concurrently, iterating or replotting. Parameters: - + node - (string|array) The node's id. Can also be an array having many ids. opt - (object) Animation options. It's an object with optional properties described below type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con" or "iter". @@ -5322,7 +5322,7 @@ Graph.Op = { fps - Described in . transition - Described in . hideLabels - (boolean) Default's *true*. Hide labels during the animation. - + Example: (start code js) var viz = new $jit.Viz(options); @@ -5339,7 +5339,7 @@ Graph.Op = { }); (end code) */ - + removeNode: function(node, opt) { var viz = this.viz; var options = $.merge(this.options, viz.controller, opt); @@ -5349,13 +5349,13 @@ Graph.Op = { case 'nothing': for(i=0; i from the visualization. + + Removes one or more from the visualization. It can also perform several animations like fading sequentially, fading concurrently, iterating or replotting. Parameters: - + vertex - (array) An array having two strings which are the ids of the nodes connected by this edge (i.e ['id1', 'id2']). Can also be a two dimensional array holding many edges (i.e [['id1', 'id2'], ['id3', 'id4'], ...]). opt - (object) Animation options. It's an object with optional properties described below type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con" or "iter". @@ -5423,7 +5423,7 @@ Graph.Op = { fps - Described in . transition - Described in . hideLabels - (boolean) Default's *true*. Hide labels during the animation. - + Example: (start code js) var viz = new $jit.Viz(options); @@ -5439,7 +5439,7 @@ Graph.Op = { duration: 1500 }); (end code) - + */ removeEdge: function(vertex, opt) { var viz = this.viz; @@ -5450,12 +5450,12 @@ Graph.Op = { case 'nothing': for(i=0; i Parameters: - + json - (object) A json tree or graph structure. See also . opt - (object) Animation options. It's an object with optional properties described below type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:seq", "fade:con". @@ -5527,7 +5527,7 @@ Graph.Op = { fps - Described in . transition - Described in . hideLabels - (boolean) Default's *true*. Hide labels during the animation. - + Example: (start code js) //...json contains a tree or graph structure... @@ -5545,7 +5545,7 @@ Graph.Op = { duration: 1500 }); (end code) - + */ sum: function(json, opt) { var viz = this.viz; @@ -5561,13 +5561,13 @@ Graph.Op = { }); }); break; - + case 'replot': viz.refresh(true); this.sum(json, { type: 'nothing' }); viz.refresh(true); break; - + case 'fade:seq': case 'fade': case 'fade:con': that = this; graph = viz.construct(json); @@ -5591,7 +5591,7 @@ Graph.Op = { } else { viz.graph.eachNode(function(elem) { if (elem.id != root && elem.pos.isZero()) { - elem.pos.set(elem.endPos); + elem.pos.set(elem.endPos); elem.startPos.set(elem.endPos); } }); @@ -5604,15 +5604,15 @@ Graph.Op = { default: this.doError(); } }, - + /* Method: morph - - This method will transform the current visualized graph into the new JSON representation passed in the method. + + This method will transform the current visualized graph into the new JSON representation passed in the method. The JSON object must at least have the root node in common with the current visualized graph. Parameters: - + json - (object) A json tree or graph structure. See also . opt - (object) Animation options. It's an object with optional properties described below type - (string) Default's *nothing*. Type of the animation. Can be "nothing", "replot", "fade:con". @@ -5621,12 +5621,12 @@ Graph.Op = { transition - Described in . hideLabels - (boolean) Default's *true*. Hide labels during the animation. id - (string) The shared id between both graphs. - - extraModes - (optional|object) When morphing with an animation, dollar prefixed data parameters are added to - *endData* and not *data* itself. This way you can animate dollar prefixed parameters during your morphing operation. - For animating these extra-parameters you have to specify an object that has animation groups as keys and animation + + extraModes - (optional|object) When morphing with an animation, dollar prefixed data parameters are added to + *endData* and not *data* itself. This way you can animate dollar prefixed parameters during your morphing operation. + For animating these extra-parameters you have to specify an object that has animation groups as keys and animation properties as values, just like specified in . - + Example: (start code js) //...json contains a tree or graph structure... @@ -5652,21 +5652,21 @@ Graph.Op = { 'node-property': ['width', 'height'] }); (end code) - + */ morph: function(json, opt, extraModes) { extraModes = extraModes || {}; var viz = this.viz; var options = $.merge(this.options, viz.controller, opt), root = viz.root; var graph; - //TODO(nico) this hack makes morphing work with the Hypertree. + //TODO(nico) this hack makes morphing work with the Hypertree. //Need to check if it has been solved and this can be removed. viz.root = opt.id || viz.root; switch(options.type) { case 'nothing': graph = viz.construct(json); graph.eachNode(function(elem) { - var nodeExists = viz.graph.hasNode(elem.id); + var nodeExists = viz.graph.hasNode(elem.id); elem.eachAdjacency(function(adj) { var adjExists = !!viz.graph.getAdjacence(adj.nodeFrom.id, adj.nodeTo.id); viz.graph.addAdjacence(adj.nodeFrom, adj.nodeTo, adj.data); @@ -5694,26 +5694,26 @@ Graph.Op = { }); if(!graph.hasNode(elem.id)) viz.graph.removeNode(elem.id); }); - + break; - + case 'replot': viz.labels.clearLabels(true); this.morph(json, { type: 'nothing' }); viz.refresh(true); viz.refresh(true); break; - + case 'fade:seq': case 'fade': case 'fade:con': that = this; graph = viz.construct(json); //preprocessing for nodes to delete. //get node property modes to interpolate - var nodeModes = ('node-property' in extraModes) - && $.map($.splat(extraModes['node-property']), + var nodeModes = ('node-property' in extraModes) + && $.map($.splat(extraModes['node-property']), function(n) { return '$' + n; }); viz.graph.eachNode(function(elem) { - var graphNode = graph.getNode(elem.id); + var graphNode = graph.getNode(elem.id); if(!graphNode) { elem.setData('alpha', 1); elem.setData('alpha', 1, 'start'); @@ -5730,7 +5730,7 @@ Graph.Op = { } } } - }); + }); viz.graph.eachNode(function(elem) { if(elem.ignore) return; elem.eachAdjacency(function(adj) { @@ -5745,18 +5745,18 @@ Graph.Op = { adj.setData('alpha', 0, 'end'); } }); - }); + }); //preprocessing for adding nodes. var fadeEdges = this.preprocessSum(graph); - var modes = !fadeEdges? ['node-property:alpha'] : - ['node-property:alpha', + var modes = !fadeEdges? ['node-property:alpha'] : + ['node-property:alpha', 'edge-property:alpha']; //Append extra node-property animations (if any) - modes[0] = modes[0] + (('node-property' in extraModes)? + modes[0] = modes[0] + (('node-property' in extraModes)? (':' + $.splat(extraModes['node-property']).join(':')) : ''); //Append extra edge-property animations (if any) - modes[1] = (modes[1] || 'edge-property:alpha') + (('edge-property' in extraModes)? + modes[1] = (modes[1] || 'edge-property:alpha') + (('edge-property' in extraModes)? (':' + $.splat(extraModes['edge-property']).join(':')) : ''); //Add label-property animations (if any) if('label-property' in extraModes) { @@ -5793,18 +5793,18 @@ Graph.Op = { } }, - + /* Method: contract - + Collapses the subtree of the given node. The node will have a _collapsed=true_ property. - + Parameters: - + node - (object) A . opt - (object) An object containing options described below type - (string) Whether to 'replot' or 'animate' the contraction. - + There are also a number of Animation options. For more information see . Example: @@ -5817,7 +5817,7 @@ Graph.Op = { transition: $jit.Trans.Quart.easeOut }); (end code) - + */ contract: function(node, opt) { var viz = this.viz; @@ -5851,18 +5851,18 @@ Graph.Op = { viz.refresh(); } }, - + /* Method: expand - + Expands the previously contracted subtree. The given node must have the _collapsed=true_ property. - + Parameters: - + node - (object) A . opt - (object) An object containing options described below type - (string) Whether to 'replot' or 'animate'. - + There are also a number of Animation options. For more information see . Example: @@ -5875,7 +5875,7 @@ Graph.Op = { transition: $jit.Trans.Quart.easeOut }); (end code) - + */ expand: function(node, opt) { if(!('collapsed' in node)) return; @@ -5914,7 +5914,7 @@ Graph.Op = { n.setData('alpha', 0, 'start'); n.setData('alpha', 1, 'end'); } - }); + }); var fadeEdges = false; graph.eachNode(function(elem) { elem.eachAdjacency(function(adj) { @@ -5922,16 +5922,16 @@ Graph.Op = { var nodeTo = viz.graph.getNode(adj.nodeTo.id); if(!nodeFrom.adjacentTo(nodeTo)) { var adj = viz.graph.addAdjacence(nodeFrom, nodeTo, adj.data); - if(nodeFrom.startAlpha == nodeFrom.endAlpha + if(nodeFrom.startAlpha == nodeFrom.endAlpha && nodeTo.startAlpha == nodeTo.endAlpha) { fadeEdges = true; adj.setData('alpha', 0); adj.setData('alpha', 0, 'start'); adj.setData('alpha', 1, 'end'); - } + } } }); - }); + }); return fadeEdges; } }; @@ -5940,14 +5940,14 @@ Graph.Op = { /* File: Helpers.js - + Helpers are objects that contain rendering primitives (like rectangles, ellipses, etc), for plotting nodes and edges. Helpers also contain implementations of the *contains* method, a method returning a boolean indicating whether the mouse position is over the rendered shape. - - Helpers are very useful when implementing new NodeTypes, since you can access them through *this.nodeHelper* and + + Helpers are very useful when implementing new NodeTypes, since you can access them through *this.nodeHelper* and *this.edgeHelper* properties, providing you with simple primitives and mouse-position check functions. - + Example: (start code js) //implement a new node type @@ -5979,7 +5979,7 @@ Graph.Op = { /* Object: NodeHelper - + Contains rendering and other type of primitives for simple shapes. */ var NodeHelper = { @@ -5993,16 +5993,16 @@ var NodeHelper = { 'circle': { /* Method: render - + Renders a circle into the canvas. - + Parameters: - + type - (string) Possible options are 'fill' or 'stroke'. pos - (object) An *x*, *y* object with the position of the center of the circle. radius - (number) The radius of the circle to be rendered. canvas - (object) A instance. - + Example: (start code js) NodeHelper.circle.render('fill', { x: 10, y: 30 }, 30, viz.canvas); @@ -6017,23 +6017,23 @@ var NodeHelper = { }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + npos - (object) An *x*, *y* object with the position. pos - (object) An *x*, *y* object with the position to check. radius - (number) The radius of the rendered circle. - + Example: (start code js) NodeHelper.circle.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); //true (end code) */ 'contains': function(npos, pos, radius){ - var diffx = npos.x - pos.x, - diffy = npos.y - pos.y, + var diffx = npos.x - pos.x, + diffy = npos.y - pos.y, diff = diffx * diffx + diffy * diffy; return diff <= radius * radius; } @@ -6044,17 +6044,17 @@ var NodeHelper = { 'ellipse': { /* Method: render - + Renders an ellipse into the canvas. - + Parameters: - + type - (string) Possible options are 'fill' or 'stroke'. pos - (object) An *x*, *y* object with the position of the center of the ellipse. width - (number) The width of the ellipse. height - (number) The height of the ellipse. canvas - (object) A instance. - + Example: (start code js) NodeHelper.ellipse.render('fill', { x: 10, y: 30 }, 30, 40, viz.canvas); @@ -6088,16 +6088,16 @@ var NodeHelper = { }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + npos - (object) An *x*, *y* object with the position. pos - (object) An *x*, *y* object with the position to check. width - (number) The width of the rendered ellipse. height - (number) The height of the rendered ellipse. - + Example: (start code js) NodeHelper.ellipse.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30, 40); @@ -6131,16 +6131,16 @@ var NodeHelper = { 'square': { /* Method: render - + Renders a square into the canvas. - + Parameters: - + type - (string) Possible options are 'fill' or 'stroke'. pos - (object) An *x*, *y* object with the position of the center of the square. dim - (number) The radius (or half-diameter) of the square. canvas - (object) A instance. - + Example: (start code js) NodeHelper.square.render('stroke', { x: 10, y: 30 }, 40, viz.canvas); @@ -6151,15 +6151,15 @@ var NodeHelper = { }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + npos - (object) An *x*, *y* object with the position. pos - (object) An *x*, *y* object with the position to check. dim - (number) The radius (or half-diameter) of the square. - + Example: (start code js) NodeHelper.square.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); @@ -6175,38 +6175,38 @@ var NodeHelper = { 'rectangle': { /* Method: render - + Renders a rectangle into the canvas. - + Parameters: - + type - (string) Possible options are 'fill' or 'stroke'. pos - (object) An *x*, *y* object with the position of the center of the rectangle. width - (number) The width of the rectangle. height - (number) The height of the rectangle. canvas - (object) A instance. - + Example: (start code js) NodeHelper.rectangle.render('fill', { x: 10, y: 30 }, 30, 40, viz.canvas); (end code) */ 'render': function(type, pos, width, height, canvas){ - canvas.getCtx()[type + "Rect"](pos.x - width / 2, pos.y - height / 2, + canvas.getCtx()[type + "Rect"](pos.x - width / 2, pos.y - height / 2, width, height); }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + npos - (object) An *x*, *y* object with the position. pos - (object) An *x*, *y* object with the position to check. width - (number) The width of the rendered rectangle. height - (number) The height of the rendered rectangle. - + Example: (start code js) NodeHelper.rectangle.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30, 40); @@ -6223,28 +6223,28 @@ var NodeHelper = { 'triangle': { /* Method: render - + Renders a triangle into the canvas. - + Parameters: - + type - (string) Possible options are 'fill' or 'stroke'. pos - (object) An *x*, *y* object with the position of the center of the triangle. dim - (number) Half the base and half the height of the triangle. canvas - (object) A instance. - + Example: (start code js) NodeHelper.triangle.render('stroke', { x: 10, y: 30 }, 40, viz.canvas); (end code) */ 'render': function(type, pos, dim, canvas){ - var ctx = canvas.getCtx(), - c1x = pos.x, - c1y = pos.y - dim, - c2x = c1x - dim, - c2y = pos.y + dim, - c3x = c1x + dim, + var ctx = canvas.getCtx(), + c1x = pos.x, + c1y = pos.y - dim, + c2x = c1x - dim, + c2y = pos.y + dim, + c3x = c1x + dim, c3y = c2y; ctx.beginPath(); ctx.moveTo(c1x, c1y); @@ -6255,15 +6255,15 @@ var NodeHelper = { }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + npos - (object) An *x*, *y* object with the position. pos - (object) An *x*, *y* object with the position to check. dim - (number) Half the base and half the height of the triangle. - + Example: (start code js) NodeHelper.triangle.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); @@ -6279,23 +6279,23 @@ var NodeHelper = { 'star': { /* Method: render - + Renders a star (concave decagon) into the canvas. - + Parameters: - + type - (string) Possible options are 'fill' or 'stroke'. pos - (object) An *x*, *y* object with the position of the center of the star. dim - (number) The length of a side of a concave decagon. canvas - (object) A instance. - + Example: (start code js) NodeHelper.star.render('stroke', { x: 10, y: 30 }, 40, viz.canvas); (end code) */ 'render': function(type, pos, dim, canvas){ - var ctx = canvas.getCtx(), + var ctx = canvas.getCtx(), pi5 = Math.PI / 5; ctx.save(); ctx.translate(pos.x, pos.y); @@ -6315,15 +6315,15 @@ var NodeHelper = { }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + npos - (object) An *x*, *y* object with the position. pos - (object) An *x*, *y* object with the position to check. dim - (number) The length of a side of a concave decagon. - + Example: (start code js) NodeHelper.star.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, 30); @@ -6337,7 +6337,7 @@ var NodeHelper = { /* Object: EdgeHelper - + Contains rendering primitives for simple edge shapes. */ var EdgeHelper = { @@ -6347,15 +6347,15 @@ var EdgeHelper = { 'line': { /* Method: render - + Renders a line into the canvas. - + Parameters: - + from - (object) An *x*, *y* object with the starting position of the line. to - (object) An *x*, *y* object with the ending position of the line. canvas - (object) A instance. - + Example: (start code js) EdgeHelper.line.render({ x: 10, y: 30 }, { x: 10, y: 50 }, viz.canvas); @@ -6370,30 +6370,30 @@ var EdgeHelper = { }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + posFrom - (object) An *x*, *y* object with a position. posTo - (object) An *x*, *y* object with a position. pos - (object) An *x*, *y* object with the position to check. epsilon - (number) The dimension of the shape. - + Example: (start code js) EdgeHelper.line.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, { x: 15, y: 35 }, 30); (end code) */ 'contains': function(posFrom, posTo, pos, epsilon) { - var min = Math.min, + var min = Math.min, max = Math.max, minPosX = min(posFrom.x, posTo.x), maxPosX = max(posFrom.x, posTo.x), minPosY = min(posFrom.y, posTo.y), maxPosY = max(posFrom.y, posTo.y); - - if(pos.x >= minPosX && pos.x <= maxPosX + + if(pos.x >= minPosX && pos.x <= maxPosX && pos.y >= minPosY && pos.y <= maxPosY) { if(Math.abs(posTo.x - posFrom.x) <= epsilon) { return true; @@ -6410,17 +6410,17 @@ var EdgeHelper = { 'arrow': { /* Method: render - + Renders an arrow into the canvas. - + Parameters: - + from - (object) An *x*, *y* object with the starting position of the arrow. to - (object) An *x*, *y* object with the ending position of the arrow. dim - (number) The dimension of the arrow. swap - (boolean) Whether to set the arrow pointing to the starting position or the ending position. canvas - (object) A instance. - + Example: (start code js) EdgeHelper.arrow.render({ x: 10, y: 30 }, { x: 10, y: 50 }, 13, false, viz.canvas); @@ -6438,9 +6438,9 @@ var EdgeHelper = { vect.$scale(dim / vect.norm()); var intermediatePoint = new Complex(to.x - vect.x, to.y - vect.y), normal = new Complex(-vect.y / 2, vect.x / 2), - v1 = intermediatePoint.add(normal), + v1 = intermediatePoint.add(normal), v2 = intermediatePoint.$add(normal.$scale(-1)); - + ctx.beginPath(); ctx.moveTo(from.x, from.y); ctx.lineTo(to.x, to.y); @@ -6454,16 +6454,16 @@ var EdgeHelper = { }, /* Method: contains - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + posFrom - (object) An *x*, *y* object with a position. posTo - (object) An *x*, *y* object with a position. pos - (object) An *x*, *y* object with the position to check. epsilon - (number) The dimension of the shape. - + Example: (start code js) EdgeHelper.arrow.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, { x: 15, y: 35 }, 30); @@ -6479,23 +6479,23 @@ var EdgeHelper = { 'hyperline': { /* Method: render - + Renders a hyperline into the canvas. A hyperline are the lines drawn for the visualization. - + Parameters: - + from - (object) An *x*, *y* object with the starting position of the hyperline. *x* and *y* must belong to [0, 1). to - (object) An *x*, *y* object with the ending position of the hyperline. *x* and *y* must belong to [0, 1). r - (number) The scaling factor. canvas - (object) A instance. - + Example: (start code js) EdgeHelper.hyperline.render({ x: 10, y: 30 }, { x: 10, y: 50 }, 100, viz.canvas); (end code) */ 'render': function(from, to, r, canvas){ - var ctx = canvas.getCtx(); + var ctx = canvas.getCtx(); var centerOfCircle = computeArcThroughTwoPoints(from, to); if (centerOfCircle.a > 1000 || centerOfCircle.b > 1000 || centerOfCircle.ratio < 0) { @@ -6514,19 +6514,19 @@ var EdgeHelper = { * r, angleBegin, angleEnd, sense); ctx.stroke(); } - /* + /* Calculates the arc parameters through two points. - - More information in - + + More information in + Parameters: - + p1 - A instance. p2 - A instance. scale - The Disk's diameter. - + Returns: - + An object containing some arc properties. */ function computeArcThroughTwoPoints(p1, p2){ @@ -6539,7 +6539,7 @@ var EdgeHelper = { y: 0, ratio: -1 }; - + var a = (p1.y * sq2 - p2.y * sq1 + p1.y - p2.y) / aDen; var b = (p2.x * sq1 - p1.x * sq2 + p2.x - p1.x) / bDen; var x = -a / 2; @@ -6560,20 +6560,20 @@ var EdgeHelper = { a: a, b: b }; - + return out; } - /* - Sets angle direction to clockwise (true) or counterclockwise (false). - - Parameters: - - angleBegin - Starting angle for drawing the arc. - angleEnd - The HyperLine will be drawn from angleBegin to angleEnd. - - Returns: - - A Boolean instance describing the sense for drawing the HyperLine. + /* + Sets angle direction to clockwise (true) or counterclockwise (false). + + Parameters: + + angleBegin - Starting angle for drawing the arc. + angleEnd - The HyperLine will be drawn from angleBegin to angleEnd. + + Returns: + + A Boolean instance describing the sense for drawing the HyperLine. */ function sense(angleBegin, angleEnd){ return (angleBegin < angleEnd)? ((angleBegin + Math.PI > angleEnd)? false @@ -6582,18 +6582,18 @@ var EdgeHelper = { }, /* Method: contains - + Not Implemented - + Returns *true* if *pos* is contained in the area of the shape. Returns *false* otherwise. - + Parameters: - + posFrom - (object) An *x*, *y* object with a position. posTo - (object) An *x*, *y* object with a position. pos - (object) An *x*, *y* object with the position to check. epsilon - (number) The dimension of the shape. - + Example: (start code js) EdgeHelper.hyperline.contains({ x: 10, y: 30 }, { x: 15, y: 35 }, { x: 15, y: 35 }, 30); @@ -6612,9 +6612,9 @@ var EdgeHelper = { Object: Graph.Plot rendering and animation methods. - + Properties: - + nodeHelper - object. edgeHelper - object. */ @@ -6634,7 +6634,7 @@ Graph.Plot = { //Add helpers nodeHelper: NodeHelper, edgeHelper: EdgeHelper, - + Interpolator: { //node/edge property parsers 'map': { @@ -6651,7 +6651,7 @@ Graph.Plot = { 'dimArray':'array-number' //'colorArray':'array-color' }, - + //canvas specific parsers 'canvas': { 'globalAlpha': 'number', @@ -6664,34 +6664,34 @@ Graph.Plot = { 'shadowOffsetY': 'number', 'miterLimit': 'number' }, - + //label parsers 'label': { 'size': 'number', 'color': 'color' }, - + //Number interpolator 'compute': function(from, to, delta) { return from + (to - from) * delta; }, - + //Position interpolators 'moebius': function(elem, props, delta, vector) { - var v = vector.scale(-delta); + var v = vector.scale(-delta); if(v.norm() < 1) { var x = v.x, y = v.y; var ans = elem.startPos .getc().moebiusTransformation(v); elem.pos.setc(ans.x, ans.y); v.x = x; v.y = y; - } + } }, 'linear': function(elem, props, delta) { var from = elem.startPos.getc(true); var to = elem.endPos.getc(true); - elem.pos.setc(this.compute(from.x, to.x, delta), + elem.pos.setc(this.compute(from.x, to.x, delta), this.compute(from.y, to.y, delta)); }, @@ -6701,7 +6701,7 @@ Graph.Plot = { var ans = to.interpolate(from, delta); elem.pos.setp(ans.theta, ans.rho); }, - + //Graph's Node/Edge interpolators 'number': function(elem, prop, delta, getter, setter) { var from = elem[getter](prop, 'start'); @@ -6716,10 +6716,10 @@ Graph.Plot = { var val = $.rgbToHex([parseInt(comp(from[0], to[0], delta)), parseInt(comp(from[1], to[1], delta)), parseInt(comp(from[2], to[2], delta))]); - + elem[setter](prop, val); }, - + 'array-number': function(elem, prop, delta, getter, setter) { var from = elem[getter](prop, 'start'), to = elem[getter](prop, 'end'), @@ -6737,7 +6737,7 @@ Graph.Plot = { } elem[setter](prop, cur); }, - + 'node': function(elem, props, delta, map, getter, setter) { map = this[map]; if(props) { @@ -6752,37 +6752,37 @@ Graph.Plot = { } } }, - + 'edge': function(elem, props, delta, mapKey, getter, setter) { var adjs = elem.adjacencies; for(var id in adjs) this['node'](adjs[id], props, delta, mapKey, getter, setter); }, - + 'node-property': function(elem, props, delta) { this['node'](elem, props, delta, 'map', 'getData', 'setData'); }, - + 'edge-property': function(elem, props, delta) { - this['edge'](elem, props, delta, 'map', 'getData', 'setData'); + this['edge'](elem, props, delta, 'map', 'getData', 'setData'); }, 'label-property': function(elem, props, delta) { this['node'](elem, props, delta, 'label', 'getLabelData', 'setLabelData'); }, - + 'node-style': function(elem, props, delta) { this['node'](elem, props, delta, 'canvas', 'getCanvasStyle', 'setCanvasStyle'); }, - + 'edge-style': function(elem, props, delta) { - this['edge'](elem, props, delta, 'canvas', 'getCanvasStyle', 'setCanvasStyle'); + this['edge'](elem, props, delta, 'canvas', 'getCanvasStyle', 'setCanvasStyle'); } }, - - + + /* sequence - + Iteratively performs an action while refreshing the state of the visualization. Parameters: @@ -6830,15 +6830,15 @@ Graph.Plot = { that.viz.refresh(true); }, options.duration); }, - + /* prepare - - Prepare graph position and other attribute values before performing an Animation. + + Prepare graph position and other attribute values before performing an Animation. This method is used internally by the Toolkit. - + See also: - + , */ @@ -6879,8 +6879,8 @@ Graph.Plot = { } } } - - graph.eachNode(function(node) { + + graph.eachNode(function(node) { node.startPos.set(node.pos); $.each(['node-property', 'node-style'], function(p) { if(p in m) { @@ -6903,10 +6903,10 @@ Graph.Plot = { }); return m; }, - + /* Method: animate - + Animates a by interpolating some , or properties. Parameters: @@ -6918,11 +6918,11 @@ Graph.Plot = { modes - (required|object) An object with animation modes (described below). Animation modes: - - Animation modes are strings representing different node/edge and graph properties that you'd like to animate. - They are represented by an object that has as keys main categories of properties to animate and as values a list + + Animation modes are strings representing different node/edge and graph properties that you'd like to animate. + They are represented by an object that has as keys main categories of properties to animate and as values a list of these specific properties. The properties are described below - + position - Describes the way nodes' positions must be interpolated. Possible values are 'linear', 'polar' or 'moebius'. node-property - Describes which Node properties will be interpolated. These properties can be any of the ones defined in . edge-property - Describes which Edge properties will be interpolated. These properties can be any the ones defined in . @@ -6962,13 +6962,13 @@ Graph.Plot = { animation = opt.type === 'nodefx'? this.nodeFxAnimation : this.animation; //prepare graph values var m = this.prepare(opt.modes); - + //animate if(opt.hideLabels) this.labels.hideLabels(true); animation.setOptions($.extend(opt, { $animating: false, compute: function(delta) { - graph.eachNode(function(node) { + graph.eachNode(function(node) { for(var p in m) { interp[p](node, m[p], delta, versor); } @@ -6982,20 +6982,20 @@ Graph.Plot = { opt.onComplete(); //TODO(nico): This shouldn't be here! //opt.onAfterCompute(); - } + } })).start(); }, - + /* nodeFx - + Apply animation to node properties like color, width, height, dim, etc. - + Parameters: - + options - Animation options. This object properties is described below elements - The Elements to be transformed. This is an object that has a properties - + (start code js) 'elements': { //can also be an array of ids @@ -7007,17 +7007,17 @@ Graph.Plot = { 'height': 10, //some height 'dim': 20, //some dim 'lineWidth': 10 //some line width - } + } } (end code) - - - _reposition_ Whether to recalculate positions and add a motion animation. + + - _reposition_ Whether to recalculate positions and add a motion animation. This might be used when changing _width_ or _height_ properties in a like layout. Default's *false*. - + - _onComplete_ A method that is called when the animation completes. - + ...and all other options like _duration_, _fps_, _transition_, etc. - + Example: (start code js) var rg = new RGraph(canvas, config); //can be also Hypertree or ST @@ -7030,7 +7030,7 @@ Graph.Plot = { 'transition': Trans.Quart.easeOut } }); - (end code) + (end code) */ nodeFx: function(opt) { var viz = this.viz, @@ -7085,10 +7085,10 @@ Graph.Plot = { })); }, - + /* Method: plot - + Plots a . Parameters: @@ -7099,25 +7099,25 @@ Graph.Plot = { (start code js) var viz = new $jit.Viz(options); - viz.fx.plot(); + viz.fx.plot(); (end code) */ plot: function(opt, animating) { - var viz = this.viz, - aGraph = viz.graph, - canvas = viz.canvas, - id = viz.root, - that = this, - ctx = canvas.getCtx(), + var viz = this.viz, + aGraph = viz.graph, + canvas = viz.canvas, + id = viz.root, + that = this, + ctx = canvas.getCtx(), min = Math.min, opt = opt || this.viz.controller; - + opt.clearCanvas && canvas.clear(); - + var root = aGraph.getNode(id); if(!root) return; - + var T = !!root.visited; aGraph.eachNode(function(node) { var nodeAlpha = node.getData('alpha'); @@ -7149,8 +7149,8 @@ Graph.Plot = { Plots a Subtree. */ plotTree: function(node, opt, animating) { - var that = this, - viz = this.viz, + var that = this, + viz = this.viz, canvas = viz.canvas, config = this.config, ctx = canvas.getCtx(); @@ -7168,9 +7168,9 @@ Graph.Plot = { !animating && opt.onBeforePlotNode(node); this.plotNode(node, canvas, animating); !animating && opt.onAfterPlotNode(node); - if(!opt.hideLabels && opt.withLabels && nodeAlpha >= 0.95) + if(!opt.hideLabels && opt.withLabels && nodeAlpha >= 0.95) this.labels.plotLabel(canvas, node, opt); - else + else this.labels.hideLabel(node, false); } else { this.labels.hideLabel(node, true); @@ -7179,17 +7179,17 @@ Graph.Plot = { /* Method: plotNode - + Plots a . Parameters: - + node - (object) A . canvas - (object) A element. */ plotNode: function(node, canvas, animating) { - var f = node.getData('type'), + var f = node.getData('type'), ctxObj = this.node.CanvasStyles; if(f != 'none') { var width = node.getData('lineWidth'), @@ -7200,7 +7200,7 @@ Graph.Plot = { ctx.lineWidth = width; ctx.fillStyle = ctx.strokeStyle = color; ctx.globalAlpha = alpha; - + for(var s in ctxObj) { ctx[s] = node.getCanvasStyle(s); } @@ -7209,10 +7209,10 @@ Graph.Plot = { ctx.restore(); } }, - + /* Method: plotLine - + Plots a . Parameters: @@ -7230,14 +7230,14 @@ Graph.Plot = { ctx = canvas.getCtx(), nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo; - + ctx.save(); ctx.lineWidth = width; ctx.fillStyle = ctx.strokeStyle = color; - ctx.globalAlpha = Math.min(nodeFrom.getData('alpha'), - nodeTo.getData('alpha'), + ctx.globalAlpha = Math.min(nodeFrom.getData('alpha'), + nodeTo.getData('alpha'), adj.getData('alpha')); - + for(var s in ctxObj) { ctx[s] = adj.getCanvasStyle(s); } @@ -7245,17 +7245,17 @@ Graph.Plot = { this.edgeTypes[f].render.call(this, adj, canvas, animating); ctx.restore(); } - } - + } + }; /* Object: Graph.Plot3D - + 3D rendering and animation methods. - + Properties: - + nodeHelper - object. edgeHelper - object. @@ -7265,12 +7265,12 @@ Graph.Plot3D = $.merge(Graph.Plot, { 'linear': function(elem, props, delta) { var from = elem.startPos.getc(true); var to = elem.endPos.getc(true); - elem.pos.setc(this.compute(from.x, to.x, delta), + elem.pos.setc(this.compute(from.x, to.x, delta), this.compute(from.y, to.y, delta), this.compute(from.z, to.z, delta)); } }, - + plotNode: function(node, canvas) { if(node.getData('type') == 'none') return; this.plotElement(node, canvas, { @@ -7279,7 +7279,7 @@ Graph.Plot3D = $.merge(Graph.Plot, { } }); }, - + plotLine: function(adj, canvas) { if(adj.getData('type') == 'none') return; this.plotElement(adj, canvas, { @@ -7290,7 +7290,7 @@ Graph.Plot3D = $.merge(Graph.Plot, { } }); }, - + plotElement: function(elem, canvas, opt) { var gl = canvas.getCtx(), viewMatrix = new Matrix4, @@ -7298,7 +7298,7 @@ Graph.Plot3D = $.merge(Graph.Plot, { wcanvas = canvas.canvases[0], program = wcanvas.program, camera = wcanvas.camera; - + if(!elem.geometry) { elem.geometry = new O3D[elem.getData('type')]; } @@ -7309,7 +7309,7 @@ Graph.Plot3D = $.merge(Graph.Plot, { normals = [], vertexIndex = 0, geom = elem.geometry; - + for(var i=0, vs=geom.vertices, fs=geom.faces, fsl=fs.length; i to provide - HTML label elements. Also we provide the interface for SVG type labels. + HTML label elements. Also we provide the interface for SVG type labels. The interface implements these methods with the native Canvas text rendering functions. - + All subclasses (, and ) implement the method plotLabel. */ @@ -7438,9 +7438,9 @@ Graph.Label.Native = new Class({ canvas - (object) A instance. node - (object) A . controller - (object) A configuration object. - + Example: - + (start code js) var viz = new $jit.Viz(options); var node = viz.graph.getNode('nodeId'); @@ -7697,9 +7697,9 @@ Graph.Label.HTML = new Class({ canvas - (object) A instance. node - (object) A . controller - (object) A configuration object. - + Example: - + (start code js) var viz = new $jit.Viz(options); var node = viz.graph.getNode('nodeId'); @@ -7748,9 +7748,9 @@ Graph.Label.SVG = new Class({ canvas - (object) A instance. node - (object) A . controller - (object) A configuration object. - + Example: - + (start code js) var viz = new $jit.Viz(options); var node = viz.graph.getNode('nodeId'); @@ -7789,18 +7789,18 @@ Graph.Geom = new Class({ }, /* Applies a translation to the tree. - + Parameters: - + pos - A number specifying translation vector. prop - A position property ('pos', 'start' or 'end'). - + Example: - + (start code js) st.geom.translate(new Complex(300, 100), 'end'); (end code) - */ + */ translate: function(pos, prop) { prop = $.splat(prop); this.viz.graph.eachNode(function(elem) { @@ -7809,9 +7809,9 @@ Graph.Geom = new Class({ }, /* Hides levels of the tree until it properly fits in canvas. - */ + */ setRightLevelToShow: function(node, canvas, callback) { - var level = this.getRightLevelToShow(node, canvas), + var level = this.getRightLevelToShow(node, canvas), fx = this.viz.labels, opt = $.merge({ execShow:true, @@ -7824,7 +7824,7 @@ Graph.Geom = new Class({ if(d > level) { opt.onHide(n); if(opt.execHide) { - n.drawn = false; + n.drawn = false; n.exist = false; fx.hideLabel(n, false); } @@ -7839,7 +7839,7 @@ Graph.Geom = new Class({ }, /* Returns the right level to show for the current tree in order to fit in canvas. - */ + */ getRightLevelToShow: function(node, canvas) { var config = this.config; var level = config.levelsToShow; @@ -7852,7 +7852,7 @@ Graph.Geom = new Class({ /* * File: Loader.js - * + * */ /* @@ -7864,7 +7864,7 @@ var Loader = { construct: function(json) { var isGraph = ($.type(json) == 'array'); var ans = new Graph(this.graphOptions, this.config.Node, this.config.Edge, this.config.Label); - if(!isGraph) + if(!isGraph) //make tree (function (ans, json) { ans.addNode(json); @@ -7914,116 +7914,116 @@ var Loader = { /* Method: loadJSON - + Loads a JSON structure to the visualization. The JSON structure can be a JSON *tree* or *graph* structure. - + A JSON tree or graph structure consists of nodes, each having as properties - + id - (string) A unique identifier for the node name - (string) A node's name - data - (object) The data optional property contains a hash (i.e {}) + data - (object) The data optional property contains a hash (i.e {}) where you can store all the information you want about this node. - + For JSON *Tree* structures, there's an extra optional property *children* of type Array which contains the node's children. - + Example: (start code js) - var json = { - "id": "aUniqueIdentifier", - "name": "usually a nodes name", + var json = { + "id": "aUniqueIdentifier", + "name": "usually a nodes name", "data": { "some key": "some value", "some other key": "some other value" - }, - "children": [ *other nodes or empty* ] - }; + }, + "children": [ *other nodes or empty* ] + }; (end code) - - JSON *Graph* structures consist of an array of nodes, each specifying the nodes to which the current node is connected. + + JSON *Graph* structures consist of an array of nodes, each specifying the nodes to which the current node is connected. For JSON *Graph* structures, the *children* property is replaced by the *adjacencies* property. - + There are two types of *Graph* structures, *simple* and *extended* graph structures. - - For *simple* Graph structures, the adjacencies property contains an array of strings, each specifying the + + For *simple* Graph structures, the adjacencies property contains an array of strings, each specifying the id of the node connected to the main node. - + Example: - + (start code js) - var json = [ - { - "id": "aUniqueIdentifier", - "name": "usually a nodes name", + var json = [ + { + "id": "aUniqueIdentifier", + "name": "usually a nodes name", "data": { "some key": "some value", "some other key": "some other value" - }, - "adjacencies": ["anotherUniqueIdentifier", "yetAnotherUniqueIdentifier", 'etc'] + }, + "adjacencies": ["anotherUniqueIdentifier", "yetAnotherUniqueIdentifier", 'etc'] }, - 'other nodes go here...' - ]; + 'other nodes go here...' + ]; (end code) - + For *extended Graph structures*, the adjacencies property contains an array of Adjacency objects that have as properties - + nodeTo - (string) The other node connected by this adjacency. data - (object) A data property, where we can store custom key/value information. - + Example: - + (start code js) - var json = [ - { - "id": "aUniqueIdentifier", - "name": "usually a nodes name", + var json = [ + { + "id": "aUniqueIdentifier", + "name": "usually a nodes name", "data": { "some key": "some value", "some other key": "some other value" - }, - "adjacencies": [ - { - nodeTo:"aNodeId", - data: {} //put whatever you want here + }, + "adjacencies": [ + { + nodeTo:"aNodeId", + data: {} //put whatever you want here }, - 'other adjacencies go here...' + 'other adjacencies go here...' }, - 'other nodes go here...' - ]; + 'other nodes go here...' + ]; (end code) - + About the data property: - - As described before, you can store custom data in the *data* property of JSON *nodes* and *adjacencies*. - You can use almost any string as key for the data object. Some keys though are reserved by the toolkit, and + + As described before, you can store custom data in the *data* property of JSON *nodes* and *adjacencies*. + You can use almost any string as key for the data object. Some keys though are reserved by the toolkit, and have special meanings. This is the case for keys starting with a dollar sign, for example, *$width*. - - For JSON *node* objects, adding dollar prefixed properties that match the names of the options defined in - will override the general value for that option with that particular value. For this to work + + For JSON *node* objects, adding dollar prefixed properties that match the names of the options defined in + will override the general value for that option with that particular value. For this to work however, you do have to set *overridable = true* in . - - The same thing is true for JSON adjacencies. Dollar prefixed data properties will alter values set in + + The same thing is true for JSON adjacencies. Dollar prefixed data properties will alter values set in if has *overridable = true*. - - When loading JSON data into TreeMaps, the *data* property must contain a value for the *$area* key, - since this is the value which will be taken into account when creating the layout. + + When loading JSON data into TreeMaps, the *data* property must contain a value for the *$area* key, + since this is the value which will be taken into account when creating the layout. The same thing goes for the *$color* parameter. - - In JSON Nodes you can use also *$label-* prefixed properties to refer to properties. For example, - *$label-size* will refer to size property. Also, in JSON nodes and adjacencies you can set - canvas specific properties individually by using the *$canvas-* prefix. For example, *$canvas-shadowBlur* will refer + + In JSON Nodes you can use also *$label-* prefixed properties to refer to properties. For example, + *$label-size* will refer to size property. Also, in JSON nodes and adjacencies you can set + canvas specific properties individually by using the *$canvas-* prefix. For example, *$canvas-shadowBlur* will refer to the *shadowBlur* property. - - These properties can also be accessed after loading the JSON data from and + + These properties can also be accessed after loading the JSON data from and by using . For more information take a look at the and documentation. - - Finally, these properties can also be used to create advanced animations like with . For more + + Finally, these properties can also be used to create advanced animations like with . For more information about creating animations please take a look at the and documentation. - + loadJSON Parameters: - + json - A JSON Tree or Graph structure. i - For Graph structures only. Sets the indexed node as root for the visualization. @@ -8041,22 +8041,22 @@ var Loader = { this.root = json[i? i : 0].id; } }, - + /* Method: toJSON - - Returns a JSON tree/graph structure from the visualization's . + + Returns a JSON tree/graph structure from the visualization's . See for the graph formats available. - + See also: - + - + Parameters: - - type - (string) Default's "tree". The type of the JSON structure to be returned. + + type - (string) Default's "tree". The type of the JSON structure to be returned. Possible options are "tree" or "graph". - */ + */ toJSON: function(type) { type = type || "tree"; if(type == 'tree') { @@ -8106,18 +8106,18 @@ var Loader = { /* * File: Layouts.js - * + * * Implements base Tree and Graph layouts. * * Description: * * Implements base Tree and Graph layouts like Radial, Tree, etc. - * + * */ /* * Object: Layouts - * + * * Parent object for common layouts. * */ @@ -8127,7 +8127,7 @@ var Layouts = $jit.Layouts = {}; //Some util shared layout functions are defined here. var NodeDim = { label: null, - + compute: function(graph, prop, opt) { this.initializeLabel(opt); var label = this.label, style = label.style; @@ -8140,16 +8140,16 @@ var NodeDim = { delete n.data.$width; delete n.data.$height; delete n.data.$dim; - + var width = n.getData('width'), height = n.getData('height'); //reset label dimensions style.width = autoWidth? 'auto' : width + 'px'; style.height = autoHeight? 'auto' : height + 'px'; - + //TODO(nico) should let the user choose what to insert here. label.innerHTML = n.name; - + var offsetWidth = label.offsetWidth, offsetHeight = label.offsetHeight; var type = n.getData('type'); @@ -8160,12 +8160,12 @@ var NodeDim = { var dim = offsetWidth > offsetHeight? offsetWidth : offsetHeight; n.setData('width', dim); n.setData('height', dim); - n.setData('dim', dim); + n.setData('dim', dim); } } }); }, - + initializeLabel: function(opt) { if(!this.label) { this.label = document.createElement('div'); @@ -8173,7 +8173,7 @@ var NodeDim = { } this.setLabelStyles(opt); }, - + setLabelStyles: function(opt) { $.extend(this.label.style, { 'visibility': 'hidden', @@ -8188,17 +8188,17 @@ var NodeDim = { /* * Class: Layouts.Tree - * + * * Implements a Tree Layout. - * + * * Implemented By: - * + * * - * + * * Inspired by: - * + * * Drawing Trees (Andrew J. Kennedy) - * + * */ Layouts.Tree = (function() { //Layout functions @@ -8206,7 +8206,7 @@ Layouts.Tree = (function() { /* Calculates the max width and height nodes for a tree level - */ + */ function getBoundaries(graph, config, level, orn, prop) { var dim = config.Node; var multitree = config.multitree; @@ -8380,7 +8380,7 @@ Layouts.Tree = (function() { return new Class({ /* Method: compute - + Computes nodes' positions. */ @@ -8396,7 +8396,7 @@ Layouts.Tree = (function() { if (!!computeLevels || !("_depth" in node)) { this.graph.computeLevels(this.root, 0, "ignore"); } - + this.computePositions(node, prop); }, @@ -8429,7 +8429,7 @@ Layouts.Tree = (function() { }); } }); - + })(); /* @@ -8438,28 +8438,28 @@ Layouts.Tree = (function() { /* Class: ST - + A Tree layout with advanced contraction and expansion animations. - + Inspired by: - - SpaceTree: Supporting Exploration in Large Node Link Tree, Design Evolution and Empirical Evaluation (Catherine Plaisant, Jesse Grosjean, Benjamin B. Bederson) + + SpaceTree: Supporting Exploration in Large Node Link Tree, Design Evolution and Empirical Evaluation (Catherine Plaisant, Jesse Grosjean, Benjamin B. Bederson) - + Drawing Trees (Andrew J. Kennedy) - + Note: - + This visualization was built and engineered from scratch, taking only the papers as inspiration, and only shares some features with the visualization described in those papers. - + Implements: - + All methods - + Constructor Options: - + Inherits options from - + - - - @@ -8470,9 +8470,9 @@ Layouts.Tree = (function() { - - - - + Additionally, there are other parameters and some default values changed - + constrained - (boolean) Default's *true*. Whether to show the entire tree when loaded or just the number of levels specified by _levelsToShow_. levelsToShow - (number) Default's *2*. The number of levels to show for a subtree. This number is relative to the selected node. levelDistance - (number) Default's *30*. The distance between two consecutive levels of the tree. @@ -8480,9 +8480,9 @@ Layouts.Tree = (function() { offsetX - (number) Default's *0*. The x-offset distance from the selected node to the center of the canvas. offsetY - (number) Default's *0*. The y-offset distance from the selected node to the center of the canvas. duration - Described in . It's default value has been changed to *700*. - + Instance Properties: - + canvas - Access a instance. graph - Access a instance. op - Access a instance. @@ -8518,21 +8518,21 @@ $jit.ST= (function() { node.eachLevel(leafLevel, leafLevel, function(n) { if(n.exist && !n.selected) nodeArray.push(n); }); - + for (var i = 0; i < nodesInPath.length; i++) { var n = this.graph.getNode(nodesInPath[i]); if(!n.isDescendantOf(node.id)) { nodeArray.push(n); } - } - return nodeArray; + } + return nodeArray; }; // Nodes to expand function getNodesToShow(node) { var nodeArray = [], config = this.config; node = node || this.clickedNode; this.clickedNode.eachLevel(0, config.levelsToShow, function(n) { - if(config.multitree && !('$orn' in n.data) + if(config.multitree && !('$orn' in n.data) && n.anySubnode(function(ch){ return ch.exist && !ch.drawn; })) { nodeArray.push(n); } else if(n.drawn && !n.anySubnode("drawn")) { @@ -8543,16 +8543,16 @@ $jit.ST= (function() { }; // Now define the actual class. return new Class({ - + Implements: [Loader, Extras, Layouts.Tree], - - initialize: function(controller) { + + initialize: function(controller) { var $ST = $jit.ST; - + var config= { levelsToShow: 2, levelDistance: 30, - constrained: true, + constrained: true, Node: { type: 'rectangle' }, @@ -8560,9 +8560,9 @@ $jit.ST= (function() { offsetX: 0, offsetY: 0 }; - + this.controller = this.config = $.merge( - Options("Canvas", "Fx", "Tree", "Node", "Edge", "Controller", + Options("Canvas", "Fx", "Tree", "Node", "Edge", "Controller", "Tips", "NodeStyles", "Events", "Navigation", "Label"), config, controller); var canvasConfig = this.config; @@ -8592,19 +8592,19 @@ $jit.ST= (function() { // initialize extras this.initializeExtras(); }, - + /* Method: plot - + Plots the . This is a shortcut to *fx.plot*. - */ + */ plot: function() { this.fx.plot(this.controller); }, - - + + /* Method: switchPosition - + Switches the tree orientation. Parameters: @@ -8619,10 +8619,10 @@ $jit.ST= (function() { st.switchPosition("right", "animate", { onComplete: function() { alert('completed!'); - } + } }); (end code) - */ + */ switchPosition: function(pos, method, onComplete) { var Geom = this.geom, Plot = this.fx, that = this; if(!Plot.busy) { @@ -8633,7 +8633,7 @@ $jit.ST= (function() { that.compute('end', false); Plot.busy = false; if(method == 'animate') { - that.onClick(that.clickedNode.id, onComplete); + that.onClick(that.clickedNode.id, onComplete); } else if(method == 'replot') { that.select(that.clickedNode.id, onComplete); } @@ -8644,7 +8644,7 @@ $jit.ST= (function() { /* Method: switchAlignment - + Switches the tree alignment. Parameters: @@ -8659,24 +8659,24 @@ $jit.ST= (function() { st.switchAlignment("right", "animate", { onComplete: function() { alert('completed!'); - } + } }); (end code) - */ + */ switchAlignment: function(align, method, onComplete) { this.config.align = align; if(method == 'animate') { this.select(this.clickedNode.id, onComplete); } else if(method == 'replot') { - this.onClick(this.clickedNode.id, onComplete); + this.onClick(this.clickedNode.id, onComplete); } }, /* Method: addNodeInPath - + Adds a node to the current path as selected node. The selected node will be visible (as in non-collapsed) at all times. - + Parameters: @@ -8687,42 +8687,42 @@ $jit.ST= (function() { (start code js) st.addNodeInPath("nodeId"); (end code) - */ + */ addNodeInPath: function(id) { nodesInPath.push(id); this.select((this.clickedNode && this.clickedNode.id) || this.root); - }, + }, /* Method: clearNodesInPath - + Removes all nodes tagged as selected by the method. - + See also: - + - + Example: (start code js) st.clearNodesInPath(); (end code) - */ + */ clearNodesInPath: function(id) { nodesInPath.length = 0; this.select((this.clickedNode && this.clickedNode.id) || this.root); }, - + /* Method: refresh - + Computes positions and plots the tree. - + */ refresh: function() { this.reposition(); this.select((this.clickedNode && this.clickedNode.id) || this.root); - }, + }, reposition: function() { this.graph.computeLevels(this.root, 0, "ignore"); @@ -8732,14 +8732,14 @@ $jit.ST= (function() { }); this.compute('end'); }, - + requestNodes: function(node, onComplete) { - var handler = $.merge(this.controller, onComplete), + var handler = $.merge(this.controller, onComplete), lev = this.config.levelsToShow; if(handler.request) { var leaves = [], d = node._depth; node.eachLevel(0, lev, function(n) { - if(n.drawn && + if(n.drawn && !n.anySubnode()) { leaves.push(n); n._level = lev - (n._depth - d); @@ -8750,7 +8750,7 @@ $jit.ST= (function() { else handler.onComplete(); }, - + contract: function(onComplete, switched) { var orn = this.config.orientation; var Geom = this.geom, Group = this.group; @@ -8759,35 +8759,35 @@ $jit.ST= (function() { if(switched) Geom.switchOrientation(orn); Group.contract(nodes, $.merge(this.controller, onComplete)); }, - + move: function(node, onComplete) { this.compute('end', false); var move = onComplete.Move, offset = { 'x': move.offsetX, - 'y': move.offsetY + 'y': move.offsetY }; if(move.enable) { this.geom.translate(node.endPos.add(offset).$scale(-1), "end"); } this.fx.animate($.merge(this.controller, { modes: ['linear'] }, onComplete)); }, - + expand: function (node, onComplete) { var nodeArray = getNodesToShow.call(this, node); this.group.expand(nodeArray, $.merge(this.controller, onComplete)); }, - + selectPath: function(node) { var that = this; - this.graph.eachNode(function(n) { n.selected = false; }); + this.graph.eachNode(function(n) { n.selected = false; }); function path(node) { if(node == null || node.selected) return; node.selected = true; - $.each(that.group.getSiblings([node])[node.id], - function(n) { - n.exist = true; - n.drawn = true; - }); + $.each(that.group.getSiblings([node])[node.id], + function(n) { + n.exist = true; + n.drawn = true; + }); var parents = node.getParents(); parents = (parents.length > 0)? parents[0] : null; path(parents); @@ -8796,17 +8796,17 @@ $jit.ST= (function() { path(this.graph.getNode(ns[i])); } }, - + /* Method: setRoot - + Switches the current root node. Changes the topology of the Tree. - + Parameters: id - (string) The id of the node to be set as root. method - (string) Set this to "animate" if you want to animate the tree after adding the subtree. You can also set this parameter to "replot" to just replot the subtree. onComplete - (optional|object) An action to perform after the animation (if any). - + Example: (start code js) @@ -8886,14 +8886,14 @@ $jit.ST= (function() { /* Method: addSubtree - + Adds a subtree. - + Parameters: subtree - (object) A JSON Tree object. See also . method - (string) Set this to "animate" if you want to animate the tree after adding the subtree. You can also set this parameter to "replot" to just replot the subtree. onComplete - (optional|object) An action to perform after the animation (if any). - + Example: (start code js) @@ -8911,12 +8911,12 @@ $jit.ST= (function() { this.op.sum(subtree, $.extend({ type: 'fade:seq' }, onComplete || {})); } }, - + /* Method: removeSubtree - + Removes a subtree. - + Parameters: id - (string) The _id_ of the subtree to be removed. removeRoot - (boolean) Default's *false*. Remove the root of the subtree or only its subnodes. @@ -8932,7 +8932,7 @@ $jit.ST= (function() { } }); (end code) - + */ removeSubtree: function(id, removeRoot, method, onComplete) { var node = this.graph.getNode(id), subids = []; @@ -8945,11 +8945,11 @@ $jit.ST= (function() { this.op.removeNode(subids, $.extend({ type: 'fade:seq'}, onComplete || {})); } }, - + /* Method: select - - Selects a node in the without performing an animation. Useful when selecting + + Selects a node in the without performing an animation. Useful when selecting nodes which are currently hidden or deep inside the tree. Parameters: @@ -8971,7 +8971,7 @@ $jit.ST= (function() { var root = this.graph.getNode(this.root); var complete = $.merge(this.controller, onComplete); var that = this; - + complete.onBeforeCompute(node); this.selectPath(node); this.clickedNode= node; @@ -8980,29 +8980,29 @@ $jit.ST= (function() { group.hide(group.prepare(getNodesToHide.call(that)), complete); geom.setRightLevelToShow(node, canvas); that.compute("current"); - that.graph.eachNode(function(n) { + that.graph.eachNode(function(n) { var pos = n.pos.getc(true); n.startPos.setc(pos.x, pos.y); n.endPos.setc(pos.x, pos.y); - n.visited = false; + n.visited = false; }); var offset = { x: complete.offsetX, y: complete.offsetY }; that.geom.translate(node.endPos.add(offset).$scale(-1), ["start", "current", "end"]); - group.show(getNodesToShow.call(that)); + group.show(getNodesToShow.call(that)); that.plot(); complete.onAfterCompute(that.clickedNode); complete.onComplete(); } - }); + }); }, - + /* Method: onClick - + Animates the to center the node specified by *id*. - + Parameters: - + id - (string) A node id. options - (optional|object) A group of options and callbacks described below. onComplete - (object) An object callback called when the animation finishes. @@ -9022,15 +9022,15 @@ $jit.ST= (function() { } }); (end code) - - */ + + */ onClick: function (id, options) { var canvas = this.canvas, that = this, Geom = this.geom, config = this.config; var innerController = { Move: { enable: true, offsetX: config.offsetX || 0, - offsetY: config.offsetY || 0 + offsetY: config.offsetY || 0 }, setRightLevelToShowConfig: false, onBeforeRequest: $.empty, @@ -9039,7 +9039,7 @@ $jit.ST= (function() { onBeforeExpand: $.empty }; var complete = $.merge(this.controller, innerController, options); - + if(!this.busy) { this.busy = true; var node = this.graph.getNode(id); @@ -9081,31 +9081,31 @@ $jit.ST.$extend = true; /* Class: ST.Op - + Custom extension of . Extends: All methods - + See also: - + */ $jit.ST.Op = new Class({ Implements: Graph.Op - + }); /* - + Performs operations on group of nodes. */ $jit.ST.Group = new Class({ - + initialize: function(viz) { this.viz = viz; this.canvas = viz.canvas; @@ -9113,10 +9113,10 @@ $jit.ST.Group = new Class({ this.animation = new Animation; this.nodes = null; }, - + /* - - Calls the request method on the controller to request a subtree for each node. + + Calls the request method on the controller to request a subtree for each node. */ requestNodes: function(nodes, controller) { var counter = 0, len = nodes.length, nodeSelected = {}; @@ -9139,10 +9139,10 @@ $jit.ST.Group = new Class({ }); } }, - + /* - - Collapses group of nodes. + + Collapses group of nodes. */ contract: function(nodes, controller) { var viz = this.viz; @@ -9156,13 +9156,13 @@ $jit.ST.Group = new Class({ that.plotStep(1 - delta, controller, this.$animating); this.$animating = 'contract'; }, - + complete: function() { that.hide(nodes, controller); - } + } })).start(); }, - + hide: function(nodes, controller) { var viz = this.viz; for(var i=0; i 0 + if(root && orns && orns.indexOf(n.data.$orn) > 0 && n.drawn) { n.drawn = false; nds[node.id].push(n); @@ -9287,7 +9287,7 @@ $jit.ST.Group = new Class({ n.drawn = false; nds[node.id].push(n); } - }); + }); node.drawn = true; } // plot the whole (non-scaled) tree @@ -9300,7 +9300,7 @@ $jit.ST.Group = new Class({ for(i=0; i instead. - */ + */ switchOrientation: function(orn) { this.config.orientation = orn; }, @@ -9376,12 +9376,12 @@ $jit.ST.Geom = new Class({ /* Returns label height or with, depending on the tree current orientation. - */ + */ getSize: function(n, invert) { var data = n.data, config = this.config; var siblingOffset = config.siblingOffset; - var s = (config.multitree - && ('$orn' in data) + var s = (config.multitree + && ('$orn' in data) && data.$orn) || config.orientation; var w = n.getData('width') + siblingOffset; var h = n.getData('height') + siblingOffset; @@ -9390,10 +9390,10 @@ $jit.ST.Geom = new Class({ else return this.dispatch(s, w, h); }, - + /* Calculates a subtree base size. This is an utility function used by _getBaseSize_ - */ + */ getTreeBaseSize: function(node, level, leaf) { var size = this.getSize(node, true), baseHeight = 0, that = this; if(leaf(level, node)) return size; @@ -9407,7 +9407,7 @@ $jit.ST.Geom = new Class({ /* getEdge - + Returns a Complex instance with the begin or end position of the edge to be plotted. Parameters: @@ -9418,12 +9418,12 @@ $jit.ST.Geom = new Class({ Returns: A number specifying the begin or end position. - */ + */ getEdge: function(node, type, s) { - var $C = function(a, b) { + var $C = function(a, b) { return function(){ return node.pos.add(new Complex(a, b)); - }; + }; }; var dim = this.node; var w = node.getData('width'); @@ -9440,8 +9440,8 @@ $jit.ST.Geom = new Class({ return this.dispatch(s, $C(0, 0), $C(-w, 0), $C(0, -h),$C(0, 0)); } else throw "align: not implemented"; - - + + } else if(type == 'end') { if(dim.align == "center") { return this.dispatch(s, $C(0, -h/2), $C(w/2, 0), @@ -9458,19 +9458,19 @@ $jit.ST.Geom = new Class({ /* Adjusts the tree position due to canvas scaling or translation. - */ + */ getScaledTreePosition: function(node, scale) { var dim = this.node; var w = node.getData('width'); var h = node.getData('height'); - var s = (this.config.multitree - && ('$orn' in node.data) + var s = (this.config.multitree + && ('$orn' in node.data) && node.data.$orn) || this.config.orientation; - var $C = function(a, b) { + var $C = function(a, b) { return function(){ return node.pos.add(new Complex(a, b)).$scale(1 - scale); - }; + }; }; if(dim.align == "left") { return this.dispatch(s, $C(0, h), $C(0, 0), @@ -9486,7 +9486,7 @@ $jit.ST.Geom = new Class({ /* treeFitsInCanvas - + Returns a Boolean if the current subtree fits in canvas. Parameters: @@ -9494,15 +9494,15 @@ $jit.ST.Geom = new Class({ node - A which is the current root of the subtree. canvas - The object. level - The depth of the subtree to be considered. - */ + */ treeFitsInCanvas: function(node, canvas, level) { var csize = canvas.getSize(); - var s = (this.config.multitree - && ('$orn' in node.data) + var s = (this.config.multitree + && ('$orn' in node.data) && node.data.$orn) || this.config.orientation; var size = this.dispatch(s, csize.width, csize.height); - var baseSize = this.getTreeBaseSize(node, level, function(level, node) { + var baseSize = this.getTreeBaseSize(node, level, function(level, node) { return level === 0 || !node.anySubnode(); }); return (baseSize < size); @@ -9511,22 +9511,22 @@ $jit.ST.Geom = new Class({ /* Class: ST.Plot - + Custom extension of . Extends: All methods - + See also: - + */ $jit.ST.Plot = new Class({ - + Implements: Graph.Plot, - + /* Plots a subtree from the spacetree. */ @@ -9534,7 +9534,7 @@ $jit.ST.Plot = new Class({ var viz = this.viz, canvas = viz.canvas, config = viz.config; scale = Math.min(Math.max(0.001, scale), 1); if(scale >= 0) { - node.drawn = false; + node.drawn = false; var ctx = canvas.getCtx(); var diff = viz.geom.getScaledTreePosition(node, scale); ctx.translate(diff.x, diff.y); @@ -9550,19 +9550,19 @@ $jit.ST.Plot = new Class({ } }), animating); if(scale >= 0) node.drawn = true; - }, - + }, + /* Method: getAlignedPos - + Returns a *x, y* object with the position of the top/left corner of a node. - + Parameters: - + pos - (object) A position. width - (number) The width of the node. height - (number) The height of the node. - + */ getAlignedPos: function(pos, width, height) { var nconfig = this.node; @@ -9599,10 +9599,10 @@ $jit.ST.Plot = new Class({ }; } } else throw "align: not implemented"; - + return square; }, - + getOrientation: function(adj) { var config = this.config; var orn = config.orientation; @@ -9610,20 +9610,20 @@ $jit.ST.Plot = new Class({ if(config.multitree) { var nodeFrom = adj.nodeFrom; var nodeTo = adj.nodeTo; - orn = (('$orn' in nodeFrom.data) - && nodeFrom.data.$orn) - || (('$orn' in nodeTo.data) + orn = (('$orn' in nodeFrom.data) + && nodeFrom.data.$orn) + || (('$orn' in nodeTo.data) && nodeTo.data.$orn); } - return orn; + return orn; } }); /* Class: ST.Label - Custom extension of . + Custom extension of . Contains custom , and extensions. Extends: @@ -9633,7 +9633,7 @@ $jit.ST.Plot = new Class({ See also: , , , . - */ + */ $jit.ST.Label = {}; /* @@ -9665,7 +9665,7 @@ $jit.ST.Label.Native = new Class({ $jit.ST.Label.DOM = new Class({ Implements: Graph.Label.DOM, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -9675,18 +9675,18 @@ $jit.ST.Label.DOM = new Class({ tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller) { - var pos = node.pos.getc(true), - config = this.viz.config, - dim = config.Node, + var pos = node.pos.getc(true), + config = this.viz.config, + dim = config.Node, canvas = this.viz.canvas, w = node.getData('width'), h = node.getData('height'), radius = canvas.getSize(), labelPos, orn; - + var ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, sx = canvas.scaleOffsetX, @@ -9782,7 +9782,7 @@ $jit.ST.Label.HTML = new Class({ /* Class: ST.Plot.NodeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Node types implemented are 'none', 'circle', 'rectangle', 'ellipse' and 'square'. You can add your custom node types, customizing your visualization to the extreme. @@ -9870,7 +9870,7 @@ $jit.ST.Plot.NodeTypes = new Class({ /* Class: ST.Plot.EdgeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Edge types implemented are 'none', 'line', 'arrow', 'quadratic:begin', 'quadratic:end', 'bezier'. You can add your custom edge types, customizing your visualization to the extreme. @@ -9897,7 +9897,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ 'line': { 'render': function(adj, canvas) { var orn = this.getOrientation(adj), - nodeFrom = adj.nodeFrom, + nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo, rel = nodeFrom._depth < nodeTo._depth, from = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), @@ -9906,7 +9906,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ }, 'contains': function(adj, pos) { var orn = this.getOrientation(adj), - nodeFrom = adj.nodeFrom, + nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo, rel = nodeFrom._depth < nodeTo._depth, from = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), @@ -9917,7 +9917,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ 'arrow': { 'render': function(adj, canvas) { var orn = this.getOrientation(adj), - node = adj.nodeFrom, + node = adj.nodeFrom, child = adj.nodeTo, dim = adj.getData('dim'), from = this.viz.geom.getEdge(node, 'begin', orn), @@ -9928,7 +9928,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ }, 'contains': function(adj, pos) { var orn = this.getOrientation(adj), - nodeFrom = adj.nodeFrom, + nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo, rel = nodeFrom._depth < nodeTo._depth, from = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), @@ -9939,7 +9939,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ 'quadratic:begin': { 'render': function(adj, canvas) { var orn = this.getOrientation(adj); - var nodeFrom = adj.nodeFrom, + var nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo, rel = nodeFrom._depth < nodeTo._depth, begin = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), @@ -9968,7 +9968,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ 'quadratic:end': { 'render': function(adj, canvas) { var orn = this.getOrientation(adj); - var nodeFrom = adj.nodeFrom, + var nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo, rel = nodeFrom._depth < nodeTo._depth, begin = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), @@ -9997,7 +9997,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ 'bezier': { 'render': function(adj, canvas) { var orn = this.getOrientation(adj), - nodeFrom = adj.nodeFrom, + nodeFrom = adj.nodeFrom, nodeTo = adj.nodeTo, rel = nodeFrom._depth < nodeTo._depth, begin = this.viz.geom.getEdge(rel? nodeFrom:nodeTo, 'begin', orn), @@ -10035,7 +10035,7 @@ $jit.ST.Plot.EdgeTypes = new Class({ $jit.ST.Plot.NodeTypes.implement({ 'areachart-stacked' : { 'render' : function(node, canvas) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), width = node.getData('width'), height = node.getData('height'), algnPos = this.getAlignedPos(pos, width, height), @@ -10064,11 +10064,11 @@ $jit.ST.Plot.NodeTypes.implement({ h2 = acumRight + dimArray[i][1], alpha = Math.atan((h2 - h1) / width), delta = 55; - var linear = ctx.createLinearGradient(x + width/2, + var linear = ctx.createLinearGradient(x + width/2, y - (h1 + h2)/2, x + width/2 + delta * Math.sin(alpha), y - (h1 + h2)/2 + delta * Math.cos(alpha)); - var color = $.rgbToHex($.map($.hexToRgb(colorArray[i % colorLength].slice(1)), + var color = $.rgbToHex($.map($.hexToRgb(colorArray[i % colorLength].slice(1)), function(v) { return (v * 0.85) >> 0; })); linear.addColorStop(0, colorArray[i % colorLength]); linear.addColorStop(1, color); @@ -10085,7 +10085,7 @@ $jit.ST.Plot.NodeTypes.implement({ if(border) { var strong = border.name == stringArray[i]; var perc = strong? 0.7 : 0.8; - var color = $.rgbToHex($.map($.hexToRgb(colorArray[i % colorLength].slice(1)), + var color = $.rgbToHex($.map($.hexToRgb(colorArray[i % colorLength].slice(1)), function(v) { return (v * perc) >> 0; })); ctx.strokeStyle = color; ctx.lineWidth = strong? 4 : 1; @@ -10103,7 +10103,7 @@ $jit.ST.Plot.NodeTypes.implement({ } acumLeft += (dimArray[i][0] || 0); acumRight += (dimArray[i][1] || 0); - + if(dimArray[i][0] > 0) valAcum += (valArray[i][0] || 0); } @@ -10126,7 +10126,7 @@ $jit.ST.Plot.NodeTypes.implement({ } }, 'contains': function(node, mpos) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), width = node.getData('width'), height = node.getData('height'), algnPos = this.getAlignedPos(pos, width, height), @@ -10161,11 +10161,11 @@ $jit.ST.Plot.NodeTypes.implement({ /* Class: AreaChart - + A visualization that displays stacked area charts. - + Constructor Options: - + See . */ @@ -10174,9 +10174,9 @@ $jit.AreaChart = new Class({ colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"], selected: {}, busy: false, - + initialize: function(opt) { - this.controller = this.config = + this.controller = this.config = $.merge(Options("Canvas", "Margin", "Label", "AreaChart"), { Label: { type: 'Native' } }, opt); @@ -10187,10 +10187,10 @@ $jit.AreaChart = new Class({ typeAggregates = $.type(showAggregates); this.config.showLabels = typeLabels == 'function'? showLabels : $.lambda(showLabels); this.config.showAggregates = typeAggregates == 'function'? showAggregates : $.lambda(showAggregates); - + this.initializeViz(); }, - + initializeViz: function() { var config = this.config, that = this, @@ -10287,11 +10287,11 @@ $jit.AreaChart = new Class({ wrapperStyle.color = labelConf.color; wrapperStyle.textAlign = 'center'; aggregateStyle.position = labelStyle.position = 'absolute'; - + domElement.style.width = node.getData('width') + 'px'; domElement.style.height = node.getData('height') + 'px'; label.innerHTML = node.name; - + domElement.appendChild(wrapper); } }, @@ -10309,7 +10309,7 @@ $jit.AreaChart = new Class({ acumRight = $.reduce(valArray, function(x, y) { return x + y[1]; }, 0), font = parseInt(wrapperStyle.fontSize, 10), domStyle = domElement.style; - + if(dimArray && valArray) { if(config.showLabels(node.name, acumLeft, acumRight, node)) { labelStyle.display = ''; @@ -10338,41 +10338,41 @@ $jit.AreaChart = new Class({ } } }); - + var size = delegate.canvas.getSize(), margin = config.Margin; - delegate.config.offsetY = -size.height/2 + margin.bottom + delegate.config.offsetY = -size.height/2 + margin.bottom + (config.showLabels && (config.labelOffset + config.Label.size)); delegate.config.offsetX = (margin.right - margin.left)/2; this.delegate = delegate; this.canvas = this.delegate.canvas; }, - + /* Method: loadJSON - - Loads JSON data into the visualization. - + + Loads JSON data into the visualization. + Parameters: - + json - The JSON data format. This format is described in . - + Example: (start code js) var areaChart = new $jit.AreaChart(options); areaChart.loadJSON(json); (end code) - */ + */ loadJSON: function(json) { - var prefix = $.time(), - ch = [], + var prefix = $.time(), + ch = [], delegate = this.delegate, - name = $.splat(json.label), + name = $.splat(json.label), color = $.splat(json.color || this.colors), config = this.config, gradient = !!config.type.split(":")[1], animate = config.animate; - + for(var i=0, values=json.values, l=values.length; i. onComplete - (object) A callback object to be called when the animation transition when updating the data end. - + Example: - + (start code js) areaChart.updateJSON(json, { onComplete: function() { @@ -10436,11 +10436,11 @@ $jit.AreaChart = new Class({ } }); (end code) - */ + */ updateJSON: function(json, onComplete) { if(this.busy) return; this.busy = true; - + var delegate = this.delegate, graph = delegate.graph, labels = json.label && $.splat(json.label), @@ -10453,13 +10453,13 @@ $jit.AreaChart = new Class({ for (var i = 0, l = values.length; i < l; i++) { hashValues[values[i].label] = values[i]; } - + graph.eachNode(function(n) { var v = hashValues[n.name], stringArray = n.getData('stringArray'), valArray = n.getData('valueArray'), next = n.getData('next'); - + if (v) { v.values = $.splat(v.values); $.each(valArray, function(a, i) { @@ -10468,7 +10468,7 @@ $jit.AreaChart = new Class({ }); n.setData('valueArray', valArray); } - + if(next) { v = hashValues[next]; if(v) { @@ -10492,19 +10492,19 @@ $jit.AreaChart = new Class({ }); } }, - + /* Method: filter - + Filter selected stacks, collapsing all other stacks. You can filter multiple stacks at the same time. - + Parameters: - + filters - (array) An array of strings with the name of the stacks to be filtered. - callback - (object) An object with an *onComplete* callback method. - + callback - (object) An object with an *onComplete* callback method. + Example: - + (start code js) areaChart.filter(['label A', 'label C'], { onComplete: function() { @@ -10512,11 +10512,11 @@ $jit.AreaChart = new Class({ } }); (end code) - + See also: - + . - */ + */ filter: function(filters, callback) { if(this.busy) return; this.busy = true; @@ -10527,7 +10527,7 @@ $jit.AreaChart = new Class({ var that = this; this.normalizeDims(); rt.eachAdjacency(function(adj) { - var n = adj.nodeTo, + var n = adj.nodeTo, dimArray = n.getData('dimArray', 'end'), stringArray = n.getData('stringArray'); n.setData('dimArray', $.map(dimArray, function(d, i) { @@ -10543,22 +10543,22 @@ $jit.AreaChart = new Class({ } }); }, - + /* Method: restore - + Sets all stacks that could have been filtered visible. - + Example: - + (start code js) areaChart.restore(); (end code) - + See also: - + . - */ + */ restore: function(callback) { if(this.busy) return; this.busy = true; @@ -10579,7 +10579,7 @@ $jit.AreaChart = new Class({ select: function(id, name, index) { if(!this.config.selectOnHover) return; var s = this.selected; - if(s.id != id || s.name != name + if(s.id != id || s.name != name || s.index != index) { s.id = id; s.name = name; @@ -10605,18 +10605,18 @@ $jit.AreaChart = new Class({ this.delegate.plot(); } }, - + /* Method: getLegend - + Returns an object containing as keys the legend names and as values hex strings with color values. - + Example: - + (start code js) var legend = areaChart.getLegend(); (end code) - */ + */ getLegend: function() { var legend = {}; var n; @@ -10630,22 +10630,22 @@ $jit.AreaChart = new Class({ }); return legend; }, - + /* Method: getMaxValue - + Returns the maximum accumulated value for the stacks. This method is used for normalizing the graph heights according to the canvas height. - + Example: - + (start code js) var ans = areaChart.getMaxValue(); (end code) - + In some cases it could be useful to override this method to normalize heights for a group of AreaCharts, like when doing small multiples. - + Example: - + (start code js) //will return 100 for all AreaChart instances, //displaying all of them with the same scale @@ -10655,14 +10655,14 @@ $jit.AreaChart = new Class({ } }); (end code) - -*/ + +*/ getMaxValue: function() { var maxValue = 0; this.delegate.graph.eachNode(function(n) { var valArray = n.getData('valueArray'), acumLeft = 0, acumRight = 0; - $.each(valArray, function(v) { + $.each(valArray, function(v) { acumLeft += +v[0]; acumRight += +v[1]; }); @@ -10671,7 +10671,7 @@ $jit.AreaChart = new Class({ }); return maxValue; }, - + normalizeDims: function() { //number of elements var root = this.delegate.graph.getNode(this.delegate.root), l=0; @@ -10685,7 +10685,7 @@ $jit.AreaChart = new Class({ labelOffset = config.labelOffset + config.Label.size, fixedDim = (size.width - (margin.left + margin.right)) / l, animate = config.animate, - height = size.height - (margin.top + margin.bottom) - (config.showAggregates && labelOffset) + height = size.height - (margin.top + margin.bottom) - (config.showAggregates && labelOffset) - (config.showLabels && labelOffset); this.delegate.graph.eachNode(function(n) { var acumLeft = 0, acumRight = 0, animateValue = []; @@ -10698,8 +10698,8 @@ $jit.AreaChart = new Class({ n.setData('width', fixedDim); if(animate) { n.setData('height', acum * height / maxValue, 'end'); - n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { - return [n[0] * height / maxValue, n[1] * height / maxValue]; + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return [n[0] * height / maxValue, n[1] * height / maxValue]; }), 'end'); var dimArray = n.getData('dimArray'); if(!dimArray) { @@ -10707,8 +10707,8 @@ $jit.AreaChart = new Class({ } } else { n.setData('height', acum * height / maxValue); - n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { - return [n[0] * height / maxValue, n[1] * height / maxValue]; + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return [n[0] * height / maxValue, n[1] * height / maxValue]; })); } }); @@ -10723,12 +10723,12 @@ $jit.AreaChart = new Class({ /* Object: Options.BarChart - - options. + + options. Other options included in the BarChart are , , , and . - + Syntax: - + (start code js) Options.BarChart = { @@ -10741,11 +10741,11 @@ $jit.AreaChart = new Class({ showAggregates: true, showLabels: true }; - + (end code) - + Example: - + (start code js) var barChart = new $jit.BarChart({ @@ -10753,11 +10753,11 @@ $jit.AreaChart = new Class({ barsOffset: 10, type: 'stacked:gradient' }); - + (end code) Parameters: - + animate - (boolean) Default's *true*. Whether to add animated transitions when filtering/restoring stacks. offset - (number) Default's *25*. Adds margin between the visualization and the canvas. labelOffset - (number) Default's *3*. Adds margin between the label and the default place where it should be drawn. @@ -10767,12 +10767,12 @@ $jit.AreaChart = new Class({ orientation - (string) Default's 'horizontal'. Sets the direction of the bars. Possible options are 'vertical' or 'horizontal'. showAggregates - (boolean, function) Default's *true*. Display the sum the values of each bar. Can also be a function that returns *true* or *false* to display the value of the bar or not. That same function can also return a string with the formatted data to be added. showLabels - (boolean, function) Default's *true*. Display the name of the slots. Can also be a function that returns *true* or *false* for each bar to decide whether to show the label or not. - + */ Options.BarChart = { $extend: true, - + animate: true, type: 'stacked', //stacked, grouped, : gradient labelOffset: 3, //label offset @@ -10800,7 +10800,7 @@ Options.BarChart = { $jit.ST.Plot.NodeTypes.implement({ 'barchart-stacked' : { 'render' : function(node, canvas) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), width = node.getData('width'), height = node.getData('height'), algnPos = this.getAlignedPos(pos, width, height), @@ -10820,20 +10820,20 @@ $jit.ST.Plot.NodeTypes.implement({ aggregates = config.showAggregates, showLabels = config.showLabels, label = config.Label; - + if (colorArray && dimArray && stringArray) { for (var i=0, l=dimArray.length, acum=0, valAcum=0; i> 0; })); linear.addColorStop(0, color); linear.addColorStop(0.5, colorArray[i % colorLength]); @@ -10895,7 +10895,7 @@ $jit.ST.Plot.NodeTypes.implement({ } }, 'contains': function(node, mpos) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), width = node.getData('width'), height = node.getData('height'), algnPos = this.getAlignedPos(pos, width, height), @@ -10948,7 +10948,7 @@ $jit.ST.Plot.NodeTypes.implement({ }, 'barchart-grouped' : { 'render' : function(node, canvas) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), width = node.getData('width'), height = node.getData('height'), algnPos = this.getAlignedPos(pos, width, height), @@ -10958,7 +10958,7 @@ $jit.ST.Plot.NodeTypes.implement({ valueLength = valueArray.length, colorArray = node.getData('colorArray'), colorLength = colorArray.length, - stringArray = node.getData('stringArray'); + stringArray = node.getData('stringArray'); var ctx = canvas.getCtx(), opt = {}, @@ -10970,20 +10970,20 @@ $jit.ST.Plot.NodeTypes.implement({ showLabels = config.showLabels, label = config.Label, fixedDim = (horz? height : width) / valueLength; - + if (colorArray && dimArray && stringArray) { for (var i=0, l=valueLength, acum=0, valAcum=0; i> 0; })); linear.addColorStop(0, color); linear.addColorStop(0.5, colorArray[i % colorLength]); @@ -11045,7 +11045,7 @@ $jit.ST.Plot.NodeTypes.implement({ } }, 'contains': function(node, mpos) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), width = node.getData('width'), height = node.getData('height'), algnPos = this.getAlignedPos(pos, width, height), @@ -11100,11 +11100,11 @@ $jit.ST.Plot.NodeTypes.implement({ /* Class: BarChart - + A visualization that displays stacked bar charts. - + Constructor Options: - + See . */ @@ -11113,9 +11113,9 @@ $jit.BarChart = new Class({ colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"], selected: {}, busy: false, - + initialize: function(opt) { - this.controller = this.config = + this.controller = this.config = $.merge(Options("Canvas", "Margin", "Label", "BarChart"), { Label: { type: 'Native' } }, opt); @@ -11126,16 +11126,16 @@ $jit.BarChart = new Class({ typeAggregates = $.type(showAggregates); this.config.showLabels = typeLabels == 'function'? showLabels : $.lambda(showLabels); this.config.showAggregates = typeAggregates == 'function'? showAggregates : $.lambda(showAggregates); - + this.initializeViz(); }, - + initializeViz: function() { var config = this.config, that = this; var nodeType = config.type.split(":")[0], horz = config.orientation == 'horizontal', nodeLabels = {}; - + var delegate = new $jit.ST({ injectInto: config.injectInto, width: config.width, @@ -11144,7 +11144,7 @@ $jit.BarChart = new Class({ levelDistance: 0, siblingOffset: config.barsOffset, subtreeOffset: 0, - withLabels: config.Label.type != 'Native', + withLabels: config.Label.type != 'Native', useCanvas: config.useCanvas, Label: { type: config.Label.type @@ -11219,13 +11219,13 @@ $jit.BarChart = new Class({ wrapperStyle.color = labelConf.color; wrapperStyle.textAlign = 'center'; aggregateStyle.position = labelStyle.position = 'absolute'; - + domElement.style.width = node.getData('width') + 'px'; domElement.style.height = node.getData('height') + 'px'; aggregateStyle.left = labelStyle.left = '0px'; label.innerHTML = node.name; - + domElement.appendChild(wrapper); }, onPlaceLabel: function(domElement, node) { @@ -11242,8 +11242,8 @@ $jit.BarChart = new Class({ height = (grouped && !horz)? Math.max.apply(null, dimArray) : node.getData('height'), font = parseInt(wrapperStyle.fontSize, 10), domStyle = domElement.style; - - + + if(dimArray && valArray) { wrapperStyle.width = aggregateStyle.width = labelStyle.width = domElement.style.width = width + 'px'; for(var i=0, l=valArray.length, acum=0; i. - + Example: (start code js) var barChart = new $jit.BarChart(options); barChart.loadJSON(json); (end code) - */ + */ loadJSON: function(json) { if(this.busy) return; this.busy = true; - - var prefix = $.time(), - ch = [], + + var prefix = $.time(), + ch = [], delegate = this.delegate, - name = $.splat(json.label), + name = $.splat(json.label), color = $.splat(json.color || this.colors), config = this.config, gradient = !!config.type.split(":")[1], animate = config.animate, horz = config.orientation == 'horizontal', that = this; - + for(var i=0, values=json.values, l=values.length; i. onComplete - (object) A callback object to be called when the animation transition when updating the data end. - + Example: - + (start code js) barChart.updateJSON(json, { onComplete: function() { @@ -11399,7 +11399,7 @@ $jit.BarChart = new Class({ } }); (end code) - */ + */ updateJSON: function(json, onComplete) { if(this.busy) return; this.busy = true; @@ -11444,7 +11444,7 @@ $jit.BarChart = new Class({ } } }, - + //adds the little brown bar when hovering the node select: function(id, name) { if(!this.config.hoveredColor) return; @@ -11463,18 +11463,18 @@ $jit.BarChart = new Class({ this.delegate.plot(); } }, - + /* Method: getLegend - + Returns an object containing as keys the legend names and as values hex strings with color values. - + Example: - + (start code js) var legend = barChart.getLegend(); (end code) - */ + */ getLegend: function() { var legend = {}; var n; @@ -11488,22 +11488,22 @@ $jit.BarChart = new Class({ }); return legend; }, - + /* Method: getMaxValue - + Returns the maximum accumulated value for the stacks. This method is used for normalizing the graph heights according to the canvas height. - + Example: - + (start code js) var ans = barChart.getMaxValue(); (end code) - + In some cases it could be useful to override this method to normalize heights for a group of BarCharts, like when doing small multiples. - + Example: - + (start code js) //will return 100 for all BarChart instances, //displaying all of them with the same scale @@ -11513,8 +11513,8 @@ $jit.BarChart = new Class({ } }); (end code) - - */ + + */ getMaxValue: function() { var maxValue = 0, stacked = this.config.type.split(':')[0] == 'stacked'; this.delegate.graph.eachNode(function(n) { @@ -11522,7 +11522,7 @@ $jit.BarChart = new Class({ acum = 0; if(!valArray) return; if(stacked) { - $.each(valArray, function(v) { + $.each(valArray, function(v) { acum += +v; }); } else { @@ -11532,12 +11532,12 @@ $jit.BarChart = new Class({ }); return maxValue; }, - + setBarType: function(type) { this.config.type = type; this.delegate.config.Node.type = 'barchart-' + type.split(':')[0]; }, - + normalizeDims: function() { //number of elements var root = this.delegate.graph.getNode(this.delegate.root), l=0; @@ -11553,7 +11553,7 @@ $jit.BarChart = new Class({ horz = config.orientation == 'horizontal', fixedDim = (size[horz? 'height':'width'] - (horz? marginHeight:marginWidth) - (l -1) * config.barsOffset) / l, animate = config.animate, - height = size[horz? 'width':'height'] - (horz? marginWidth:marginHeight) + height = size[horz? 'width':'height'] - (horz? marginWidth:marginHeight) - (!horz && config.showAggregates && (config.Label.size + config.labelOffset)) - (config.showLabels && (config.Label.size + config.labelOffset)), dim1 = horz? 'height':'width', @@ -11567,8 +11567,8 @@ $jit.BarChart = new Class({ n.setData(dim1, fixedDim); if(animate) { n.setData(dim2, acum * height / maxValue, 'end'); - n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { - return n * height / maxValue; + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return n * height / maxValue; }), 'end'); var dimArray = n.getData('dimArray'); if(!dimArray) { @@ -11576,8 +11576,8 @@ $jit.BarChart = new Class({ } } else { n.setData(dim2, acum * height / maxValue); - n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { - return n * height / maxValue; + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return n * height / maxValue; })); } }); @@ -11591,12 +11591,12 @@ $jit.BarChart = new Class({ */ /* Object: Options.PieChart - - options. + + options. Other options included in the PieChart are , , and . - + Syntax: - + (start code js) Options.PieChart = { @@ -11609,24 +11609,24 @@ $jit.BarChart = new Class({ showLabels: true, resizeLabels: false, updateHeights: false - }; + }; (end code) - + Example: - + (start code js) var pie = new $jit.PieChart({ animate: true, sliceOffset: 5, type: 'stacked:gradient' - }); + }); (end code) - + Parameters: - + animate - (boolean) Default's *true*. Whether to add animated transitions when plotting/updating the visualization. offset - (number) Default's *25*. Adds margin between the visualization and the canvas. sliceOffset - (number) Default's *0*. Separation between the center of the canvas and each pie slice. @@ -11658,46 +11658,46 @@ Options.PieChart = { }, showLabels: true, resizeLabels: false, - + //only valid for mono-valued datasets updateHeights: false }; /* * Class: Layouts.Radial - * + * * Implements a Radial Layout. - * + * * Implemented By: - * + * * , - * + * */ Layouts.Radial = new Class({ /* * Method: compute - * + * * Computes nodes' positions. - * + * * Parameters: - * + * * property - _optional_ A position property to store the new * positions. Possible values are 'pos', 'end' or 'start'. - * + * */ compute : function(property) { var prop = $.splat(property || [ 'current', 'start', 'end' ]); NodeDim.compute(this.graph, prop, this.config); this.graph.computeLevels(this.root, 0, "ignore"); - var lengthFunc = this.createLevelDistanceFunc(); + var lengthFunc = this.createLevelDistanceFunc(); this.computeAngularWidths(prop); this.computePositions(prop, lengthFunc); }, /* * computePositions - * + * * Performs the main algorithm for computing node positions. */ computePositions : function(property, getLength) { @@ -11767,7 +11767,7 @@ Layouts.Radial = new Class({ /* * Method: setAngularWidthForNodes - * + * * Sets nodes angular widths. */ setAngularWidthForNodes : function(prop) { @@ -11779,7 +11779,7 @@ Layouts.Radial = new Class({ /* * Method: setSubtreesAngularWidth - * + * * Sets subtrees angular widths. */ setSubtreesAngularWidth : function() { @@ -11791,7 +11791,7 @@ Layouts.Radial = new Class({ /* * Method: setSubtreeAngularWidth - * + * * Sets the angular width for a subtree. */ setSubtreeAngularWidth : function(elem) { @@ -11805,7 +11805,7 @@ Layouts.Radial = new Class({ /* * Method: computeAngularWidths - * + * * Computes nodes and subtrees angular widths. */ computeAngularWidths : function(prop) { @@ -11822,25 +11822,25 @@ Layouts.Radial = new Class({ /* Class: Sunburst - + A radial space filling tree visualization. - + Inspired by: - + Sunburst . - + Note: - + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the visualization described in the paper. - + Implements: - + All methods - + Constructor Options: - + Inherits options from - + - - - @@ -11850,24 +11850,24 @@ Layouts.Radial = new Class({ - - - - + Additionally, there are other parameters and some default values changed - + interpolation - (string) Default's *linear*. Describes the way nodes are interpolated. Possible values are 'linear' and 'polar'. - levelDistance - (number) Default's *100*. The distance between levels of the tree. + levelDistance - (number) Default's *100*. The distance between levels of the tree. Node.type - Described in . Default's to *multipie*. Node.height - Described in . Default's *0*. Edge.type - Described in . Default's *none*. Label.textAlign - Described in . Default's *start*. Label.textBaseline - Described in . Default's *middle*. - + Instance Properties: canvas - Access a instance. graph - Access a instance. op - Access a instance. fx - Access a instance. - labels - Access a interface implementation. + labels - Access a interface implementation. */ @@ -11932,14 +11932,14 @@ $jit.Sunburst = new Class({ this.initializeExtras(); }, - /* - - createLevelDistanceFunc - - Returns the levelDistance function used for calculating a node distance - to its origin. This function returns a function that is computed - per level and not per node, such that all nodes with the same depth will have the - same distance to the origin. The resulting function gets the + /* + + createLevelDistanceFunc + + Returns the levelDistance function used for calculating a node distance + to its origin. This function returns a function that is computed + per level and not per node, such that all nodes with the same depth will have the + same distance to the origin. The resulting function gets the parent node as parameter and returns a float. */ @@ -11950,9 +11950,9 @@ $jit.Sunburst = new Class({ }; }, - /* - Method: refresh - + /* + Method: refresh + Computes positions and plots the tree. */ @@ -11963,13 +11963,13 @@ $jit.Sunburst = new Class({ /* reposition - + An alias for computing new positions to _endPos_ See also: - + */ reposition: function() { this.compute('end'); @@ -11977,19 +11977,19 @@ $jit.Sunburst = new Class({ /* Method: rotate - + Rotates the graph so that the selected node is horizontal on the right. Parameters: - + node - (object) A . method - (string) Whether to perform an animation or just replot the graph. Possible values are "replot" or "animate". opt - (object) Configuration options merged with this visualization configuration options. - + See also: - + */ rotate: function(node, method, opt) { var theta = node.getPos(opt.property || 'current').getp(true).theta; @@ -11999,19 +11999,19 @@ $jit.Sunburst = new Class({ /* Method: rotateAngle - + Rotates the graph of an angle theta. - + Parameters: - + node - (object) A . method - (string) Whether to perform an animation or just replot the graph. Possible values are "replot" or "animate". opt - (object) Configuration options merged with this visualization configuration options. - + See also: - + */ rotateAngle: function(theta, method, opt) { var that = this; @@ -12039,7 +12039,7 @@ $jit.Sunburst = new Class({ /* Method: plot - + Plots the Sunburst. This is a shortcut to *fx.plot*. */ plot: function() { @@ -12059,9 +12059,9 @@ $jit.Sunburst.$extend = true; Extends: All methods - + See also: - + */ @@ -12075,15 +12075,15 @@ $jit.Sunburst.$extend = true; Class: Sunburst.Plot Custom extension of . - + Extends: - + All methods - + See also: - + - + */ Sunburst.Plot = new Class( { @@ -12094,17 +12094,17 @@ $jit.Sunburst.$extend = true; /* Class: Sunburst.Label - Custom extension of . + Custom extension of . Contains custom , and extensions. - + Extends: - + All methods and subclasses. - + See also: - + , , , . - + */ Sunburst.Label = {}; @@ -12132,7 +12132,7 @@ $jit.Sunburst.$extend = true; renderLabel: function(canvas, node, controller) { var span = node.getData('span'); - if(span < Math.PI /2 && Math.tan(span) * + if(span < Math.PI /2 && Math.tan(span) * this.config.levelDistance * node._depth < 10) { return; } @@ -12172,15 +12172,15 @@ $jit.Sunburst.$extend = true; Sunburst.Label.SVG Custom extension of . - + Extends: - + All methods - + See also: - + - + */ Sunburst.Label.SVG = new Class( { Implements: Graph.Label.SVG, @@ -12189,7 +12189,7 @@ $jit.Sunburst.$extend = true; this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -12199,7 +12199,7 @@ $jit.Sunburst.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller) { var pos = node.pos.getc(true), viz = this.viz, canvas = this.viz.canvas; @@ -12258,7 +12258,7 @@ $jit.Sunburst.$extend = true; initialize: function(viz) { this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -12268,17 +12268,17 @@ $jit.Sunburst.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller) { - var pos = node.pos.clone(), + var pos = node.pos.clone(), canvas = this.viz.canvas, height = node.getData('height'), ldist = ((height || node._depth == 0)? height : this.viz.config.levelDistance) /2, radius = canvas.getSize(); pos.rho += ldist; pos = pos.getc(true); - + var labelPos = { x: Math.round(pos.x + radius.width / 2), y: Math.round(pos.y + radius.height / 2) @@ -12296,7 +12296,7 @@ $jit.Sunburst.$extend = true; /* Class: Sunburst.Plot.NodeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Node types implemented are 'none', 'pie', 'multipie', 'gradient-pie' and 'gradient-multipie'. You can add your custom node types, customizing your visualization to the extreme. @@ -12470,13 +12470,13 @@ $jit.Sunburst.$extend = true; /* Class: Sunburst.Plot.EdgeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Edge types implemented are 'none', 'line' and 'arrow'. - + You can add your custom edge types, customizing your visualization to the extreme. - + Example: - + (start code js) Sunburst.Plot.EdgeTypes.implement({ 'mySpecialType': { @@ -12490,7 +12490,7 @@ $jit.Sunburst.$extend = true; } }); (end code) - + */ Sunburst.Plot.EdgeTypes = new Class({ 'none': $.empty, @@ -12554,8 +12554,8 @@ $jit.Sunburst.Plot.NodeTypes.implement({ begin = theta - span, end = theta + span, polar = new Polar; - - var ctx = canvas.getCtx(), + + var ctx = canvas.getCtx(), opt = {}, gradient = node.getData('gradient'), border = node.getData('border'), @@ -12575,7 +12575,7 @@ $jit.Sunburst.Plot.NodeTypes.implement({ if(gradient && dimi) { var radialGradient = ctx.createRadialGradient(xpos, ypos, acum + config.sliceOffset, xpos, ypos, acum + dimi + config.sliceOffset); - var colorRgb = $.hexToRgb(colori), + var colorRgb = $.hexToRgb(colori), ans = $.map(colorRgb, function(i) { return (i * 0.8) >> 0; }), endColor = $.rgbToHex(ans); @@ -12584,7 +12584,7 @@ $jit.Sunburst.Plot.NodeTypes.implement({ radialGradient.addColorStop(1, endColor); ctx.fillStyle = radialGradient; } - + polar.rho = acum + config.sliceOffset; polar.theta = begin; var p1coord = polar.getc(true); @@ -12629,15 +12629,15 @@ $jit.Sunburst.Plot.NodeTypes.implement({ var scale = resizeLabels? node.getData('normalizedDim') : 1, fontSize = (label.size * scale) >> 0; fontSize = fontSize < +resizeLabels? +resizeLabels : fontSize; - + ctx.font = label.style + ' ' + fontSize + 'px ' + label.family; ctx.textBaseline = 'middle'; ctx.textAlign = 'center'; - + polar.rho = acum + config.labelOffset + config.sliceOffset; polar.theta = node.pos.theta; var cart = polar.getc(true); - + ctx.fillText(node.name, cart.x, cart.y); ctx.restore(); } @@ -12664,7 +12664,7 @@ $jit.Sunburst.Plot.NodeTypes.implement({ } } return false; - + } return false; } @@ -12673,11 +12673,11 @@ $jit.Sunburst.Plot.NodeTypes.implement({ /* Class: PieChart - + A visualization that displays stacked bar charts. - + Constructor Options: - + See . */ @@ -12686,15 +12686,15 @@ $jit.PieChart = new Class({ colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"], selected: {}, busy: false, - + initialize: function(opt) { - this.controller = this.config = + this.controller = this.config = $.merge(Options("Canvas", "PieChart", "Label"), { Label: { type: 'Native' } }, opt); this.initializeViz(); }, - + initializeViz: function() { var config = this.config, that = this; var nodeType = config.type.split(":")[0]; @@ -12763,11 +12763,11 @@ $jit.PieChart = new Class({ begin = theta - span, end = theta + span, polar = new Polar; - + var showLabels = config.showLabels, resizeLabels = config.resizeLabels, label = config.Label; - + if (dimArray) { for (var i=0, l=dimArray.length, acum=0; i. - + Example: (start code js) var pieChart = new $jit.PieChart(options); pieChart.loadJSON(json); (end code) - */ + */ loadJSON: function(json) { - var prefix = $.time(), - ch = [], + var prefix = $.time(), + ch = [], delegate = this.delegate, name = $.splat(json.label), nameLength = name.length, @@ -12826,7 +12826,7 @@ $jit.PieChart = new Class({ gradient = !!config.type.split(":")[1], animate = config.animate, mono = nameLength == 1; - + for(var i=0, values=json.values, l=values.length; i. onComplete - (object) A callback object to be called when the animation transition when updating the data end. - + Example: - + (start code js) pieChart.updateJSON(json, { onComplete: function() { @@ -12886,11 +12886,11 @@ $jit.PieChart = new Class({ } }); (end code) - */ + */ updateJSON: function(json, onComplete) { if(this.busy) return; this.busy = true; - + var delegate = this.delegate; var graph = delegate.graph; var values = json.values; @@ -12922,7 +12922,7 @@ $jit.PieChart = new Class({ delegate.refresh(); } }, - + //adds the little brown bar when hovering the node select: function(id, name) { if(!this.config.hoveredColor) return; @@ -12941,18 +12941,18 @@ $jit.PieChart = new Class({ this.delegate.plot(); } }, - + /* Method: getLegend - + Returns an object containing as keys the legend names and as values hex strings with color values. - + Example: - + (start code js) var legend = pieChart.getLegend(); (end code) - */ + */ getLegend: function() { var legend = {}; var n; @@ -12966,22 +12966,22 @@ $jit.PieChart = new Class({ }); return legend; }, - + /* Method: getMaxValue - + Returns the maximum accumulated value for the stacks. This method is used for normalizing the graph heights according to the canvas height. - + Example: - + (start code js) var ans = pieChart.getMaxValue(); (end code) - + In some cases it could be useful to override this method to normalize heights for a group of PieCharts, like when doing small multiples. - + Example: - + (start code js) //will return 100 for all PieChart instances, //displaying all of them with the same scale @@ -12991,21 +12991,21 @@ $jit.PieChart = new Class({ } }); (end code) - - */ + + */ getMaxValue: function() { var maxValue = 0; this.delegate.graph.eachNode(function(n) { var valArray = n.getData('valueArray'), acum = 0; - $.each(valArray, function(v) { + $.each(valArray, function(v) { acum += +v; }); maxValue = maxValue>acum? maxValue:acum; }); return maxValue; }, - + normalizeDims: function() { //number of elements var root = this.delegate.graph.getNode(this.delegate.root), l=0; @@ -13024,16 +13024,16 @@ $jit.PieChart = new Class({ }); var stat = (animateValue.length == 1) && !config.updateHeights; if(animate) { - n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { - return stat? rho: (n * rho / maxValue); + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return stat? rho: (n * rho / maxValue); }), 'end'); var dimArray = n.getData('dimArray'); if(!dimArray) { n.setData('dimArray', animateValue); } } else { - n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { - return stat? rho : (n * rho / maxValue); + n.setData('dimArray', $.map(n.getData('valueArray'), function(n) { + return stat? rho : (n * rho / maxValue); })); } n.setData('normalizedDim', acum / maxValue); @@ -13044,13 +13044,13 @@ $jit.PieChart = new Class({ /* * Class: Layouts.TM - * + * * Implements TreeMaps layouts (SliceAndDice, Squarified, Strip). - * + * * Implemented By: - * + * * - * + * */ Layouts.TM = {}; @@ -13070,14 +13070,14 @@ Layouts.TM.SliceAndDice = new Class({ this.computePositions(root, root, this.layout.orientation, prop); this.controller.onAfterCompute(root); }, - + computePositions: function(par, ch, orn, prop) { //compute children areas var totalArea = 0; par.eachSubnode(function(n) { totalArea += n.getData('area', prop); }); - + var config = this.config, offst = config.offset, width = par.getData('width', prop), @@ -13096,7 +13096,7 @@ Layouts.TM.SliceAndDice = new Class({ posth = config.titleHeight; pos2th = 0; } else { - orn = 'h'; + orn = 'h'; otherSize = height * fact; size = width; dim = 'width'; @@ -13123,9 +13123,9 @@ Layouts.TM.SliceAndDice = new Class({ Layouts.TM.Area = { /* Method: compute - + Called by loadJSON to calculate recursively all node positions and lay out the tree. - + Parameters: json - A JSON tree. See also . @@ -13156,17 +13156,17 @@ Layouts.TM.Area = { }; this.computePositions(root, coord, prop); this.controller.onAfterCompute(root); - }, - + }, + /* Method: computeDim - + Computes dimensions and positions of a group of nodes - according to a custom layout row condition. - + according to a custom layout row condition. + Parameters: - tail - An array of nodes. + tail - An array of nodes. initElem - An array of nodes (containing the initial node to be laid). w - A fixed dimension where nodes will be layed out. coord - A coordinates object specifying width, height, left and top style properties. @@ -13194,23 +13194,23 @@ Layouts.TM.Area = { } }, - + /* Method: worstAspectRatio - - Calculates the worst aspect ratio of a group of rectangles. - + + Calculates the worst aspect ratio of a group of rectangles. + See also: - + - + Parameters: - ch - An array of nodes. + ch - An array of nodes. w - The fixed dimension where rectangles are being laid out. Returns: - + The worst aspect ratio. @@ -13220,31 +13220,31 @@ Layouts.TM.Area = { var areaSum = 0, maxArea = 0, minArea = Number.MAX_VALUE; for(var i=0, l=ch.length; i area? maxArea : area; + maxArea = maxArea > area? maxArea : area; } var sqw = w * w, sqAreaSum = areaSum * areaSum; return Math.max(sqw * maxArea / sqAreaSum, sqAreaSum / (sqw * minArea)); }, - + /* Method: avgAspectRatio - - Calculates the average aspect ratio of a group of rectangles. - + + Calculates the average aspect ratio of a group of rectangles. + See also: - + - + Parameters: - ch - An array of nodes. + ch - An array of nodes. w - The fixed dimension where rectangles are being laid out. Returns: - + The average aspect ratio. @@ -13262,12 +13262,12 @@ Layouts.TM.Area = { /* layoutLast - + Performs the layout of the last computed sibling. - + Parameters: - ch - An array of nodes. + ch - An array of nodes. w - A fixed dimension where nodes will be layed out. coord - A coordinates object specifying width, height, left and top style properties. */ @@ -13282,21 +13282,21 @@ Layouts.TM.Area = { Layouts.TM.Squarified = new Class({ Implements: Layouts.TM.Area, - + computePositions: function(node, coord, prop) { - var config = this.config, + var config = this.config, max = Math.max; - - if (coord.width >= coord.height) + + if (coord.width >= coord.height) this.layout.orientation = 'h'; else this.layout.orientation = 'v'; - + var ch = node.getSubnodes([1, 1], "ignore"); if(ch.length > 0) { this.processChildrenLayout(node, ch, coord, prop); for(var i=0, l=ch.length; i. + + json - A JSON subtree. See also . coord - A coordinates object specifying width, height, left and top style properties. */ computePositions: function(node, coord, prop) { - var ch = node.getSubnodes([1, 1], "ignore"), + var ch = node.getSubnodes([1, 1], "ignore"), config = this.config, max = Math.max; if(ch.length > 0) { @@ -13466,15 +13466,15 @@ Layouts.TM.Strip = new Class({ } } }, - + /* Method: processChildrenLayout - + Computes children real areas and other useful parameters for performing the Strip algorithm. - + Parameters: - - par - The parent node of the json subtree. + + par - The parent node of the json subtree. ch - An Array of nodes coord - A coordinates object specifying width, height, left and top style properties. */ @@ -13494,16 +13494,16 @@ Layouts.TM.Strip = new Class({ var tail = ch.slice(1); this.stripify(tail, initElem, side, coord, prop); }, - + /* Method: stripify - - Performs an heuristic method to calculate div elements sizes in order to have + + Performs an heuristic method to calculate div elements sizes in order to have a good compromise between aspect ratio and order. - + Parameters: - - tail - An array of nodes. + + tail - An array of nodes. initElem - An array of nodes. w - A fixed dimension where nodes will be layed out. coord - A coordinates object specifying width, height, left and top style properties. @@ -13511,15 +13511,15 @@ Layouts.TM.Strip = new Class({ stripify: function(tail, initElem, w, coord, prop) { this.computeDim(tail, initElem, w, coord, this.avgAspectRatio, prop); }, - + /* Method: layoutRow - + Performs the layout of an array of nodes. - + Parameters: - - ch - An array of nodes. + + ch - An array of nodes. w - A fixed dimension where nodes will be laid out. coord - A coordinates object specifying width, height, left and top style properties. */ @@ -13530,21 +13530,21 @@ Layouts.TM.Strip = new Class({ return this.layoutV(ch, w, coord, prop); } }, - + layoutV: function(ch, w, coord, prop) { - var totalArea = 0; + var totalArea = 0; $.each(ch, function(elem) { totalArea += elem._area; }); - var width = totalArea / w, top = 0; + var width = totalArea / w, top = 0; for(var i=0, l=ch.length; i methods - + Constructor Options: - + Inherits options from - + - - - @@ -13687,7 +13687,7 @@ Layouts.Icicle = new Class({ - - - - + Additionally, there are other parameters and some default values changed orientation - (string) Default's *h*. Whether to set horizontal or vertical layouts. Possible values are 'h' and 'v'. @@ -13699,9 +13699,9 @@ Layouts.Icicle = new Class({ Label.type - Described in . Default's *Native*. duration - Described in . Default's *700*. fps - Described in . Default's *45*. - + Instance Properties: - + canvas - Access a instance. graph - Access a instance. op - Access a instance. @@ -13782,9 +13782,9 @@ $jit.Icicle = new Class({ this.initializeExtras(); }, - /* - Method: refresh - + /* + Method: refresh + Computes positions and plots the tree. */ refresh: function(){ @@ -13797,25 +13797,25 @@ $jit.Icicle = new Class({ this.plot(); }, - /* - Method: plot - - Plots the Icicle visualization. This is a shortcut to *fx.plot*. - + /* + Method: plot + + Plots the Icicle visualization. This is a shortcut to *fx.plot*. + */ plot: function(){ this.fx.plot(this.config); }, - /* - Method: enter - + /* + Method: enter + Sets the node as root. - + Parameters: - + node - (object) A . - + */ enter: function (node) { if (this.busy) @@ -13872,11 +13872,11 @@ $jit.Icicle = new Class({ } }, - /* - Method: out - + /* + Method: out + Sets the parent node of the current selected node as root. - + */ out: function(){ if(this.busy) @@ -13975,17 +13975,17 @@ $jit.Icicle = new Class({ /* Class: Icicle.Op - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ $jit.Icicle.Op = new Class({ @@ -14037,17 +14037,17 @@ $jit.Icicle.Group = new Class({ /* Class: Icicle.Plot - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ $jit.Icicle.Plot = new Class({ Implements: Graph.Plot, @@ -14073,32 +14073,32 @@ $jit.Icicle.Plot = new Class({ /* Class: Icicle.Label - - Custom extension of . + + Custom extension of . Contains custom , and extensions. - + Extends: - + All methods and subclasses. - + See also: - + , , , . - + */ $jit.Icicle.Label = {}; /* Icicle.Label.Native - + Custom extension of . - + Extends: - + All methods - + See also: - + */ @@ -14125,15 +14125,15 @@ $jit.Icicle.Label.Native = new Class({ /* Icicle.Label.SVG - + Custom extension of . - + Extends: - + All methods - + See also: - + */ $jit.Icicle.Label.SVG = new Class( { @@ -14145,11 +14145,11 @@ $jit.Icicle.Label.SVG = new Class( { /* placeLabel - + Overrides abstract method placeLabel in . - + Parameters: - + tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. @@ -14170,17 +14170,17 @@ $jit.Icicle.Label.SVG = new Class( { /* Icicle.Label.HTML - + Custom extension of . - + Extends: - + All methods. - + See also: - + - + */ $jit.Icicle.Label.HTML = new Class( { Implements: Graph.Label.HTML, @@ -14191,11 +14191,11 @@ $jit.Icicle.Label.HTML = new Class( { /* placeLabel - + Overrides abstract method placeLabel in . - + Parameters: - + tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. @@ -14219,14 +14219,14 @@ $jit.Icicle.Label.HTML = new Class( { /* Class: Icicle.Plot.NodeTypes - - This class contains a list of built-in types. + + This class contains a list of built-in types. Node types implemented are 'none', 'rectangle'. - + You can add your custom node types, customizing your visualization to the extreme. - + Example: - + (start code js) Icicle.Plot.NodeTypes.implement({ 'mySpecialType': { @@ -14240,7 +14240,7 @@ $jit.Icicle.Label.HTML = new Class( { } }); (end code) - + */ $jit.Icicle.Plot.NodeTypes = new Class( { 'none': { @@ -14257,16 +14257,16 @@ $jit.Icicle.Plot.NodeTypes = new Class( { var pos = node.pos.getc(true); var posx = pos.x + offset / 2, posy = pos.y + offset / 2; var ctx = canvas.getCtx(); - + if(width - offset < 2 || height - offset < 2) return; - + if(config.cushion) { var color = node.getData('color'); - var lg = ctx.createRadialGradient(posx + (width - offset)/2, - posy + (height - offset)/2, 1, - posx + (width-offset)/2, posy + (height-offset)/2, + var lg = ctx.createRadialGradient(posx + (width - offset)/2, + posy + (height - offset)/2, 1, + posx + (width-offset)/2, posy + (height-offset)/2, width < height? height : width); - var colorGrad = $.rgbToHex($.map($.hexToRgb(color), + var colorGrad = $.rgbToHex($.map($.hexToRgb(color), function(r) { return r * 0.3 >> 0; })); lg.addColorStop(0, color); lg.addColorStop(1, colorGrad); @@ -14305,17 +14305,17 @@ $jit.Icicle.Plot.EdgeTypes = new Class( { /* * Class: Layouts.ForceDirected - * + * * Implements a Force Directed Layout. - * + * * Implemented By: - * + * * - * + * * Credits: - * + * * Marcus Cobden - * + * */ Layouts.ForceDirected = new Class({ @@ -14324,12 +14324,12 @@ Layouts.ForceDirected = new Class({ var w = s.width, h = s.height; //count nodes var count = 0; - this.graph.eachNode(function(n) { + this.graph.eachNode(function(n) { count++; }); var k2 = w * h / count, k = Math.sqrt(k2); var l = this.config.levelDistance; - + return { width: w, height: h, @@ -14338,7 +14338,7 @@ Layouts.ForceDirected = new Class({ edgef: function(x) { return /* x * x / k; */ k * (x - l); } }; }, - + compute: function(property, incremental) { var prop = $.splat(property || ['current', 'start', 'end']); var opt = this.getOptions(); @@ -14360,7 +14360,7 @@ Layouts.ForceDirected = new Class({ }); this.computePositions(prop, opt, incremental); }, - + computePositions: function(property, opt, incremental) { var times = this.config.iterations, i = 0, that = this; if(incremental) { @@ -14384,7 +14384,7 @@ Layouts.ForceDirected = new Class({ } } }, - + computePositionStep: function(property, opt) { var graph = this.graph; var min = Math.min, max = Math.max; @@ -14433,7 +14433,7 @@ Layouts.ForceDirected = new Class({ var disp = u.disp[p]; var norm = disp.norm() || 1; var p = u.getPos(p); - p.$add($C(disp.x * min(Math.abs(disp.x), t) / norm, + p.$add($C(disp.x * min(Math.abs(disp.x), t) / norm, disp.y * min(Math.abs(disp.y), t) / norm)); p.x = min(w2, max(-w2, p.x)); p.y = min(h2, max(-h2, p.y)); @@ -14448,21 +14448,21 @@ Layouts.ForceDirected = new Class({ /* Class: ForceDirected - + A visualization that lays graphs using a Force-Directed layout algorithm. - + Inspired by: - + Force-Directed Drawing Algorithms (Stephen G. Kobourov) - + Implements: - + All methods - + Constructor Options: - + Inherits options from - + - - - @@ -14472,12 +14472,12 @@ Layouts.ForceDirected = new Class({ - - - - + Additionally, there are two parameters - + levelDistance - (number) Default's *50*. The natural length desired for the edges. - iterations - (number) Default's *50*. The number of iterations for the spring layout simulation. Depending on the browser's speed you could set this to a more 'interesting' number, like *200*. - + iterations - (number) Default's *50*. The number of iterations for the spring layout simulation. Depending on the browser's speed you could set this to a more 'interesting' number, like *200*. + Instance Properties: canvas - Access a instance. @@ -14536,9 +14536,9 @@ $jit.ForceDirected = new Class( { this.initializeExtras(); }, - /* - Method: refresh - + /* + Method: refresh + Computes positions and plots the tree. */ refresh: function() { @@ -14552,35 +14552,35 @@ $jit.ForceDirected = new Class( { /* Method: computeIncremental - + Performs the Force Directed algorithm incrementally. - + Description: - - ForceDirected algorithms can perform many computations and lead to JavaScript taking too much time to complete. - This method splits the algorithm into smaller parts allowing the user to track the evolution of the algorithm and + + ForceDirected algorithms can perform many computations and lead to JavaScript taking too much time to complete. + This method splits the algorithm into smaller parts allowing the user to track the evolution of the algorithm and avoiding browser messages such as "This script is taking too long to complete". - + Parameters: - + opt - (object) The object properties are described below - - iter - (number) Default's *20*. Split the algorithm into pieces of _iter_ iterations. For example, if the _iterations_ configuration property + + iter - (number) Default's *20*. Split the algorithm into pieces of _iter_ iterations. For example, if the _iterations_ configuration property of your class is 100, then you could set _iter_ to 20 to split the main algorithm into 5 smaller pieces. - - property - (string) Default's *end*. Whether to update starting, current or ending node positions. Possible values are 'end', 'start', 'current'. - You can also set an array of these properties. If you'd like to keep the current node positions but to perform these + + property - (string) Default's *end*. Whether to update starting, current or ending node positions. Possible values are 'end', 'start', 'current'. + You can also set an array of these properties. If you'd like to keep the current node positions but to perform these computations for final animation positions then you can just choose 'end'. - - onStep - (function) A callback function called when each "small part" of the algorithm completed. This function gets as first formal + + onStep - (function) A callback function called when each "small part" of the algorithm completed. This function gets as first formal parameter a percentage value. - + onComplete - A callback function called when the algorithm completed. - + Example: - + In this example I calculate the end positions and then animate the graph to those positions - + (start code js) var fd = new $jit.ForceDirected(...); fd.computeIncremental({ @@ -14595,9 +14595,9 @@ $jit.ForceDirected = new Class( { } }); (end code) - + In this example I calculate all positions and (re)plot the graph - + (start code js) var fd = new ForceDirected(...); fd.computeIncremental({ @@ -14612,7 +14612,7 @@ $jit.ForceDirected = new Class( { } }); (end code) - + */ computeIncremental: function(opt) { opt = $.merge( { @@ -14628,7 +14628,7 @@ $jit.ForceDirected = new Class( { /* Method: plot - + Plots the ForceDirected graph. This is a shortcut to *fx.plot*. */ plot: function() { @@ -14637,7 +14637,7 @@ $jit.ForceDirected = new Class( { /* Method: animate - + Animates the graph from the current positions to the 'end' node positions. */ animate: function(opt) { @@ -14653,15 +14653,15 @@ $jit.ForceDirected.$extend = true; /* Class: ForceDirected.Op - + Custom extension of . Extends: All methods - + See also: - + */ @@ -14673,17 +14673,17 @@ $jit.ForceDirected.$extend = true; /* Class: ForceDirected.Plot - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ ForceDirected.Plot = new Class( { @@ -14693,24 +14693,24 @@ $jit.ForceDirected.$extend = true; /* Class: ForceDirected.Label - - Custom extension of . + + Custom extension of . Contains custom , and extensions. - + Extends: - + All methods and subclasses. - + See also: - + , , , . - + */ ForceDirected.Label = {}; /* ForceDirected.Label.Native - + Custom extension of . Extends: @@ -14728,17 +14728,17 @@ $jit.ForceDirected.$extend = true; /* ForceDirected.Label.SVG - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ ForceDirected.Label.SVG = new Class( { Implements: Graph.Label.SVG, @@ -14747,7 +14747,7 @@ $jit.ForceDirected.$extend = true; this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -14757,10 +14757,10 @@ $jit.ForceDirected.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -14780,7 +14780,7 @@ $jit.ForceDirected.$extend = true; /* ForceDirected.Label.HTML - + Custom extension of . Extends: @@ -14798,7 +14798,7 @@ $jit.ForceDirected.$extend = true; initialize: function(viz) { this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -14808,10 +14808,10 @@ $jit.ForceDirected.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -14834,7 +14834,7 @@ $jit.ForceDirected.$extend = true; /* Class: ForceDirected.Plot.NodeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Node types implemented are 'none', 'circle', 'triangle', 'rectangle', 'star', 'ellipse' and 'square'. You can add your custom node types, customizing your visualization to the extreme. @@ -14863,64 +14863,64 @@ $jit.ForceDirected.$extend = true; }, 'circle': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), dim = node.getData('dim'); this.nodeHelper.circle.render('fill', pos, dim, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), + var npos = node.pos.getc(true), dim = node.getData('dim'); return this.nodeHelper.circle.contains(npos, pos, dim); } }, 'ellipse': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), - width = node.getData('width'), + var pos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); this.nodeHelper.ellipse.render('fill', pos, width, height, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), - width = node.getData('width'), + var npos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); return this.nodeHelper.ellipse.contains(npos, pos, width, height); } }, 'square': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), dim = node.getData('dim'); this.nodeHelper.square.render('fill', pos, dim, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), + var npos = node.pos.getc(true), dim = node.getData('dim'); return this.nodeHelper.square.contains(npos, pos, dim); } }, 'rectangle': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), - width = node.getData('width'), + var pos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); this.nodeHelper.rectangle.render('fill', pos, width, height, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), - width = node.getData('width'), + var npos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); return this.nodeHelper.rectangle.contains(npos, pos, width, height); } }, 'triangle': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), dim = node.getData('dim'); this.nodeHelper.triangle.render('fill', pos, dim, canvas); }, 'contains': function(node, pos) { - var npos = node.pos.getc(true), + var npos = node.pos.getc(true), dim = node.getData('dim'); return this.nodeHelper.triangle.contains(npos, pos, dim); } @@ -14941,14 +14941,14 @@ $jit.ForceDirected.$extend = true; /* Class: ForceDirected.Plot.EdgeTypes - - This class contains a list of built-in types. + + This class contains a list of built-in types. Edge types implemented are 'none', 'line' and 'arrow'. - + You can add your custom edge types, customizing your visualization to the extreme. - + Example: - + (start code js) ForceDirected.Plot.EdgeTypes.implement({ 'mySpecialType': { @@ -14962,7 +14962,7 @@ $jit.ForceDirected.$extend = true; } }); (end code) - + */ ForceDirected.Plot.EdgeTypes = new Class({ 'none': $.empty, @@ -15011,17 +15011,17 @@ $jit.TM.$extend = true; /* Class: TM.Base - + Abstract class providing base functionality for , and visualizations. - + Implements: - + All methods - + Constructor Options: - + Inherits options from - + - - - @@ -15031,7 +15031,7 @@ $jit.TM.$extend = true; - - - - + Additionally, there are other parameters and some default values changed orientation - (string) Default's *h*. Whether to set horizontal or vertical layouts. Possible values are 'h' and 'v'. @@ -15043,9 +15043,9 @@ $jit.TM.$extend = true; Node.type - Described in . Default's *rectangle*. duration - Described in . Default's *700*. fps - Described in . Default's *45*. - + Instance Properties: - + canvas - Access a instance. graph - Access a instance. op - Access a instance. @@ -15053,13 +15053,13 @@ $jit.TM.$extend = true; labels - Access a interface implementation. Inspired by: - + Squarified Treemaps (Mark Bruls, Kees Huizing, and Jarke J. van Wijk) - + Tree visualization with tree-maps: 2-d space-filling approach (Ben Shneiderman) - + Note: - + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the visualization described in the paper. */ @@ -15144,9 +15144,9 @@ TM.Base = { this.initializeExtras(); }, - /* - Method: refresh - + /* + Method: refresh + Computes positions and plots the tree. */ refresh: function(){ @@ -15155,7 +15155,7 @@ TM.Base = { var that = this; if(this.config.animate) { this.compute('end'); - this.config.levelsToShow > 0 && this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode + this.config.levelsToShow > 0 && this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode && this.clickedNode.id || this.root)); this.fx.animate($.merge(this.config, { modes: ['linear', 'node-property:width:height'], @@ -15171,29 +15171,29 @@ TM.Base = { } this.busy = false; this.compute(); - this.config.levelsToShow > 0 && this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode + this.config.levelsToShow > 0 && this.geom.setRightLevelToShow(this.graph.getNode(this.clickedNode && this.clickedNode.id || this.root)); this.plot(); } }, - /* - Method: plot - - Plots the TreeMap. This is a shortcut to *fx.plot*. - + /* + Method: plot + + Plots the TreeMap. This is a shortcut to *fx.plot*. + */ plot: function(){ this.fx.plot(); }, - /* - Method: leaf - + /* + Method: leaf + Returns whether the node is a leaf. - + Parameters: - + n - (object) A . */ @@ -15202,21 +15202,21 @@ TM.Base = { 1, 1 ], "ignore").length == 0; }, - - /* - Method: enter - + + /* + Method: enter + Sets the node as root. - + Parameters: - + n - (object) A . */ enter: function(n){ if(this.busy) return; this.busy = true; - + var that = this, config = this.config, graph = this.graph, @@ -15250,7 +15250,7 @@ TM.Base = { that.fx.animate({ modes:['linear', 'node-property:width:height'], duration: 1000, - onComplete: function() { + onComplete: function() { that.busy = false; //TODO(nico) check comment above that.clickedNode = clickedNode; @@ -15272,9 +15272,9 @@ TM.Base = { } }, - /* - Method: out - + /* + Method: out + Sets the parent node of the current selected node as root. */ @@ -15285,12 +15285,12 @@ TM.Base = { var that = this, config = this.config, graph = this.graph, - parents = graph.getNode(this.clickedNode + parents = graph.getNode(this.clickedNode && this.clickedNode.id || this.root).getParents(), parent = parents[0], clickedNode = parent, previousClickedNode = this.clickedNode; - + //if no parents return if(!parent) { this.busy = false; @@ -15354,7 +15354,7 @@ TM.Base = { }, requestNodes: function(node, onComplete){ - var handler = $.merge(this.controller, onComplete), + var handler = $.merge(this.controller, onComplete), lev = this.config.levelsToShow; if (handler.request) { var leaves = [], d = node._depth; @@ -15370,7 +15370,7 @@ TM.Base = { handler.onComplete(); } }, - + reposition: function() { this.compute('end'); } @@ -15378,17 +15378,17 @@ TM.Base = { /* Class: TM.Op - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ TM.Op = new Class({ Implements: Graph.Op, @@ -15401,18 +15401,18 @@ TM.Op = new Class({ //extend level methods of Graph.Geom TM.Geom = new Class({ Implements: Graph.Geom, - + getRightLevelToShow: function() { return this.viz.config.levelsToShow; }, - + setRightLevelToShow: function(node) { - var level = this.getRightLevelToShow(), + var level = this.getRightLevelToShow(), fx = this.viz.labels; node.eachLevel(0, level+1, function(n) { var d = n._depth - node._depth; if(d > level) { - n.drawn = false; + n.drawn = false; n.exist = false; n.ignore = true; fx.hideLabel(n, false); @@ -15441,8 +15441,8 @@ TM.Group = new Class( { }, /* - - Calls the request method on the controller to request a subtree for each node. + + Calls the request method on the controller to request a subtree for each node. */ requestNodes: function(nodes, controller){ var counter = 0, len = nodes.length, nodeSelected = {}; @@ -15474,17 +15474,17 @@ TM.Group = new Class( { /* Class: TM.Plot - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ TM.Plot = new Class({ @@ -15502,7 +15502,7 @@ TM.Plot = new Class({ }, plot: function(opt, animating){ - var viz = this.viz, + var viz = this.viz, graph = viz.graph; viz.canvas.clear(); this.plotTree(graph.getNode(viz.clickedNode && viz.clickedNode.id || viz.root), $.merge(viz.config, opt || {}, { @@ -15517,8 +15517,8 @@ TM.Plot = new Class({ /* Class: TM.Label - - Custom extension of . + + Custom extension of . Contains custom , and extensions. Extends: @@ -15528,7 +15528,7 @@ TM.Plot = new Class({ See also: , , , . - + */ TM.Label = {}; @@ -15552,16 +15552,16 @@ TM.Label.Native = new Class({ this.config = viz.config; this.leaf = viz.leaf; }, - + renderLabel: function(canvas, node, controller){ if(!this.leaf(node) && !this.config.titleHeight) return; - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), ctx = canvas.getCtx(), width = node.getData('width'), height = node.getData('height'), x = pos.x + width/2, y = pos.y; - + ctx.fillText(node.name, x, y, width); } }); @@ -15588,7 +15588,7 @@ TM.Label.SVG = new Class( { this.config = viz.config; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -15598,10 +15598,10 @@ TM.Label.SVG = new Class( { tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -15645,20 +15645,20 @@ TM.Label.HTML = new Class( { this.config = viz.config; }, - /* + /* placeLabel - + Overrides abstract method placeLabel in . - + Parameters: - + tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -15688,7 +15688,7 @@ TM.Label.HTML = new Class( { /* Class: TM.Plot.NodeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Node types implemented are 'none', 'rectangle'. You can add your custom node types, customizing your visualization to the extreme. @@ -15726,15 +15726,15 @@ TM.Plot.NodeTypes = new Class( { height = node.getData('height'), border = node.getData('border'), ctx = canvas.getCtx(), - posx = pos.x + offst / 2, + posx = pos.x + offst / 2, posy = pos.y + offst / 2; if(width <= offst || height <= offst) return; if (leaf) { if(config.cushion) { - var lg = ctx.createRadialGradient(posx + (width-offst)/2, posy + (height-offst)/2, 1, + var lg = ctx.createRadialGradient(posx + (width-offst)/2, posy + (height-offst)/2, 1, posx + (width-offst)/2, posy + (height-offst)/2, width < height? height : width); var color = node.getData('color'); - var colorGrad = $.rgbToHex($.map($.hexToRgb(color), + var colorGrad = $.rgbToHex($.map($.hexToRgb(color), function(r) { return r * 0.2 >> 0; })); lg.addColorStop(0, color); lg.addColorStop(1, colorGrad); @@ -15762,7 +15762,7 @@ TM.Plot.NodeTypes = new Class( { 'contains': function(node, pos) { if(this.viz.clickedNode && !node.isDescendantOf(this.viz.clickedNode.id) || node.ignore) return false; var npos = node.pos.getc(true), - width = node.getData('width'), + width = node.getData('width'), leaf = this.viz.leaf(node), height = leaf? node.getData('height') : this.config.titleHeight; return this.nodeHelper.rectangle.contains({x: npos.x + width/2, y: npos.y + height/2}, pos, width, height); @@ -15776,11 +15776,11 @@ TM.Plot.EdgeTypes = new Class( { /* Class: TM.SliceAndDice - + A slice and dice TreeMap visualization. - + Implements: - + All methods and properties. */ TM.SliceAndDice = new Class( { @@ -15791,11 +15791,11 @@ TM.SliceAndDice = new Class( { /* Class: TM.Squarified - + A squarified TreeMap visualization. Implements: - + All methods and properties. */ TM.Squarified = new Class( { @@ -15806,11 +15806,11 @@ TM.Squarified = new Class( { /* Class: TM.Strip - + A strip TreeMap visualization. Implements: - + All methods and properties. */ TM.Strip = new Class( { @@ -15827,25 +15827,25 @@ TM.Strip = new Class( { /* Class: RGraph - + A radial graph visualization with advanced animations. - + Inspired by: - + Animated Exploration of Dynamic Graphs with Radial Layout (Ka-Ping Yee, Danyel Fisher, Rachna Dhamija, Marti Hearst) - + Note: - + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the visualization described in the paper. - + Implements: - + All methods - + Constructor Options: - + Inherits options from - + - - - @@ -15855,19 +15855,19 @@ TM.Strip = new Class( { - - - - + Additionally, there are other parameters and some default values changed - + interpolation - (string) Default's *linear*. Describes the way nodes are interpolated. Possible values are 'linear' and 'polar'. - levelDistance - (number) Default's *100*. The distance between levels of the tree. - + levelDistance - (number) Default's *100*. The distance between levels of the tree. + Instance Properties: canvas - Access a instance. graph - Access a instance. op - Access a instance. fx - Access a instance. - labels - Access a interface implementation. + labels - Access a interface implementation. */ $jit.RGraph = new Class( { @@ -15922,14 +15922,14 @@ $jit.RGraph = new Class( { this.initializeExtras(); }, - /* - - createLevelDistanceFunc - - Returns the levelDistance function used for calculating a node distance - to its origin. This function returns a function that is computed - per level and not per node, such that all nodes with the same depth will have the - same distance to the origin. The resulting function gets the + /* + + createLevelDistanceFunc + + Returns the levelDistance function used for calculating a node distance + to its origin. This function returns a function that is computed + per level and not per node, such that all nodes with the same depth will have the + same distance to the origin. The resulting function gets the parent node as parameter and returns a float. */ @@ -15940,9 +15940,9 @@ $jit.RGraph = new Class( { }; }, - /* - Method: refresh - + /* + Method: refresh + Computes positions and plots the tree. */ @@ -15957,7 +15957,7 @@ $jit.RGraph = new Class( { /* Method: plot - + Plots the RGraph. This is a shortcut to *fx.plot*. */ plot: function(){ @@ -15965,7 +15965,7 @@ $jit.RGraph = new Class( { }, /* getNodeAndParentAngle - + Returns the _parent_ of the given node, also calculating its angle span. */ getNodeAndParentAngle: function(id){ @@ -15987,7 +15987,7 @@ $jit.RGraph = new Class( { }, /* tagChildren - + Enumerates the children in order to maintain child ordering (second constraint of the paper). */ tagChildren: function(par, id){ @@ -16004,9 +16004,9 @@ $jit.RGraph = new Class( { } } }, - /* - Method: onClick - + /* + Method: onClick + Animates the to center the node specified by *id*. Parameters: @@ -16024,7 +16024,7 @@ $jit.RGraph = new Class( { hideLabels: false }); (end code) - + */ onClick: function(id, opt){ if (this.root != id && !this.busy) { @@ -16071,15 +16071,15 @@ $jit.RGraph.$extend = true; /* Class: RGraph.Op - + Custom extension of . Extends: All methods - + See also: - + */ @@ -16091,17 +16091,17 @@ $jit.RGraph.$extend = true; /* Class: RGraph.Plot - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ RGraph.Plot = new Class( { @@ -16112,17 +16112,17 @@ $jit.RGraph.$extend = true; /* Object: RGraph.Label - Custom extension of . + Custom extension of . Contains custom , and extensions. - + Extends: - + All methods and subclasses. - + See also: - + , , , . - + */ RGraph.Label = {}; @@ -16146,17 +16146,17 @@ $jit.RGraph.$extend = true; /* RGraph.Label.SVG - + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ RGraph.Label.SVG = new Class( { Implements: Graph.Label.SVG, @@ -16165,7 +16165,7 @@ $jit.RGraph.$extend = true; this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -16175,10 +16175,10 @@ $jit.RGraph.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -16216,7 +16216,7 @@ $jit.RGraph.$extend = true; initialize: function(viz){ this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -16226,10 +16226,10 @@ $jit.RGraph.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -16253,7 +16253,7 @@ $jit.RGraph.$extend = true; /* Class: RGraph.Plot.NodeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Node types implemented are 'none', 'circle', 'triangle', 'rectangle', 'star', 'ellipse' and 'square'. You can add your custom node types, customizing your visualization to the extreme. @@ -16282,64 +16282,64 @@ $jit.RGraph.$extend = true; }, 'circle': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), dim = node.getData('dim'); this.nodeHelper.circle.render('fill', pos, dim, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), + var npos = node.pos.getc(true), dim = node.getData('dim'); return this.nodeHelper.circle.contains(npos, pos, dim); } }, 'ellipse': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), - width = node.getData('width'), + var pos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); this.nodeHelper.ellipse.render('fill', pos, width, height, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), - width = node.getData('width'), + var npos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); return this.nodeHelper.ellipse.contains(npos, pos, width, height); } }, 'square': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), dim = node.getData('dim'); this.nodeHelper.square.render('fill', pos, dim, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), + var npos = node.pos.getc(true), dim = node.getData('dim'); return this.nodeHelper.square.contains(npos, pos, dim); } }, 'rectangle': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), - width = node.getData('width'), + var pos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); this.nodeHelper.rectangle.render('fill', pos, width, height, canvas); }, 'contains': function(node, pos){ - var npos = node.pos.getc(true), - width = node.getData('width'), + var npos = node.pos.getc(true), + width = node.getData('width'), height = node.getData('height'); return this.nodeHelper.rectangle.contains(npos, pos, width, height); } }, 'triangle': { 'render': function(node, canvas){ - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), dim = node.getData('dim'); this.nodeHelper.triangle.render('fill', pos, dim, canvas); }, 'contains': function(node, pos) { - var npos = node.pos.getc(true), + var npos = node.pos.getc(true), dim = node.getData('dim'); return this.nodeHelper.triangle.contains(npos, pos, dim); } @@ -16361,13 +16361,13 @@ $jit.RGraph.$extend = true; /* Class: RGraph.Plot.EdgeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Edge types implemented are 'none', 'line' and 'arrow'. - + You can add your custom edge types, customizing your visualization to the extreme. - + Example: - + (start code js) RGraph.Plot.EdgeTypes.implement({ 'mySpecialType': { @@ -16381,7 +16381,7 @@ $jit.RGraph.$extend = true; } }); (end code) - + */ RGraph.Plot.EdgeTypes = new Class({ 'none': $.empty, @@ -16419,25 +16419,25 @@ $jit.RGraph.$extend = true; /* * File: Hypertree.js - * + * */ -/* - Complex - - A multi-purpose Complex Class with common methods. Extended for the Hypertree. - +/* + Complex + + A multi-purpose Complex Class with common methods. Extended for the Hypertree. + */ -/* - moebiusTransformation - - Calculates a moebius transformation for this point / complex. - For more information go to: - http://en.wikipedia.org/wiki/Moebius_transformation. - - Parameters: - - c - An initialized Complex instance representing a translation Vector. +/* + moebiusTransformation + + Calculates a moebius transformation for this point / complex. + For more information go to: + http://en.wikipedia.org/wiki/Moebius_transformation. + + Parameters: + + c - An initialized Complex instance representing a translation Vector. */ Complex.prototype.moebiusTransformation = function(c) { @@ -16447,20 +16447,20 @@ Complex.prototype.moebiusTransformation = function(c) { return num.$div(den); }; -/* - moebiusTransformation - - Calculates a moebius transformation for the hyperbolic tree. - - - - Parameters: - +/* + moebiusTransformation + + Calculates a moebius transformation for the hyperbolic tree. + + + + Parameters: + graph - A instance. pos - A . prop - A property array. - theta - Rotation angle. - startPos - _optional_ start position. + theta - Rotation angle. + startPos - _optional_ start position. */ Graph.Util.moebiusTransformation = function(graph, pos, prop, startPos, flags) { this.eachNode(graph, function(elem) { @@ -16471,28 +16471,28 @@ Graph.Util.moebiusTransformation = function(graph, pos, prop, startPos, flags) { }, flags); }; -/* - Class: Hypertree - +/* + Class: Hypertree + A Hyperbolic Tree/Graph visualization. - + Inspired by: - - A Focus+Context Technique Based on Hyperbolic Geometry for Visualizing Large Hierarchies (John Lamping, Ramana Rao, and Peter Pirolli). + + A Focus+Context Technique Based on Hyperbolic Geometry for Visualizing Large Hierarchies (John Lamping, Ramana Rao, and Peter Pirolli). - + Note: - + This visualization was built and engineered from scratch, taking only the paper as inspiration, and only shares some features with the Hypertree described in the paper. Implements: - + All methods - + Constructor Options: - + Inherits options from - + - - - @@ -16502,17 +16502,17 @@ Graph.Util.moebiusTransformation = function(graph, pos, prop, startPos, flags) { - - - - + Additionally, there are other parameters and some default values changed - + radius - (string|number) Default's *auto*. The radius of the disc to plot the in. 'auto' will take the smaller value from the width and height canvas dimensions. You can also set this to a custom value, for example *250*. offset - (number) Default's *0*. A number in the range [0, 1) that will be substracted to each node position to make a more compact . This will avoid placing nodes too far from each other when a there's a selected node. fps - Described in . It's default value has been changed to *35*. duration - Described in . It's default value has been changed to *1500*. - Edge.type - Described in . It's default value has been changed to *hyperline*. - + Edge.type - Described in . It's default value has been changed to *hyperline*. + Instance Properties: - + canvas - Access a instance. graph - Access a instance. op - Access a instance. @@ -16574,14 +16574,14 @@ $jit.Hypertree = new Class( { this.initializeExtras(); }, - /* - - createLevelDistanceFunc + /* + + createLevelDistanceFunc - Returns the levelDistance function used for calculating a node distance - to its origin. This function returns a function that is computed - per level and not per node, such that all nodes with the same depth will have the - same distance to the origin. The resulting function gets the + Returns the levelDistance function used for calculating a node distance + to its origin. This function returns a function that is computed + per level and not per node, such that all nodes with the same depth will have the + same distance to the origin. The resulting function gets the parent node as parameter and returns a float. */ @@ -16614,16 +16614,16 @@ $jit.Hypertree = new Class( { return genDistFunc(0.75); }, - /* - Method: getRadius - - Returns the current radius of the visualization. If *config.radius* is *auto* then it + /* + Method: getRadius + + Returns the current radius of the visualization. If *config.radius* is *auto* then it calculates the radius by taking the smaller size of the widget. - + See also: - + - + */ getRadius: function() { var rad = this.config.radius; @@ -16632,9 +16632,9 @@ $jit.Hypertree = new Class( { return Math.min(s.width, s.height) / 2; }, - /* - Method: refresh - + /* + Method: refresh + Computes positions and plots the tree. Parameters: @@ -16655,14 +16655,14 @@ $jit.Hypertree = new Class( { this.plot(); }, - /* - reposition - + /* + reposition + Computes nodes' positions and restores the tree to its previous position. - For calculating nodes' positions the root must be placed on its origin. This method does this + For calculating nodes' positions the root must be placed on its origin. This method does this and then attemps to restore the hypertree to its previous position. - + */ reposition: function() { this.compute('end'); @@ -16677,19 +16677,19 @@ $jit.Hypertree = new Class( { }); }, - /* - Method: plot - - Plots the . This is a shortcut to *fx.plot*. + /* + Method: plot + + Plots the . This is a shortcut to *fx.plot*. */ plot: function() { this.fx.plot(); }, - /* - Method: onClick - + /* + Method: onClick + Animates the to center the node specified by *id*. Parameters: @@ -16707,25 +16707,25 @@ $jit.Hypertree = new Class( { hideLabels: false }); (end code) - + */ onClick: function(id, opt) { var pos = this.graph.getNode(id).pos.getc(true); this.move(pos, opt); }, - /* - Method: move + /* + Method: move - Translates the tree to the given position. + Translates the tree to the given position. Parameters: pos - (object) A *x, y* coordinate object where x, y in [0, 1), to move the tree to. opt - This object has been defined in - + Example: - + (start code js) ht.move({ x: 0, y: 0.7 }, { hideLabels: false @@ -16760,17 +16760,17 @@ $jit.Hypertree.$extend = true; (function(Hypertree) { - /* - Class: Hypertree.Op - + /* + Class: Hypertree.Op + Custom extension of . Extends: All methods - + See also: - + */ @@ -16780,19 +16780,19 @@ $jit.Hypertree.$extend = true; }); - /* - Class: Hypertree.Plot - + /* + Class: Hypertree.Plot + Custom extension of . - + Extends: - + All methods - + See also: - + - + */ Hypertree.Plot = new Class( { @@ -16803,15 +16803,15 @@ $jit.Hypertree.$extend = true; /* Object: Hypertree.Label - Custom extension of . + Custom extension of . Contains custom , and extensions. - + Extends: - + All methods and subclasses. - + See also: - + , , , . */ @@ -16850,15 +16850,15 @@ $jit.Hypertree.$extend = true; Hypertree.Label.SVG Custom extension of . - + Extends: - + All methods - + See also: - + - + */ Hypertree.Label.SVG = new Class( { Implements: Graph.Label.SVG, @@ -16867,7 +16867,7 @@ $jit.Hypertree.$extend = true; this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -16877,10 +16877,10 @@ $jit.Hypertree.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -16918,7 +16918,7 @@ $jit.Hypertree.$extend = true; initialize: function(viz) { this.viz = viz; }, - /* + /* placeLabel Overrides abstract method placeLabel in . @@ -16928,10 +16928,10 @@ $jit.Hypertree.$extend = true; tag - A DOM label element. node - A . controller - A configuration/controller object passed to the visualization. - + */ placeLabel: function(tag, node, controller) { - var pos = node.pos.getc(true), + var pos = node.pos.getc(true), canvas = this.viz.canvas, ox = canvas.translateOffsetX, oy = canvas.translateOffsetY, @@ -16955,7 +16955,7 @@ $jit.Hypertree.$extend = true; /* Class: Hypertree.Plot.NodeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Node types implemented are 'none', 'circle', 'triangle', 'rectangle', 'star', 'ellipse' and 'square'. You can add your custom node types, customizing your visualization to the extreme. @@ -17089,13 +17089,13 @@ $jit.Hypertree.$extend = true; /* Class: Hypertree.Plot.EdgeTypes - This class contains a list of built-in types. + This class contains a list of built-in types. Edge types implemented are 'none', 'line', 'arrow' and 'hyperline'. - + You can add your custom edge types, customizing your visualization to the extreme. - + Example: - + (start code js) Hypertree.Plot.EdgeTypes.implement({ 'mySpecialType': { @@ -17109,7 +17109,7 @@ $jit.Hypertree.$extend = true; } }); (end code) - + */ Hypertree.Plot.EdgeTypes = new Class({ 'none': $.empty, @@ -17160,4 +17160,4 @@ $jit.Hypertree.$extend = true; - })(); \ No newline at end of file + })(); diff --git a/frontend_knowledge/js/script.js b/frontend_knowledge/js/script.js index 88f39ff..4b3cd7d 100644 --- a/frontend_knowledge/js/script.js +++ b/frontend_knowledge/js/script.js @@ -5,7 +5,7 @@ var labelType, useGradients, nativeTextSupport, animate; iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i), typeOfCanvas = typeof HTMLCanvasElement, nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'), - textSupport = nativeCanvasSupport + textSupport = nativeCanvasSupport && (typeof document.createElement('canvas').getContext('2d').fillText == 'function'); //I'm setting this based on the fact that ExCanvas provides text support for IE //and that as of today iPhone/iPad current text support is lame @@ -18,7 +18,7 @@ var labelType, useGradients, nativeTextSupport, animate; var Log = { elem: false, write: function(text){ - if (!this.elem) + if (!this.elem) this.elem = document.getElementById('log'); this.elem.innerHTML = text; this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px'; @@ -28,517 +28,94 @@ var Log = { function init(){ //init data - var json = { - "id": "000", - "name": "前端工程师", - "children": [{ - "id": "001", - "name": "Web服务", - "children": [{ - "id": "001_01", - "name": "YQL/Company Open Platform" - }, - { - "id": "001_02", - "name": "APP Engine/Cloud" - }, - { - "id": "001_03", - "name": "Google Open API/Github" - }] - }, - {"id": "002", - "name": "前沿技术社区/会议", - "children": [{ - "id": "002_01", - "name": "YDN/YUIConf/JSConf" - }, - { - "id": "002_02", - "name": "QCon/Velocity" - }, - { - "id": "002_03", - "name": "D2/WebRebuild" - }, - { - "id": "002_04", - "name": "NodeParty/HTML5研究小组" - }, - { - "id": "002_05", - "name": "UED Teams" - }] - }, - {"id": "003", - "name": "移动终端", - "children": [{ - "id": "003_02", - "name": "jQueryMobile" - }, - { - "id": "003_03", - "name": "HTML5" - }, - { - "id": "003_04", - "name": "CSS3" - }, - { - "id": "003_05", - "name": "iOs/android" - }, - { - "id": "003_06", - "name": "responsive UI Design" - }] - }, - {"id": "004", - "name": "安全", - "children": [{ - "id": "004_01", - "name": "CSRF/XSS" - }, - { - "id": "004_02", - "name": "ADsafe" - }, - { - "id": "004_03", - "name": "Caja" - }, - { - "id": "004_04", - "name": "FBJS" - }, - { - "id": "004_05", - "name": "Sandbox" - }] - }, - {"id": "005", - "name": "软技能", - "children": [{ - "id": "005_01", - "name": "知识管理/总结分享" - },{ - "id": "005_02", - "name": "沟通技巧/团队开发" - },{ - "id": "005_03", - "name": "需求管理/PM" - },{ - "id": "005_04", - "name": "代码模块化开发/代码版本管理" - },{ - "id": "005_05", - "name": "交互设计/可用性" - },{ - "id": "005_06", - "name": "可访问性知识" - }] - }, - {"id": "006", - "name": "开发流程/部署", - "children": [{ - "id": "006_01", - "name": "JSLint" - },{ - "id": "006_02", - "name": "CSSLint" - },{ - "id": "006_03", - "name": "YUICompressor" - },{ - "id": "006_04", - "name": "JSMin" - },{ - "id": "006_05", - "name": "TPacker-minifier" - },{ - "id": "006_06", - "name": "Ant" - },{ - "id": "006_07", - "name": "Make" - },{ - "id": "006_08", - "name": "JSDoc" - },{ - "id": "006_09", - "name": "YUIDoc" - },{ - "id": "006_10", - "name": "LAMP" - }] - }, - {"id": "007", - "name": "前端框架/库", - "children": [{ - "id": "007_01", - "name": "jQuery" - },{ - "id": "007_02", - "name": "YUI2/YUI3" - },{ - "id": "007_03", - "name": "Prototype" - },{ - "id": "007_04", - "name": "Mootools" - },{ - "id": "007_05", - "name": "ExtJS" - },{ - "id": "007_06", - "name": "Smarty" - },{ - "id": "007_07", - "name": "Django" - },{ - "id": "007_08", - "name": "Zend" - },{ - "id": "007_09", - "name": "YUITest" - },{ - "id": "007_10", - "name": "Quint" - },{ - "id": "007_11", - "name": "Jasmine" - },{ - "id": "007_12", - "name": "前端测试" - },{ - "id": "007_13", - "name": "前端MVC" - }] - }, - {"id": "008", - "name": "浏览器兼容性", - "children": [{ - "id": "008_01", - "name": "IE6/7/8/9" - },{ - "id": "008_02", - "name": "Firfox" - },{ - "id": "008_03", - "name": "Chrome" - },{ - "id": "008_04", - "name": "Opera" - },{ - "id": "008_05", - "name": "Safari" - }] - }, - {"id": "009", - "name": "切页面", - "children": [{ - "id": "009_01", - "name": "HTML" - },{ - "id": "009_02", - "name": "CSS" - },{ - "id": "009_03", - "name": "PhotoShop" - }] - }, - {"id": "010", - "name": "编程语言", - "children": [{ - "id": "010_01", - "name": "JavaScript" - },{ - "id": "010_02", - "name": "PHP" - },{ - "id": "010_03", - "name": "Python" - },{ - "id": "010_04", - "name": "Perl" - },{ - "id": "010_05", - "name": "Python" - },{ - "id": "010_06", - "name": "Ruby" - }] - }, - {"id": "011", - "name": "调试工具", - "children": [{ - "id": "011_01", - "name": "Firebug" - },{ - "id": "011_02", - "name": "Firebug-lite" - },{ - "id": "011_03", - "name": "Web Inspector" - },{ - "id": "011_04", - "name": "YSlow" - },{ - "id": "011_05", - "name": "Smushi" - },{ - "id": "011_06", - "name": "IEDeveloperToolBar" - },{ - "id": "011_07", - "name": "IETester" - },{ - "id": "011_08", - "name": "SuperPreview" - },{ - "id": "011_09", - "name": "JsBeautifier" - },{ - "id": "011_10", - "name": "Fiddler" - },{ - "id": "011_11", - "name": "WireShark" - },{ - "id": "011_12", - "name": "tcpdump" - }] - }, - {"id": "012", - "name": "开发工具", - "children": [{ - "id": "012_01", - "name": "VIM" - },{ - "id": "012_02", - "name": "Aptana" - },{ - "id": "012_03", - "name": "Notepad++" - },{ - "id": "012_04", - "name": "EditPlus" - },{ - "id": "012_05", - "name": "Sublime Text" - },{ - "id": "012_06", - "name": "WebStorm" - },{ - "id": "012_07", - "name": "svn" - },{ - "id": "012_08", - "name": "git" - }] - }, - {"id": "013", - "name": "计算机知识储备", - "children": [{ - "id": "013_01", - "name": "编程原理" - },{ - "id": "013_02", - "name": "计算机网络" - },{ - "id": "013_03", - "name": "操作系统" - },{ - "id": "013_04", - "name": "算法原理" - },{ - "id": "013_05", - "name": "软件工程" - },{ - "id": "013_06", - "name": "软件测试原理" - }] - }, - {"id": "014", - "name": "前端标准/规范", - "children": [{ - "id": "014_01", - "name": "w3c" - },{ - "id": "014_02", - "name": "DOM/BOM" - },{ - "id": "014_03", - "name": "XHTML" - },{ - "id": "014_04", - "name": "XML" - },{ - "id": "014_05", - "name": "JSON" - },{ - "id": "014_06", - "name": "JONP" - },{ - "id": "014_07", - "name": "HTML5" - },{ - "id": "014_08", - "name": "CSS3" - },{ - "id": "014_09", - "name": "ECMAScript3" - },{ - "id": "014_10", - "name": "ECMAScript5" - },{ - "id": "014_11", - "name": "CommonJS" - },{ - "id": "014_12", - "name": "AMD" - },{ - "id": "014_13", - "name": "HTTP1.1" - }] - }, - {"id": "015", - "name": "性能", - "children": [{ - "id": "015_01", - "name": "WebPageTest" - },{ - "id": "015_02", - "name": "ShowSlow" - },{ - "id": "015_03", - "name": "YSlow" - },{ - "id": "015_04", - "name": "34Rule" - },{ - "id": "015_05", - "name": "PageSpeed" - },{ - "id": "015_06", - "name": "HttpWatch" - },{ - "id": "015_07", - "name": "DynaTrace's Ajax" - }] - }, - {"id": "016", - "name": "编程知识储备", - "children": [{ - "id": "016_01", - "name": "数据结构" - },{ - "id": "016_02", - "name": "MVC" - },{ - "id": "016_03", - "name": "面向对象" - },{ - "id": "016_04", - "name": "切面编程" - },{ - "id": "016_05", - "name": "函数式编程" - },{ - "id": "016_06", - "name": "JavaScript设计模式" - },{ - "id": "016_07", - "name": "JavaScript编程模式" - }] - }] - }; - //end - var infovis = document.getElementById('infovis'); - var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50; - - //init Hypertree - var ht = new $jit.Hypertree({ - //id of the visualization container - injectInto: 'infovis', - //canvas width and height - width: w, - height: h, - //Change node and edge styles such as - //color, width and dimensions. - Node: { - dim: 9, - color: "#f00" - }, - Edge: { - lineWidth: 2, - color: "#088" - }, - onBeforeCompute: function(node){ - Log.write("centering"); - }, - //Attach event handlers and add text to the - //labels. This method is only triggered on label - //creation - onCreateLabel: function(domElement, node){ - domElement.innerHTML = node.name; - $jit.util.addEvent(domElement, 'click', function () { - ht.onClick(node.id, { - onComplete: function() { - ht.controller.onComplete(); - } + $.getJSON('./f2e.json', function (json) { + //end + var infovis = document.getElementById('infovis'); + var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50; + + //init Hypertree + var ht = new $jit.Hypertree({ + //id of the visualization container + injectInto: 'infovis', + //canvas width and height + width: w, + height: h, + //Change node and edge styles such as + //color, width and dimensions. + Node: { + dim: 9, + color: "#f00" + }, + Edge: { + lineWidth: 2, + color: "#088" + }, + onBeforeCompute: function(node){ + Log.write("centering"); + }, + //Attach event handlers and add text to the + //labels. This method is only triggered on label + //creation + onCreateLabel: function(domElement, node){ + domElement.innerHTML = node.name; + $jit.util.addEvent(domElement, 'click', function () { + ht.onClick(node.id, { + onComplete: function() { + ht.controller.onComplete(); + } + }); }); - }); - }, - //Change node styles when labels are placed - //or moved. - onPlaceLabel: function(domElement, node){ - var style = domElement.style; - style.display = ''; - style.cursor = 'pointer'; - if (node._depth <= 1) { - style.fontSize = "0.8em"; - style.color = "#ddd"; + }, + //Change node styles when labels are placed + //or moved. + onPlaceLabel: function(domElement, node){ + var style = domElement.style; + style.display = ''; + style.cursor = 'pointer'; + if (node._depth <= 1) { + style.fontSize = "0.8em"; + style.color = "#ddd"; - } else if(node._depth == 2){ - style.fontSize = "0.7em"; - style.color = "#555"; + } else if(node._depth == 2){ + style.fontSize = "0.7em"; + style.color = "#555"; - } else { - style.display = 'none'; - } - - var left = parseInt(style.left); - var w = domElement.offsetWidth; - style.left = (left - w / 2) + 'px'; - }, - - onComplete: function(){ - Log.write("done"); - - //Build the right column relations list. - //This is done by collecting the information (stored in the data property) - //for all the nodes adjacent to the centered node. - var node = ht.graph.getClosestNodeToOrigin("current"); - var html = "

" + node.name + "

关系列表:"; - html += "
    "; - node.eachAdjacency(function(adj){ - var child = adj.nodeTo; - if (child.data) { - var rel = (child.data.band == node.name) ? child.data.relation : node.data.relation; - html += "
  • " + child.name + "
  • "; + } else { + style.display = 'none'; } - }); - html += "
"; - $jit.id('inner-details').innerHTML = html; - } + + var left = parseInt(style.left); + var w = domElement.offsetWidth; + style.left = (left - w / 2) + 'px'; + }, + + onComplete: function(){ + Log.write("done"); + + //Build the right column relations list. + //This is done by collecting the information (stored in the data property) + //for all the nodes adjacent to the centered node. + var node = ht.graph.getClosestNodeToOrigin("current"); + var html = "

" + node.name + "

关系列表:"; + html += "
    "; + node.eachAdjacency(function(adj){ + var child = adj.nodeTo; + if (child.data) { + var rel = (child.data.band == node.name) ? child.data.relation : node.data.relation; + html += "
  • " + child.name + "
  • "; + } + }); + html += "
"; + $jit.id('inner-details').innerHTML = html; + } + }); + //load JSON data. + ht.loadJSON(json); + //compute positions and plot. + ht.refresh(); + //end + ht.controller.onComplete(); }); - //load JSON data. - ht.loadJSON(json); - //compute positions and plot. - ht.refresh(); - //end - ht.controller.onComplete(); } function toggleDuoshuoComments(container, id, url){ From cdf244833ddcb06c4a15ba3cd12dbb786f23efa5 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Fri, 24 Oct 2014 19:18:40 +0800 Subject: [PATCH 065/107] Rename chart --- bin/generate.js | 2 +- {frontend_knowledge => chart}/css/Hypertree.css | 0 {frontend_knowledge => chart}/css/base.css | 0 {frontend_knowledge => chart}/css/col1.png | Bin {frontend_knowledge => chart}/css/col2.png | Bin {frontend_knowledge => chart}/f2e.json | 0 {frontend_knowledge => chart}/index.html | 0 {frontend_knowledge => chart}/js/jit.js | 0 {frontend_knowledge => chart}/js/script.js | 0 9 files changed, 1 insertion(+), 1 deletion(-) rename {frontend_knowledge => chart}/css/Hypertree.css (100%) rename {frontend_knowledge => chart}/css/base.css (100%) rename {frontend_knowledge => chart}/css/col1.png (100%) rename {frontend_knowledge => chart}/css/col2.png (100%) rename {frontend_knowledge => chart}/f2e.json (100%) rename {frontend_knowledge => chart}/index.html (100%) rename {frontend_knowledge => chart}/js/jit.js (100%) rename {frontend_knowledge => chart}/js/script.js (100%) diff --git a/bin/generate.js b/bin/generate.js index 96199bf..31c5ceb 100644 --- a/bin/generate.js +++ b/bin/generate.js @@ -82,4 +82,4 @@ var buildTree = function (list) { }; var tree = buildTree(formated); -fs.writeFileSync(path.join(__dirname, '../frontend_knowledge/f2e.json'), JSON.stringify(tree, null, ' ')); +fs.writeFileSync(path.join(__dirname, '../chart/f2e.json'), JSON.stringify(tree, null, ' ')); diff --git a/frontend_knowledge/css/Hypertree.css b/chart/css/Hypertree.css similarity index 100% rename from frontend_knowledge/css/Hypertree.css rename to chart/css/Hypertree.css diff --git a/frontend_knowledge/css/base.css b/chart/css/base.css similarity index 100% rename from frontend_knowledge/css/base.css rename to chart/css/base.css diff --git a/frontend_knowledge/css/col1.png b/chart/css/col1.png similarity index 100% rename from frontend_knowledge/css/col1.png rename to chart/css/col1.png diff --git a/frontend_knowledge/css/col2.png b/chart/css/col2.png similarity index 100% rename from frontend_knowledge/css/col2.png rename to chart/css/col2.png diff --git a/frontend_knowledge/f2e.json b/chart/f2e.json similarity index 100% rename from frontend_knowledge/f2e.json rename to chart/f2e.json diff --git a/frontend_knowledge/index.html b/chart/index.html similarity index 100% rename from frontend_knowledge/index.html rename to chart/index.html diff --git a/frontend_knowledge/js/jit.js b/chart/js/jit.js similarity index 100% rename from frontend_knowledge/js/jit.js rename to chart/js/jit.js diff --git a/frontend_knowledge/js/script.js b/chart/js/script.js similarity index 100% rename from frontend_knowledge/js/script.js rename to chart/js/script.js From 27cb51fe3b72639b48f8f1d77b4d1bb49626e6af Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Fri, 24 Oct 2014 19:28:55 +0800 Subject: [PATCH 066/107] Update document --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 67b5839..0b1f1ca 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ Frontend Knowledge Structure 图片的形式具有诸多的不便。缺失源图的我们,无法为此图贡献些什么,随着时间的迁移,或许有些技术点会发生改变,所以有了这个GitHub项目。我们可以通过协作的方式来共同维护这个项目。Git的历史记录也可以见证前端行业的一些变迁。 +[可视化效果](http://html5ify.com/fks/chart/) + ## 前端开发知识结构 - 前端工程师 - 浏览器 From 087370b565b6518b1e997614fff32a59d6562ea5 Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Sun, 30 Nov 2014 17:37:16 +0800 Subject: [PATCH 067/107] Update README.md --- README.md | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0b1f1ca..41707e9 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,12 @@ Frontend Knowledge Structure - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - [Brackets](http://brackets.io) + - [Atom](https://atom.io/) + - [Lime Text](http://limetext.org/) + - [Light Table](http://lighttable.com/) + - [Codebox](https://www.codebox.io/) + - [TextMate](http://macromates.com/) + - [Neovim](http://neovim.org/) - [Komodo IDE / Edit](http://www.activestate.com/komodo-edit) - [Eclipse](http://www.eclipse.org/) - [Visual Studio](http://www.visualstudio.com/) @@ -54,6 +60,7 @@ Frontend Knowledge Structure - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs) - [CSSLint](http://csslint.net/) - [Markup Validation Service](http://validator.w3.org/) + - [HTML Validators](https://validator.whatwg.org/) - 单元测试 - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) @@ -72,16 +79,23 @@ Frontend Knowledge Structure - [Juice UI](http://juiceui.com/) - [Web Atoms](http://webatomsjs.neurospeech.com/) - [Polymer](http://docs.polymerchina.org/) + - [Dhtmlx](http://dhtmlx.com/) + - [qooxdoo](http://qooxdoo.org/) + - [React](http://facebook.github.io/react/) + - [Brick](http://mozbrick.github.io/) + - [Knockout](http://knockoutjs.com/) - 前端标准/规范 - - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) + - HTTP/1.1: RFCs 7230-7235 + - [HTTP/2](https://http2.github.io/) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) - - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) + - [W3C: DOM/BOM/XHTML/XML/JSON/JSONP/...](http://www.w3.org/TR/) - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) - [Semantic Web](http://semanticweb.org/) - [MicroData](http://schema.org) - [RDFa](http://www.w3.org/TR/rdfa-core/) - - [Web Accessibility](http://www.w3.org/TR/WAI-WEBCONTENT/) + - [Web Accessibility](http://www.w3.org/WAI/) + - [WCAG](http://www.w3.org/TR/WAI-WEBCONTENT/) - [Role Attribute](http://www.w3.org/TR/role-attribute/) - [WAI-ARIA](http://www.w3.org/TR/wai-aria/) - 性能 @@ -130,6 +144,8 @@ Frontend Knowledge Structure - [Browserify](https://github.com/substack/node-browserify) - 安全 - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) + - [CSP](http://www.w3.org/TR/CSP/) + - [Same-origin policy](https://developer.mozilla.org/docs/Web/Security/Same-origin_policy) - ADsafe/Caja/Sandbox - 移动Web - HTML5/CSS3 @@ -138,6 +154,9 @@ Frontend Knowledge Structure - V5/[Sencha Touch](http://www.sencha.com/products/touch) - [PhoneGap](http://phonegap.com/) - [jQuery Mobile](http://jquerymobile.com/) + - [W3C Mobile Web Initiative](http://www.w3.org/Mobile/) + - [W3C mobileOK Checker](http://validator.w3.org/mobile/) + - [Open Mobile Alliance](http://openmobilealliance.org/) - 前沿技术社区/会议 - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂](http://www.html5dw.com) @@ -154,6 +173,7 @@ Frontend Knowledge Structure - [操作系统](http://zh.wikipedia.org/wiki/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F) - 算法原理 - 软件工程/软件测试原理 + - [Unicode](http://www.unicode.org/) - 软技能 - 知识管理/总结分享 - 沟通技巧/团队协作 @@ -163,7 +183,7 @@ Frontend Knowledge Structure - SVG/Canvas/VML - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) - - WebGL(http://zh.wikipedia.org/wiki/WebGL):[Three.JS](http://threejs.org/) + - [WebGL](http://en.wikipedia.org/wiki/WebGL)/[Three.JS](http://threejs.org/) - 后端工程师 - 编程语言 @@ -174,7 +194,7 @@ Frontend Knowledge Structure - [Lighttpd](http://www.lighttpd.net/) - 数据库 - SQL - - [MySQL](http://www.mysql.com/)/[PostgreSQL](http://www.postgresql.org/)/[Oracle](http://www.oracle.com/us/products/database/overview/index.html) + - [MySQL](http://www.mysql.com/)/[PostgreSQL](http://www.postgresql.org/)/[Oracle](http://www.oracle.com/us/products/database/overview/index.html)/[DB2](http://www-01.ibm.com/software/data/db2) - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - 数据缓存 - [Redis](http://redis.io/) From 1c0029c721b7ed48eeadf253b3349900a44d190f Mon Sep 17 00:00:00 2001 From: Xue Fuqiao Date: Sun, 30 Nov 2014 17:38:27 +0800 Subject: [PATCH 068/107] Update README.en.md --- README.en.md | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/README.en.md b/README.en.md index 6058e07..319ea47 100644 --- a/README.en.md +++ b/README.en.md @@ -32,6 +32,12 @@ Although the project would be maintained in plain text instead, I promise a smal - [WebStorm](http://www.jetbrains.com/webstorm/) - [Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org) - [Brackets](http://brackets.io) + - [Atom](https://atom.io/) + - [Lime Text](http://limetext.org/) + - [Light Table](http://lighttable.com/) + - [Codebox](https://www.codebox.io/) + - [TextMate](http://macromates.com/) + - [Neovim](http://neovim.org/) - [Komodo IDE / Edit](http://www.activestate.com/komodo-edit) - [Eclipse](http://www.eclipse.org/) - [Visual Studio](http://www.visualstudio.com/) @@ -54,6 +60,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs) - [CSSLint](http://csslint.net/) - [Markup Validation Service](http://validator.w3.org/) + - [HTML Validators](https://validator.whatwg.org/) - Unit testing - [QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/) - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) @@ -72,16 +79,23 @@ Although the project would be maintained in plain text instead, I promise a smal - [Juice UI](http://juiceui.com/) - [Web Atoms](http://webatomsjs.neurospeech.com/) - [Polymer](https://www.polymer-project.org/) + - [Dhtmlx](http://dhtmlx.com/) + - [qooxdoo](http://qooxdoo.org/) + - [React](http://facebook.github.io/react/) + - [Brick](http://mozbrick.github.io/) + - [Knockout](http://knockoutjs.com/) - Frontend standards / specifications - - [HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html) + - HTTP/1.1: RFCs 7230-7235 + - [HTTP/2](https://http2.github.io/) - [ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm) - - [W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/) + - [W3C: DOM/BOM/XHTML/XML/JSON/JSONP/...](http://www.w3.org/TR/) - [CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) - [HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html) - [Semantic Web](http://semanticweb.org/) - [MicroData](http://schema.org) - [RDFa](http://www.w3.org/TR/rdfa-core/) - - [Web Accessibility](http://www.w3.org/TR/WAI-WEBCONTENT/) + - [Web Accessibility](http://www.w3.org/WAI/) + - [WCAG](http://www.w3.org/TR/WAI-WEBCONTENT/) - [Role Attribute](http://www.w3.org/TR/role-attribute/) - [WAI-ARIA](http://www.w3.org/TR/wai-aria/) - Performance @@ -130,6 +144,8 @@ Although the project would be maintained in plain text instead, I promise a smal - [Browserify](https://github.com/substack/node-browserify) - Security - [CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) + - [CSP](http://www.w3.org/TR/CSP/) + - [Same-origin policy](https://developer.mozilla.org/docs/Web/Security/Same-origin_policy) - ADsafe/Caja/Sandbox - Mobile Web - HTML5/CSS3 @@ -138,6 +154,9 @@ Although the project would be maintained in plain text instead, I promise a smal - V5/[Sencha Touch](http://www.sencha.com/products/touch) - [PhoneGap](http://phonegap.com/) - [jQuery Mobile](http://jquerymobile.com/) + - [W3C Mobile Web Initiative](http://www.w3.org/Mobile/) + - [W3C mobileOK Checker](http://validator.w3.org/mobile/) + - [Open Mobile Alliance](http://openmobilealliance.org/) - Advanced technology communities/conferences - [D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/) - NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂(HTML5 Dreamworks)](http://www.html5dw.com) @@ -154,6 +173,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [OS](http://en.wikipedia.org/wiki/Operating_system) - Algorithm principle - Software Engineering/Software testing principle + - [Unicode](http://www.unicode.org/) - Soft skills - Knowledge Management/Sharing - Communication/Teamwork @@ -163,7 +183,7 @@ Although the project would be maintained in plain text instead, I promise a smal - SVG/Canvas/VML - SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/) - Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/) - - WebGL(http://zh.wikipedia.org/wiki/WebGL):[Three.JS](http://threejs.org/) + - [WebGL](http://zh.wikipedia.org/wiki/WebGL)/[Three.JS](http://threejs.org/) - Backend Engineer - Programming languages - C/C++/Java/PHP/Ruby/Python/... @@ -173,7 +193,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Lighttpd](http://www.lighttpd.net/) - Databases - SQL - - [MySQL](http://www.mysql.com/)/[PostgreSQL](http://www.postgresql.org/)/[Oracle](http://www.oracle.com/us/products/database/overview/index.html) + - [MySQL](http://www.mysql.com/)/[PostgreSQL](http://www.postgresql.org/)/[Oracle](http://www.oracle.com/us/products/database/overview/index.html)/[DB2](http://www-01.ibm.com/software/data/db2) - [MongoDB](http://www.mongodb.org/)/[CouchDB](http://couchdb.apache.org/) - Data Caching - [Redis](http://redis.io/) From d2e425e63c6dec50b1f0207389b3e06250d71596 Mon Sep 17 00:00:00 2001 From: yunxiange Date: Sun, 30 Nov 2014 20:28:00 +0800 Subject: [PATCH 069/107] add HBuilder IDE --- README.en.md | 1 + README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README.en.md b/README.en.md index 319ea47..655439e 100644 --- a/README.en.md +++ b/README.en.md @@ -43,6 +43,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Visual Studio](http://www.visualstudio.com/) - [NetBeans](https://netbeans.org/) - [Cloud9 IDE](http://c9.io/) + - [HBuilder](http://www.dcloud.io/) - Debugging - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) diff --git a/README.md b/README.md index 41707e9..d268eef 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ Frontend Knowledge Structure - [Visual Studio](http://www.visualstudio.com/) - [NetBeans](https://netbeans.org/) - [Cloud9 IDE](http://c9.io/) + - [HBuilder](http://www.dcloud.io/) - 调试工具 - [Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/) - [YSlow](http://developer.yahoo.com/yslow/) From 33017d318c872ee3525077dc03a3b81a0b80223d Mon Sep 17 00:00:00 2001 From: yunxiange Date: Sun, 30 Nov 2014 20:46:01 +0800 Subject: [PATCH 070/107] Add CSS pre-processor to extend the CSS language --- README.en.md | 3 ++- README.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.en.md b/README.en.md index 655439e..5591fa7 100644 --- a/README.en.md +++ b/README.en.md @@ -23,7 +23,8 @@ Although the project would be maintained in plain text instead, I promise a smal - [TypeScript](http://www.typescriptlang.org/) - Slicing - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - - [CSS](http://www.w3.org/Style/CSS/)/CSS3 + - [CSS](http://www.w3.org/Style/CSS/)/CSS3 + - [Sass](http://sass-lang.com/)/[LESS](http://lesscss.org/)/[Stylus](http://learnboost.github.io/stylus/) - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/) - Development tools - Editors and IDEs diff --git a/README.md b/README.md index d268eef..560331e 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Frontend Knowledge Structure - 切页面 - [HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/) - [CSS/CSS3](http://www.w3.org/Style/CSS/) + - [Sass](http://sass-lang.com/)/[LESS](http://lesscss.org/)/[Stylus](http://learnboost.github.io/stylus/) - [PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/) - 开发工具 - 编辑器和IDE From 90d87c2ae9a1bf6f65e0f5faee705d8e4341e505 Mon Sep 17 00:00:00 2001 From: Jason Hao Date: Sun, 21 Dec 2014 23:12:11 -0500 Subject: [PATCH 071/107] add Protractor, SourceLabs, BrowserStack as Automation testing tools, added GitLab as Git repo management tool, TeamForge as a SVN repo management tool --- README.en.md | 5 +++-- README.md | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.en.md b/README.en.md index f115cbb..29d104a 100644 --- a/README.en.md +++ b/README.en.md @@ -48,7 +48,7 @@ Although the project would be maintained in plain text instead, I promise a smal - [Venkman](https://developer.mozilla.org/en-US/docs/Venkman) - Revision Control - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/)/[Mercurial](http://mercurial.selenic.com/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/) + - [Github](https://github.com/)/[GitLab](https://about.gitlab.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/)/[TeamForge](http://www.collab.net/products/teamforge) - Code quality - Coding style - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs) @@ -59,8 +59,9 @@ Although the project would be maintained in plain text instead, I promise a smal - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - [Unit JS](http://unitjs.com/) - Auto-testing - - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Protractor](https://github.com/angular/protractor)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - [phantomjs](http://phantomjs.org/) + - [SourceLabs](https://saucelabs.com/)/[BrowserStack](http://www.browserstack.com/) - Frontend libraries / frameworks - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) diff --git a/README.md b/README.md index c92214f..072d1e2 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Frontend Knowledge Structure - [Venkman](https://developer.mozilla.org/en-US/docs/Venkman) - 版本管理 - [Git](git-scm.com/)/[SVN](http://subversion.apache.org/)/[Mercurial](http://mercurial.selenic.com/) - - [Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/) + - [Github](https://github.com/)/[GitLab](https://about.gitlab.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/)/[TeamForge](http://www.collab.net/products/teamforge) - 代码质量 - Coding style - [JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs) @@ -59,8 +59,9 @@ Frontend Knowledge Structure - [Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/) - [Unit JS](http://unitjs.com/) - 自动化测试 - - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) + - [WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Protractor](https://github.com/angular/protractor)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/) - [phantomjs](http://phantomjs.org/) + - [SourceLabs](https://saucelabs.com/)/[BrowserStack](http://www.browserstack.com/) - 前端库/框架 - [jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/) - [YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/) From ea7ddb7b35084975dc1dc3280d111f0a4bd91641 Mon Sep 17 00:00:00 2001 From: HaoJu Zheng Date: Mon, 19 Jan 2015 23:00:45 +0800 Subject: [PATCH 072/107] submit fks-chart --- fks-chart/bower.json | 20 ++ fks-chart/css/bootstrap.min.css | 5 + fks-chart/css/style.css | 70 +++++ fks-chart/data/front-end.json | 497 ++++++++++++++++++++++++++++++++ fks-chart/index.html | 26 ++ fks-chart/js/app.js | 116 ++++++++ 6 files changed, 734 insertions(+) create mode 100644 fks-chart/bower.json create mode 100644 fks-chart/css/bootstrap.min.css create mode 100644 fks-chart/css/style.css create mode 100644 fks-chart/data/front-end.json create mode 100644 fks-chart/index.html create mode 100644 fks-chart/js/app.js diff --git a/fks-chart/bower.json b/fks-chart/bower.json new file mode 100644 index 0000000..e3a8acb --- /dev/null +++ b/fks-chart/bower.json @@ -0,0 +1,20 @@ +{ + "name": "front-end-collect-", + "version": "0.0.0", + "authors": [ + "hjzheng " + ], + "license": "MIT", + "ignore": [ + "node_modules", + "bower_components", + "test", + "tests" + ], + "dependencies": { + "angular": "~1.2.19", + "d3": "~3.4.9", + "angular-marked": "~0.0.12", + "jquery": "~2.1.3" + } +} diff --git a/fks-chart/css/bootstrap.min.css b/fks-chart/css/bootstrap.min.css new file mode 100644 index 0000000..4af8905 --- /dev/null +++ b/fks-chart/css/bootstrap.min.css @@ -0,0 +1,5 @@ +/*! + * Bootstrap v3.3.0 (http://getbootstrap.com) + * Copyright 2011-2014 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + *//*! normalize.css v3.0.2 | MIT License | git.io/normalize */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:before,:after{color:#000!important;text-shadow:none!important;background:transparent!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="#"]:after,a[href^="javascript:"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(https://github.com/fonts/glyphicons-halflings-regular.eot);src:url(https://github.com/fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(https://github.com/fonts/glyphicons-halflings-regular.woff) format('woff'),url(https://github.com/fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(https://github.com/fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before,.glyphicon-eur:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:before,:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small{font-weight:400;line-height:1;color:#777}h1,.h1,h2,.h2,h3,.h3{margin-top:20px;margin-bottom:10px}h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small{font-size:65%}h4,.h4,h5,.h5,h6,.h6{margin-top:10px;margin-bottom:10px}h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small{font-size:75%}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}small,.small{font-size:85%}mark,.mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#428bca}a.text-primary:hover{color:#3071a9}.text-success{color:#3c763d}a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#428bca}a.bg-primary:hover{background-color:#3071a9}.bg-success{background-color:#dff0d8}a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dt,dd{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote p:last-child,blockquote ul:last-child,blockquote ol:last-child{margin-bottom:0}blockquote footer,blockquote small,blockquote .small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote footer:before,blockquote small:before,blockquote .small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse footer:before,blockquote.pull-right footer:before,.blockquote-reverse small:before,blockquote.pull-right small:before,.blockquote-reverse .small:before,blockquote.pull-right .small:before{content:''}.blockquote-reverse footer:after,blockquote.pull-right footer:after,.blockquote-reverse small:after,blockquote.pull-right small:after,.blockquote-reverse .small:after,blockquote.pull-right .small:after{content:'\00A0 \2014'}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover,.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr.active:hover>th{background-color:#e8e8e8}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr.success:hover>th{background-color:#d0e9c6}.table>thead>tr>td.info,.table>tbody>tr>td.info,.table>tfoot>tr>td.info,.table>thead>tr>th.info,.table>tbody>tr>th.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>tbody>tr.info>td,.table>tfoot>tr.info>td,.table>thead>tr.info>th,.table>tbody>tr.info>th,.table>tfoot>tr.info>th{background-color:#d9edf7}.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover,.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr.info:hover>th{background-color:#c4e3f3}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr.warning:hover>th{background-color:#faf2cc}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr.danger:hover>th{background-color:#ebcccc}.table-responsive{min-height:.01%;overflow-x:auto}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=radio],input[type=checkbox]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=radio]:focus,input[type=checkbox]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#999;opacity:1}.form-control:-ms-input-placeholder{color:#999}.form-control::-webkit-input-placeholder{color:#999}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}input[type=date],input[type=time],input[type=datetime-local],input[type=month]{line-height:34px;line-height:1.42857143 \0}input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px;line-height:1.5 \0}input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px;line-height:1.33 \0}_:-ms-fullscreen,:root input[type=date],_:-ms-fullscreen,:root input[type=time],_:-ms-fullscreen,:root input[type=datetime-local],_:-ms-fullscreen,:root input[type=month]{line-height:1.42857143}_:-ms-fullscreen.input-sm,:root input[type=date].input-sm,_:-ms-fullscreen.input-sm,:root input[type=time].input-sm,_:-ms-fullscreen.input-sm,:root input[type=datetime-local].input-sm,_:-ms-fullscreen.input-sm,:root input[type=month].input-sm{line-height:1.5}_:-ms-fullscreen.input-lg,:root input[type=date].input-lg,_:-ms-fullscreen.input-lg,:root input[type=time].input-lg,_:-ms-fullscreen.input-lg,:root input[type=datetime-local].input-lg,_:-ms-fullscreen.input-lg,:root input[type=month].input-lg{line-height:1.33}.form-group{margin-bottom:15px}.radio,.checkbox{position:relative;display:block;margin-top:10px;margin-bottom:10px}.radio label,.checkbox label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.radio input[type=radio],.radio-inline input[type=radio],.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox]{position:absolute;margin-top:4px \9;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type=radio][disabled],input[type=checkbox][disabled],input[type=radio].disabled,input[type=checkbox].disabled,fieldset[disabled] input[type=radio],fieldset[disabled] input[type=checkbox]{cursor:not-allowed}.radio-inline.disabled,.checkbox-inline.disabled,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.radio.disabled label,.checkbox.disabled label,fieldset[disabled] .radio label,fieldset[disabled] .checkbox label{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm,.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm,select.form-group-sm .form-control{height:30px;line-height:30px}textarea.input-sm,textarea.form-group-sm .form-control,select[multiple].input-sm,select[multiple].form-group-sm .form-control{height:auto}.input-lg,.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg,select.form-group-lg .form-control{height:46px;line-height:46px}textarea.input-lg,textarea.form-group-lg .form-control,select[multiple].input-lg,select[multiple].form-group-lg .form-control{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline,.has-success.radio label,.has-success.checkbox label,.has-success.radio-inline label,.has-success.checkbox-inline label{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline,.has-warning.radio label,.has-warning.checkbox label,.has-warning.radio-inline label,.has-warning.checkbox-inline label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline,.has-error.radio label,.has-error.checkbox label,.has-error.radio-inline label,.has-error.checkbox-inline label{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:25px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .radio label,.form-inline .checkbox label{padding-left:0}.form-inline .radio input[type=radio],.form-inline .checkbox input[type=checkbox]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:14.3px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn:focus,.btn:active:focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn.active.focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus,.btn.focus{color:#333;text-decoration:none}.btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default.focus,.btn-default:active,.btn-default.active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default:active,.btn-default.active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled.focus,.btn-default[disabled].focus,fieldset[disabled] .btn-default.focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary.focus,.btn-primary:active,.btn-primary.active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#3071a9;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled.focus,.btn-primary[disabled].focus,fieldset[disabled] .btn-primary.focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success.focus,.btn-success:active,.btn-success.active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success:active,.btn-success.active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled.focus,.btn-success[disabled].focus,fieldset[disabled] .btn-success.focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info.focus,.btn-info:active,.btn-info.active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info:active,.btn-info.active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled.focus,.btn-info[disabled].focus,fieldset[disabled] .btn-info.focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning.focus,.btn-warning:active,.btn-warning.active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled.focus,.btn-warning[disabled].focus,fieldset[disabled] .btn-warning.focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger.focus,.btn-danger:active,.btn-danger.active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled.focus,.btn-danger[disabled].focus,fieldset[disabled] .btn-danger.focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#428bca;border-radius:0}.btn-link,.btn-link:active,.btn-link.active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#777;text-decoration:none}.btn-lg,.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs,.btn-group-xs>.btn{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none;visibility:hidden}.collapse.in{display:block;visibility:visible}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-timing-function:ease;-o-transition-timing-function:ease;transition-timing-function:ease;-webkit-transition-duration:.35s;-o-transition-duration:.35s;transition-duration:.35s;-webkit-transition-property:height,visibility;-o-transition-property:height,visibility;transition-property:height,visibility}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#428bca;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#777}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px solid}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=radio],[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn,select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn,select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=radio],.input-group-addon input[type=checkbox]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none;visibility:hidden}.tab-content>.active{display:block;visibility:visible}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important;visibility:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{max-height:200px}}.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn,.navbar-form .input-group .form-control{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .radio label,.navbar-form .checkbox label{padding-left:0}.navbar-form .radio input[type=radio],.navbar-form .checkbox input[type=checkbox]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:hover,.navbar-default .btn-link:focus{color:#333}.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:hover,.navbar-default .btn-link[disabled]:focus,fieldset[disabled] .navbar-default .btn-link:focus{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:hover,.navbar-inverse .btn-link:focus{color:#fff}.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:hover,.navbar-inverse .btn-link[disabled]:focus,fieldset[disabled] .navbar-inverse .btn-link:focus{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#428bca;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;cursor:default;background-color:#428bca;border-color:#428bca}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:hover,a.label:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:hover,.label-default[href]:focus{background-color:#5e5e5e}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-xs .badge{top:0;padding:1px 5px}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px 15px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron h1,.jumbotron .h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron,.container-fluid .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding:48px 0}.container .jumbotron{padding-right:60px;padding-left:60px}.jumbotron h1,.jumbotron .h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail>img,.thumbnail a>img{margin-right:auto;margin-left:auto}a.thumbnail:hover,a.thumbnail:focus,a.thumbnail.active{border-color:#428bca}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar,.progress-bar-striped{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress.active .progress-bar,.progress-bar.active{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-left,.media-right,.media-body{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{color:#555;text-decoration:none;background-color:#f5f5f5}.list-group-item.disabled,.list-group-item.disabled:hover,.list-group-item.disabled:focus{color:#777;cursor:not-allowed;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}.list-group-item.active .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>.small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:hover .list-group-item-text,.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:hover,a.list-group-item-success:focus{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:hover,a.list-group-item-success.active:focus{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:hover,a.list-group-item-info:focus{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:hover,a.list-group-item-info.active:focus{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:hover,a.list-group-item-warning:focus{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:hover,a.list-group-item-warning.active:focus{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:hover,a.list-group-item-danger:focus{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:hover,a.list-group-item-danger.active:focus{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.table,.panel>.table-responsive>.table,.panel>.panel-collapse>.table{margin-bottom:0}.panel>.table caption,.panel>.table-responsive>.table caption,.panel>.panel-collapse>.table caption{padding-right:15px;padding-left:15px}.panel>.table:first-child,.panel>.table-responsive:first-child>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table:last-child,.panel>.table-responsive:last-child>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child th,.panel>.table>tbody:first-child>tr:first-child td{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.panel-body,.panel-group .panel-heading+.panel-collapse>.list-group{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#428bca}.panel-primary>.panel-heading .badge{color:#428bca;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive iframe,.embed-responsive embed,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{min-height:16.43px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-size:12px;line-height:1.4;visibility:visible;filter:alpha(opacity=0);opacity:0}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-size:14px;font-weight:400;line-height:1.42857143;text-align:left;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2)}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;-o-transition:-o-transform .6s ease-in-out;transition:transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000;perspective:1000}.carousel-inner>.item.next,.carousel-inner>.item.active.right{left:0;-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}.carousel-inner>.item.prev,.carousel-inner>.item.active.left{left:0;-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right,.carousel-inner>.item.active{left:0;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .glyphicon-chevron-left{left:50%;margin-left:-10px}.carousel-control .icon-next,.carousel-control .glyphicon-chevron-right{right:50%;margin-right:-10px}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-15px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-15px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after,.dl-horizontal dd:before,.dl-horizontal dd:after,.container:before,.container:after,.container-fluid:before,.container-fluid:after,.row:before,.row:after,.form-horizontal .form-group:before,.form-horizontal .form-group:after,.btn-toolbar:before,.btn-toolbar:after,.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after,.nav:before,.nav:after,.navbar:before,.navbar:after,.navbar-header:before,.navbar-header:after,.navbar-collapse:before,.navbar-collapse:after,.pager:before,.pager:after,.panel-body:before,.panel-body:after,.modal-footer:before,.modal-footer:after{display:table;content:" "}.clearfix:after,.dl-horizontal dd:after,.container:after,.container-fluid:after,.row:after,.form-horizontal .form-group:after,.btn-toolbar:after,.btn-group-vertical>.btn-group:after,.nav:after,.navbar:after,.navbar-header:after,.navbar-collapse:after,.pager:after,.panel-body:after,.modal-footer:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-xs,.visible-sm,.visible-md,.visible-lg{display:none!important}.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}} \ No newline at end of file diff --git a/fks-chart/css/style.css b/fks-chart/css/style.css new file mode 100644 index 0000000..ef9d92a --- /dev/null +++ b/fks-chart/css/style.css @@ -0,0 +1,70 @@ +/*Dendrogram*/ +.node circle { + fill: #fff; + stroke: steelblue; + stroke-width: 1.5px; +} + +.node { + font: 20px sans-serif; + cursor: pointer; +} + +.node text:hover { + fill: steelblue; +} + +.link { + fill: none; + stroke: #ccc; + stroke-width: 1.5px; +} + +/*tooltip*/ +#tooltip { + position: fixed; + min-width: 200px; + height: auto; + padding: 10px; + background-color: #444; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border-radius: 10px; + -webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4); + -moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4); + box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4); + color: #fff; +} + +#tooltip.hidden { + display: none; +} + +#tooltip p { + margin: 0; + font-family: sans-serif; + font-size: 16px; + line-height: 20px; +} + +.title { + width: 460px; + position: fixed; + top: 10px; + right: -40px; + height: auto; + padding: 10px; + margin: 15px; + background-color: #444; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border-radius: 10px; + -webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4); + -moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4); + box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4); + color: #fff; +} + +a:hover { + text-decoration: none; +} diff --git a/fks-chart/data/front-end.json b/fks-chart/data/front-end.json new file mode 100644 index 0000000..80b8447 --- /dev/null +++ b/fks-chart/data/front-end.json @@ -0,0 +1,497 @@ +{ + "id": "0", + "name": "前端工程师", + "children": [{ + "id": "1", + "name": "浏览器", + "children": [{ + "id": "2", + "name": "IE6/[7](http://www.microsoft.com/en-US/download/details.aspx?id=2)/[8](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-8)/[9](http://windows.microsoft.com/en-US/internet-explorer/downloads/ie-9/worldwide-languages)/[10](http://windows.microsoft.com/en-US/internet-explorer/ie-10-worldwide-languages)/[11](http://windows.microsoft.com/en-US/internet-explorer/ie-11-worldwide-languages) (Trident)" + }, { + "id": "3", + "name": "[Firefox](http://www.mozilla.org/en-US/) (Gecko)" + }, { + "id": "4", + "name": "[Chrome](http://www.google.com/chrome)/[Chromium](http://www.chromium.org/) (Blink)" + }, { + "id": "5", + "name": "[Safari](http://www.apple.com/safari/) (WebKit)" + }, { + "id": "6", + "name": "[Opera](http://www.opera.com/) (Blink)" + }] + }, { + "id": "7", + "name": "编程语言", + "children": [{ + "id": "8", + "name": "[JavaScript](https://developer.mozilla.org/en-US/docs/JavaScript)/[Node.js](http://nodejs.org/)" + }, { + "id": "9", + "name": "[CoffeeScript](http://coffeescript.org/)" + }, { + "id": "10", + "name": "[TypeScript](http://www.typescriptlang.org/)" + }] + }, { + "id": "11", + "name": "切页面", + "children": [{ + "id": "12", + "name": "[HTML](http://www.w3.org/html/)/[HTML5](http://www.w3.org/TR/html5/)" + }, { + "id": "13", + "name": "[CSS/CSS3](http://www.w3.org/Style/CSS/)" + }, { + "id": "14", + "name": "[PhotoShop](http://www.photoshop.com/products/photoshop)/[Paint.net](http://www.getpaint.net/)/[Fireworks](http://www.adobe.com/cn/products/fireworks.html)/[GIMP](http://www.gimp.org/)" + }] + }, { + "id": "15", + "name": "开发工具", + "children": [{ + "id": "16", + "name": "编辑器和IDE", + "children": [{ + "id": "17", + "name": "[VIM](http://www.vim.org/)/[Sublime Text2](http://www.sublimetext.com/)" + }, { + "id": "18", + "name": "[Notepad++](http://notepad-plus-plus.org/)/[EditPlus](http://www.editplus.com/)" + }, { + "id": "19", + "name": "[WebStorm](http://www.jetbrains.com/webstorm/)" + }, { + "id": "20", + "name": "[Emacs](http://www.gnu.org/software/emacs/) [EmacsWiki](http://emacswiki.org)" + }, { + "id": "21", + "name": "[Brackets](http://brackets.io)" + }, { + "id": "22", + "name": "[Komodo IDE / Edit](http://www.activestate.com/komodo-edit)" + }, { + "id": "23", + "name": "[Eclipse](http://www.eclipse.org/)" + }, { + "id": "24", + "name": "[Visual Studio](http://www.visualstudio.com/)" + }, { + "id": "25", + "name": "[NetBeans](https://netbeans.org/)" + }, { + "id": "26", + "name": "[Cloud9 IDE](http://c9.io/)" + }] + }, { + "id": "27", + "name": "调试工具", + "children": [{ + "id": "28", + "name": "[Firebug](http://getfirebug.com/)/[Firecookie](https://addons.mozilla.org/en-US/firefox/addon/firecookie/)" + }, { + "id": "29", + "name": "[YSlow](http://developer.yahoo.com/yslow/)" + }, { + "id": "30", + "name": "[IEDeveloperToolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359)/[IETester](http://www.my-debugbar.com/wiki/IETester/HomePage)" + }, { + "id": "31", + "name": "[Fiddler](http://www.fiddler2.com/fiddler2/)" + }, { + "id": "32", + "name": "[Chrome Dev Tools](https://developers.google.com/chrome-developer-tools/)" + }, { + "id": "33", + "name": "[Dragonfly](http://www.opera.com/dragonfly/)" + }, { + "id": "34", + "name": "[DebugBar](http://www.debugbar.com/)" + }, { + "id": "35", + "name": "[Venkman](https://developer.mozilla.org/en-US/docs/Venkman)" + }] + }, { + "id": "36", + "name": "版本管理", + "children": [{ + "id": "37", + "name": "[Git](git-scm.com/)/[SVN](http://subversion.apache.org/)/[Mercurial](http://mercurial.selenic.com/)" + }, { + "id": "38", + "name": "[Github](https://github.com/)/[Bitbucket](https://bitbucket.org/)/[Google Code](http://code.google.com/hosting/)/[Gitorious](https://gitorious.org/)/[GNU Savannah](http://savannah.gnu.org/)/[Launchpad](https://launchpad.net/)/[SourceForge](http://sourceforge.net/)" + }] + }] + }, { + "id": "39", + "name": "代码质量", + "children": [{ + "id": "40", + "name": "Coding style", + "children": [{ + "id": "41", + "name": "[JSLint](http://www.jslint.com/)/[JSHint](http://www.jshint.com/)/[jscs](https://github.com/mdevils/node-jscs)" + }, { + "id": "42", + "name": "[CSSLint](http://csslint.net/)" + }, { + "id": "43", + "name": "[Markup Validation Service](http://validator.w3.org/)" + }] + }, { + "id": "44", + "name": "单元测试", + "children": [{ + "id": "45", + "name": "[QUnit](http://qunitjs.com/)/[Jasmine](http://pivotal.github.com/jasmine/)" + }, { + "id": "46", + "name": "[Mocha](http://visionmedia.github.com/mocha/)/[Should](https://github.com/visionmedia/should.js/)/[Chai](http://chaijs.com/)/[Expect](https://github.com/LearnBoost/expect.js/)" + }, { + "id": "47", + "name": "[Unit JS](http://unitjs.com/)" + }] + }, { + "id": "48", + "name": "自动化测试", + "children": [{ + "id": "49", + "name": "[WebDriver](http://docs.seleniumhq.org/docs/03_webdriver.jsp)/[Karma Runner](https://github.com/karma-runner/karma)/[Sahi](http://sahi.co.in/)" + }, { + "id": "50", + "name": "[phantomjs](http://phantomjs.org/)" + }] + }] + }, { + "id": "51", + "name": "前端库/框架", + "children": [{ + "id": "52", + "name": "[jQuery](http://jquery.com/)/[Underscore](http://underscorejs.org/)/[Mootools](http://mootools.net/)/[Prototype.js](http://www.prototypejs.org/)" + }, { + "id": "53", + "name": "[YUI3](http://yuilibrary.com/projects/yui3/)/[Dojo](http://dojotoolkit.org/)/[ExtJS](http://www.sencha.com/products/extjs)/[KISSY](http://docs.kissyui.com/)" + }, { + "id": "54", + "name": "[Backbone](http://backbonejs.org/)/[KnockoutJS](http://knockoutjs.com/)/[Emberjs](http://emberjs.com/)" + }, { + "id": "55", + "name": "[AngularJS](http://angularjs.org/)", + "children": [{ + "id": "56", + "name": "[Batarang](https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk)" + }] + }, { + "id": "57", + "name": "[Bootstrap](http://getbootstrap.com/)" + }, { + "id": "58", + "name": "[Semantic UI](http://www.semantic-ui.com/)" + }, { + "id": "59", + "name": "[Juice UI](http://juiceui.com/)" + }, { + "id": "60", + "name": "[Web Atoms](http://webatomsjs.neurospeech.com/)" + }, { + "id": "61", + "name": "[Polymer](http://docs.polymerchina.org/)" + }] + }, { + "id": "62", + "name": "前端标准/规范", + "children": [{ + "id": "63", + "name": "[HTTP1.1](http://www.w3.org/Protocols/rfc2616/rfc2616.html)" + }, { + "id": "64", + "name": "[ECMAScript3/5](http://www.ecma-international.org/publications/standards/Ecma-262.htm)" + }, { + "id": "65", + "name": "[W3C/DOM/BOM/XHTML/XML/JSON/JSONP](http://www.w3.org/TR/)" + }, { + "id": "66", + "name": "[CommonJS Modules](http://wiki.commonjs.org/wiki/Modules/1.0)/[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)" + }, { + "id": "67", + "name": "[HTML5](http://www.w3.org/html/wg/drafts/html/master/)/[CSS3](http://www.w3.org/Style/CSS/specs.en.html)" + }, { + "id": "68", + "name": "[Semantic Web](http://semanticweb.org/)", + "children": [{ + "id": "69", + "name": "[MicroData](http://schema.org)" + }, { + "id": "70", + "name": "[RDFa](http://www.w3.org/TR/rdfa-core/)" + }] + }, { + "id": "71", + "name": "[Web Accessibility](http://www.w3.org/TR/WAI-WEBCONTENT/)", + "children": [{ + "id": "72", + "name": "[Role Attribute](http://www.w3.org/TR/role-attribute/)" + }, { + "id": "73", + "name": "[WAI-ARIA](http://www.w3.org/TR/wai-aria/)" + }] + }] + }, { + "id": "74", + "name": "性能", + "children": [{ + "id": "75", + "name": "[JSPerf](http://jsperf.com/)" + }, { + "id": "76", + "name": "[YSlow 35 rules](http://developer.yahoo.com/performance/rules.html)" + }, { + "id": "77", + "name": "[PageSpeed](https://developers.google.com/speed/pagespeed/)" + }, { + "id": "78", + "name": "[HTTPWatch](http://www.httpwatch.com/)" + }, { + "id": "79", + "name": "[DynaTrace's Ajax](http://www.compuware.com/application-performance-management/dynatrace-ajax-download.html)" + }, { + "id": "80", + "name": "[高性能JavaScript](http://book.douban.com/subject/5362856/)" + }] + }, { + "id": "81", + "name": "SEO" + }, { + "id": "82", + "name": "编程知识储备", + "children": [{ + "id": "83", + "name": "[数据结构](http://zh.wikipedia.org/wiki/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84)" + }, { + "id": "84", + "name": "OOP/AOP" + }, { + "id": "85", + "name": "[原型链](http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/)/作用域链" + }, { + "id": "86", + "name": "[闭包](http://www.jibbering.com/faq/notes/closures/)" + }, { + "id": "87", + "name": "[编程范型](http://zh.wikipedia.org/wiki/%E7%BC%96%E7%A8%8B%E8%8C%83%E5%9E%8B)" + }, { + "id": "88", + "name": "[设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/)" + }, { + "id": "89", + "name": "[Javascript Tips](http://sanshi.me/articles/JavaScript-Garden-CN/html/index.html)" + }] + }, { + "id": "90", + "name": "部署流程", + "children": [{ + "id": "91", + "name": "压缩合并", + "children": [{ + "id": "92", + "name": "[YUI Compressor](http://developer.yahoo.com/yui/compressor/)" + }, { + "id": "93", + "name": "[Google Clousure Complier](https://developers.google.com/closure/compiler/)" + }, { + "id": "94", + "name": "[UglifyJS](https://github.com/mishoo/UglifyJS)" + }, { + "id": "95", + "name": "[CleanCSS](https://github.com/GoalSmashers/clean-css)" + }] + }, { + "id": "96", + "name": "文档输出", + "children": [{ + "id": "97", + "name": "[JSDoc](https://github.com/jsdoc3/jsdoc)" + }, { + "id": "98", + "name": "[Dox](https://github.com/visionmedia/dox)/[Doxmate](https://github.com/JacksonTian/doxmate)/[Grunt-Doxmate](https://github.com/luozhihua/grunt-doxmate)" + }] + }, { + "id": "99", + "name": "项目构建工具", + "children": [{ + "id": "100", + "name": "[make](http://www.gnu.org/software/make/)/[Ant](http://ant.apache.org/)" + }, { + "id": "101", + "name": "[GYP](http://code.google.com/p/gyp/)" + }, { + "id": "102", + "name": "[Grunt](http://gruntjs.com/)" + }, { + "id": "103", + "name": "[Gulp](http://gulpjs.com/)" + }, { + "id": "104", + "name": "[Yeoman](http://yeoman.io/)" + }, { + "id": "105", + "name": "[FIS](http://fis.baidu.com/)" + }, { + "id": "106", + "name": "[Mod](https://github.com/modulejs/modjs)" + }] + }] + }, { + "id": "107", + "name": "代码组织", + "children": [{ + "id": "108", + "name": "类库模块化", + "children": [{ + "id": "109", + "name": "[CommonJS](http://www.commonjs.org/)/AMD" + }, { + "id": "110", + "name": "[YUI3模块](http://yuilibrary.com/projects/yui3/)" + }] + }, { + "id": "111", + "name": "业务逻辑模块化", + "children": [{ + "id": "112", + "name": "[bower](https://github.com/twitter/bower)/[component](https://github.com/component/component)" + }] + }, { + "id": "113", + "name": "文件加载", + "children": [{ + "id": "114", + "name": "[LABjs](http://labjs.com/)" + }, { + "id": "115", + "name": "[SeaJS](http://seajs.org/)/[Require.js](http://requirejs.org/)" + }] + }, { + "id": "116", + "name": "模块化预处理器", + "children": [{ + "id": "117", + "name": "[Browserify](https://github.com/substack/node-browserify)" + }] + }] + }, { + "id": "118", + "name": "安全", + "children": [{ + "id": "119", + "name": "[CSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)/[XSS](http://en.wikipedia.org/wiki/Cross-site_scripting)" + }, { + "id": "120", + "name": "ADsafe/Caja/Sandbox" + }] + }, { + "id": "121", + "name": "移动Web", + "children": [{ + "id": "122", + "name": "HTML5/CSS3" + }, { + "id": "123", + "name": "[响应式网页设计](http://zh.wikipedia.org/wiki/%E5%93%8D%E5%BA%94%E5%BC%8F%E7%BD%91%E9%A1%B5%E8%AE%BE%E8%AE%A1)" + }, { + "id": "124", + "name": "[Zeptojs](http://zeptojs.com/)/[iScroll](http://cubiq.org/iscroll)" + }, { + "id": "125", + "name": "V5/[Sencha Touch](http://www.sencha.com/products/touch)" + }, { + "id": "126", + "name": "[PhoneGap](http://phonegap.com/)" + }, { + "id": "127", + "name": "[jQuery Mobile](http://jquerymobile.com/)" + }] + }, { + "id": "128", + "name": "前沿技术社区/会议", + "children": [{ + "id": "129", + "name": "[D2](http://d2forum.org)/[WebRebuild](http://www.webrebuild.org/)" + }, { + "id": "130", + "name": "NodeParty/[W3CTech](http://w3ctech.com)/[HTML5梦工厂](http://www.html5dw.com)" + }, { + "id": "131", + "name": "[JSConf](http://jsconf.com/)/[沪JS(JSConf.cn)](http://jsconf.cn)" + }, { + "id": "132", + "name": "QCon/Velocity/SDCC" + }, { + "id": "133", + "name": "[JSConf](http://jsconf.com/)/[NodeConf](http://www.nodeconf.com/)" + }, { + "id": "134", + "name": "[CSSConf](http://cssconf.com/)" + }, { + "id": "135", + "name": "YDN/YUIConf" + }, { + "id": "136", + "name": "HybridApp" + }, { + "id": "137", + "name": "[WHATWG](http://whatwg.org/)" + }] + }, { + "id": "138", + "name": "计算机知识储备", + "children": [{ + "id": "139", + "name": "编译原理" + }, { + "id": "140", + "name": "[计算机网络](http://zh.wikipedia.org/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C)" + }, { + "id": "141", + "name": "[操作系统](http://zh.wikipedia.org/wiki/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F)" + }, { + "id": "142", + "name": "算法原理" + }, { + "id": "143", + "name": "软件工程/软件测试原理" + }] + }, { + "id": "144", + "name": "软技能", + "children": [{ + "id": "145", + "name": "知识管理/总结分享" + }, { + "id": "146", + "name": "沟通技巧/团队协作" + }, { + "id": "147", + "name": "需求管理/PM" + }, { + "id": "148", + "name": "交互设计/可用性/可访问性知识" + }] + }, { + "id": "149", + "name": "可视化", + "children": [{ + "id": "150", + "name": "SVG/Canvas/VML" + }, { + "id": "151", + "name": "SVG: [D3](http://d3js.org/)/[Raphaël](http://raphaeljs.com/)/[Snap.svg](http://snapsvg.io/)/[DataV](http://datavlab.org/datavjs/)" + }, { + "id": "152", + "name": "Canvas: [CreateJS](http://www.createjs.com/)/[KineticJS](http://kineticjs.com/)" + }, { + "id": "153", + "name": "WebGL(http://zh.wikipedia.org/wiki/WebGL):[Three.JS](http://threejs.org/)" + }] + }] +} diff --git a/fks-chart/index.html b/fks-chart/index.html new file mode 100644 index 0000000..fd9b1be --- /dev/null +++ b/fks-chart/index.html @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + +

+ Frontend Knowledge Structure Chart +

Follow me on Github

+

+ + + diff --git a/fks-chart/js/app.js b/fks-chart/js/app.js new file mode 100644 index 0000000..8d5d1b3 --- /dev/null +++ b/fks-chart/js/app.js @@ -0,0 +1,116 @@ +angular.module('frontEnd', ["hc.marked"]) + .factory('data', ['$http', function($http) { + return { + getFrontEndData: function() { + var url = 'data/front-end.json'; + return $http.get(url); + } + }; + }]) + .controller('frontEndCtrl', ['$scope', '$window', 'data', + function($scope, $window, data) { + $scope.type = 'Dendrogram'; + $scope.frontEndData = ''; + + $window.addEventListener('resize', function() { + $scope.$broadcast('windowResize'); + }); + + data.getFrontEndData() + .success(function(res) { + if (res.error) { + throw new Error(res.message); + } else { + $scope.frontEndData = res + } + }); + } + ]).directive('frontEndChart', ['data','$window', "marked", function(data, $window, marked) { + + var link = function($scope, $el, $attrs) { + + var radius = 1200 / 2; + + var cluster = d3.layout.cluster() + .size([360, radius - 120]); + + var diagonal = d3.svg.diagonal.radial() + .projection(function(d) { + return [d.y, d.x / 180 * Math.PI]; + }); + + var svg = d3.select($el[0]).append("svg") + .attr("width", radius * 2) + .attr("height", radius * 2) + .call( + d3.behavior.zoom().scaleExtent([0.6, 3]).on("zoom", zoom) + ); + + var g = svg.append("g") + .attr("transform", "translate(" + radius + "," + radius + ")"); + + function zoom () { + //svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")" ); + } + + var update = function() { + if ($scope.frontEndData === '') return; + + var data = $scope.frontEndData; + + var nodes = cluster.nodes(data); + + var link = g.selectAll("path.link") + .data(cluster.links(nodes)) + .enter().append("path") + .attr("class", "link") + .attr("d", diagonal); + + var node = g.selectAll("g.node") + .data(nodes) + .enter().append("g") + .attr("class", "node") + .attr("transform", function(d) { + return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; + }); + + node.append("circle") + .attr("r", 4.5); + + node.append("text") + .attr("dy", ".31em") + .attr("text-anchor", function(d) { + return d.x < 180 ? "start" : "end"; + }) + .attr("transform", function(d) { + return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; + }) + .text(function(d) { + return $(marked(d.name)).text(); + }) + .attr("fill", "#000") + .on("click", function(d) { + + //Update the tooltip position and value + d3.select("#tooltip") + .style("left", 10 + "px") + .style("top", 10 + "px") + + $("#name").html(marked(d.name)); + + //Show the tooltip + d3.select("#tooltip").classed("hidden", false); + }); + }; + + $scope.$watch('frontEndData', update); + + }; + return { + template: '
', + replace: true, + link: link, + restrict: 'E' + }; + } +]); \ No newline at end of file From 7b619ee711f468e558f757ff67fe0064ab635a29 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Tue, 20 Jan 2015 12:36:52 +0800 Subject: [PATCH 073/107] Use fks-chart --- bin/generate.js | 2 +- .../angular-marked/.bower.json | 41 + .../bower_components/angular-marked/README.md | 86 + .../angular-marked/angular-marked.js | 64 + .../angular-marked/angular-marked.min.js | 6 + .../angular-marked/bower.json | 31 + .../angular-marked/example/index.html | 91 + .../angular-marked/gruntfile.js | 50 + .../angular-marked/karma.conf.js | 55 + .../angular-marked/package.json | 39 + .../bower_components/angular-marked/todo.md | 8 + .../bower_components/angular/.bower.json | 17 + fks-chart/bower_components/angular/README.md | 67 + .../bower_components/angular/angular-csp.css | 24 + fks-chart/bower_components/angular/angular.js | 22154 ++++++++++++++++ .../bower_components/angular/angular.min.js | 217 + .../angular/angular.min.js.gzip | Bin 0 -> 40123 bytes .../angular/angular.min.js.map | 8 + fks-chart/bower_components/angular/bower.json | 8 + .../bower_components/angular/package.json | 25 + fks-chart/bower_components/d3/.bower.json | 34 + fks-chart/bower_components/d3/.spmignore | 4 + fks-chart/bower_components/d3/CONTRIBUTING.md | 25 + fks-chart/bower_components/d3/LICENSE | 26 + fks-chart/bower_components/d3/README.md | 9 + fks-chart/bower_components/d3/bower.json | 24 + fks-chart/bower_components/d3/composer.json | 19 + fks-chart/bower_components/d3/d3.js | 9215 +++++++ fks-chart/bower_components/d3/d3.min.js | 5 + fks-chart/bower_components/jquery/.bower.json | 37 + .../bower_components/jquery/MIT-LICENSE.txt | 21 + fks-chart/bower_components/jquery/bower.json | 27 + .../bower_components/jquery/dist/jquery.js | 9205 +++++++ .../jquery/dist/jquery.min.js | 5 + .../jquery/dist/jquery.min.map | 1 + fks-chart/bower_components/jquery/src/ajax.js | 786 + .../bower_components/jquery/src/ajax/jsonp.js | 89 + .../bower_components/jquery/src/ajax/load.js | 75 + .../jquery/src/ajax/parseJSON.js | 13 + .../jquery/src/ajax/parseXML.js | 28 + .../jquery/src/ajax/script.js | 64 + .../jquery/src/ajax/var/nonce.js | 5 + .../jquery/src/ajax/var/rquery.js | 3 + .../bower_components/jquery/src/ajax/xhr.js | 136 + .../bower_components/jquery/src/attributes.js | 11 + .../jquery/src/attributes/attr.js | 141 + .../jquery/src/attributes/classes.js | 158 + .../jquery/src/attributes/prop.js | 94 + .../jquery/src/attributes/support.js | 35 + .../jquery/src/attributes/val.js | 161 + .../bower_components/jquery/src/callbacks.js | 205 + fks-chart/bower_components/jquery/src/core.js | 497 + .../jquery/src/core/access.js | 60 + .../bower_components/jquery/src/core/init.js | 123 + .../jquery/src/core/parseHTML.js | 39 + .../bower_components/jquery/src/core/ready.js | 97 + .../jquery/src/core/var/rsingleTag.js | 4 + fks-chart/bower_components/jquery/src/css.js | 450 + .../jquery/src/css/addGetHookIf.js | 22 + .../bower_components/jquery/src/css/curCSS.js | 57 + .../jquery/src/css/defaultDisplay.js | 70 + .../jquery/src/css/hiddenVisibleSelectors.js | 15 + .../jquery/src/css/support.js | 96 + .../bower_components/jquery/src/css/swap.js | 28 + .../jquery/src/css/var/cssExpand.js | 3 + .../jquery/src/css/var/getStyles.js | 12 + .../jquery/src/css/var/isHidden.js | 13 + .../jquery/src/css/var/rmargin.js | 3 + .../jquery/src/css/var/rnumnonpx.js | 5 + fks-chart/bower_components/jquery/src/data.js | 178 + .../bower_components/jquery/src/data/Data.js | 181 + .../jquery/src/data/accepts.js | 20 + .../jquery/src/data/var/data_priv.js | 5 + .../jquery/src/data/var/data_user.js | 5 + .../bower_components/jquery/src/deferred.js | 149 + .../bower_components/jquery/src/deprecated.js | 13 + .../bower_components/jquery/src/dimensions.js | 50 + .../bower_components/jquery/src/effects.js | 648 + .../jquery/src/effects/Tween.js | 114 + .../jquery/src/effects/animatedSelector.js | 13 + .../bower_components/jquery/src/event.js | 868 + .../bower_components/jquery/src/event/ajax.js | 13 + .../jquery/src/event/alias.js | 39 + .../jquery/src/event/support.js | 9 + .../jquery/src/exports/amd.js | 24 + .../jquery/src/exports/global.js | 32 + .../bower_components/jquery/src/intro.js | 44 + .../bower_components/jquery/src/jquery.js | 37 + .../jquery/src/manipulation.js | 580 + .../jquery/src/manipulation/_evalUrl.js | 18 + .../jquery/src/manipulation/support.js | 32 + .../src/manipulation/var/rcheckableType.js | 3 + .../bower_components/jquery/src/offset.js | 207 + .../bower_components/jquery/src/outro.js | 1 + .../bower_components/jquery/src/queue.js | 142 + .../jquery/src/queue/delay.js | 22 + .../jquery/src/selector-native.js | 172 + .../jquery/src/selector-sizzle.js | 14 + .../bower_components/jquery/src/selector.js | 1 + .../bower_components/jquery/src/serialize.js | 111 + .../jquery/src/sizzle/dist/sizzle.js | 2067 ++ .../jquery/src/sizzle/dist/sizzle.min.js | 3 + .../jquery/src/sizzle/dist/sizzle.min.map | 1 + .../bower_components/jquery/src/traversing.js | 199 + .../jquery/src/traversing/findFilter.js | 100 + .../src/traversing/var/rneedsContext.js | 6 + .../bower_components/jquery/src/var/arr.js | 3 + .../jquery/src/var/class2type.js | 4 + .../bower_components/jquery/src/var/concat.js | 5 + .../bower_components/jquery/src/var/hasOwn.js | 5 + .../jquery/src/var/indexOf.js | 5 + .../bower_components/jquery/src/var/pnum.js | 3 + .../bower_components/jquery/src/var/push.js | 5 + .../jquery/src/var/rnotwhite.js | 3 + .../bower_components/jquery/src/var/slice.js | 5 + .../jquery/src/var/strundefined.js | 3 + .../jquery/src/var/support.js | 4 + .../jquery/src/var/toString.js | 5 + fks-chart/bower_components/jquery/src/wrap.js | 79 + fks-chart/bower_components/marked/.bower.json | 14 + fks-chart/bower_components/marked/.gitignore | 1 + fks-chart/bower_components/marked/.npmignore | 2 + fks-chart/bower_components/marked/.travis.yml | 5 + fks-chart/bower_components/marked/LICENSE | 19 + fks-chart/bower_components/marked/Makefile | 12 + fks-chart/bower_components/marked/README.md | 386 + fks-chart/bower_components/marked/bin/marked | 187 + .../bower_components/marked/component.json | 10 + .../bower_components/marked/doc/broken.md | 426 + fks-chart/bower_components/marked/doc/todo.md | 2 + fks-chart/bower_components/marked/index.js | 1 + .../bower_components/marked/lib/marked.js | 1266 + .../bower_components/marked/man/marked.1 | 88 + .../bower_components/marked/package.json | 22 + fks-chart/bower_components/marked/test/README | 10 + .../marked/test/browser/index.html | 5 + .../marked/test/browser/index.js | 41 + .../marked/test/browser/test.js | 62 + .../bower_components/marked/test/index.js | 543 + .../marked/test/new/autolink_lines.html | 3 + .../marked/test/new/autolink_lines.text | 2 + .../marked/test/new/blockquote_list_item.html | 3 + .../marked/test/new/blockquote_list_item.text | 4 + .../test/new/case_insensitive_refs.html | 1 + .../test/new/case_insensitive_refs.text | 3 + .../marked/test/new/def_blocks.html | 28 + .../marked/test/new/def_blocks.text | 21 + .../marked/test/new/double_link.html | 5 + .../marked/test/new/double_link.text | 5 + .../marked/test/new/escaped_angles.html | 1 + .../marked/test/new/escaped_angles.text | 1 + .../marked/test/new/gfm_break.breaks.html | 1 + .../marked/test/new/gfm_break.breaks.text | 3 + .../marked/test/new/gfm_code.html | 5 + .../marked/test/new/gfm_code.text | 16 + .../marked/test/new/gfm_code_hr_list.html | 52 + .../marked/test/new/gfm_code_hr_list.text | 53 + .../marked/test/new/gfm_del.html | 1 + .../marked/test/new/gfm_del.text | 1 + .../marked/test/new/gfm_em.html | 1 + .../marked/test/new/gfm_em.text | 1 + .../marked/test/new/gfm_links.html | 2 + .../marked/test/new/gfm_links.text | 1 + .../marked/test/new/gfm_tables.html | 37 + .../marked/test/new/gfm_tables.text | 21 + .../marked/test/new/hr_list_break.html | 10 + .../marked/test/new/hr_list_break.text | 6 + .../marked/test/new/lazy_blockquotes.html | 4 + .../marked/test/new/lazy_blockquotes.text | 2 + .../marked/test/new/list_item_text.html | 1 + .../marked/test/new/list_item_text.text | 5 + .../marked/test/new/loose_lists.html | 62 + .../marked/test/new/loose_lists.text | 59 + .../marked/test/new/main.html | 4 + .../marked/test/new/main.text | 55 + .../marked/test/new/nested_code.html | 1 + .../marked/test/new/nested_code.text | 1 + .../marked/test/new/nested_em.html | 3 + .../marked/test/new/nested_em.text | 3 + .../marked/test/new/nested_square_link.html | 1 + .../marked/test/new/nested_square_link.text | 1 + .../marked/test/new/not_a_link.html | 1 + .../marked/test/new/not_a_link.text | 1 + .../marked/test/new/ref_paren.html | 1 + .../marked/test/new/ref_paren.text | 3 + .../marked/test/new/same_bullet.html | 5 + .../marked/test/new/same_bullet.text | 3 + .../marked/test/new/text.smartypants.html | 6 + .../marked/test/new/text.smartypants.text | 6 + .../test/new/toplevel_paragraphs.gfm.html | 34 + .../test/new/toplevel_paragraphs.gfm.text | 37 + .../marked/test/new/tricky_list.html | 23 + .../marked/test/new/tricky_list.text | 15 + .../original/amps_and_angles_encoding.html | 17 + .../original/amps_and_angles_encoding.text | 21 + .../marked/test/original/auto_links.html | 18 + .../marked/test/original/auto_links.text | 13 + .../test/original/backslash_escapes.html | 118 + .../test/original/backslash_escapes.text | 120 + .../blockquotes_with_code_blocks.html | 15 + .../blockquotes_with_code_blocks.text | 11 + .../marked/test/original/code_blocks.html | 18 + .../marked/test/original/code_blocks.text | 14 + .../marked/test/original/code_spans.html | 6 + .../marked/test/original/code_spans.text | 6 + ...apped_paragraphs_with_list_like_lines.html | 8 + ...apped_paragraphs_with_list_like_lines.text | 8 + .../test/original/horizontal_rules.html | 71 + .../test/original/horizontal_rules.text | 67 + .../test/original/inline_html_advanced.html | 15 + .../test/original/inline_html_advanced.text | 15 + .../test/original/inline_html_comments.html | 13 + .../test/original/inline_html_comments.text | 13 + .../test/original/inline_html_simple.html | 72 + .../test/original/inline_html_simple.text | 69 + .../test/original/links_inline_style.html | 15 + .../test/original/links_inline_style.text | 15 + .../test/original/links_reference_style.html | 52 + .../test/original/links_reference_style.text | 71 + .../original/links_shortcut_references.html | 9 + .../original/links_shortcut_references.text | 20 + .../original/literal_quotes_in_titles.html | 3 + .../original/literal_quotes_in_titles.text | 7 + .../markdown_documentation_basics.html | 314 + .../markdown_documentation_basics.text | 306 + .../markdown_documentation_syntax.html | 942 + .../markdown_documentation_syntax.text | 888 + .../test/original/nested_blockquotes.html | 9 + .../test/original/nested_blockquotes.text | 5 + .../original/ordered_and_unordered_lists.html | 148 + .../original/ordered_and_unordered_lists.text | 131 + .../test/original/strong_and_em_together.html | 7 + .../test/original/strong_and_em_together.text | 7 + .../marked/test/original/tabs.html | 25 + .../marked/test/original/tabs.text | 21 + .../marked/test/original/tidyness.html | 8 + .../marked/test/original/tidyness.text | 5 + .../test/tests/amps_and_angles_encoding.html | 17 + .../test/tests/amps_and_angles_encoding.text | 21 + .../marked/test/tests/auto_links.html | 18 + .../marked/test/tests/auto_links.text | 13 + .../marked/test/tests/autolink_lines.html | 3 + .../marked/test/tests/autolink_lines.text | 2 + .../marked/test/tests/backslash_escapes.html | 118 + .../marked/test/tests/backslash_escapes.text | 120 + .../test/tests/blockquote_list_item.html | 3 + .../test/tests/blockquote_list_item.text | 4 + .../tests/blockquotes_with_code_blocks.html | 15 + .../tests/blockquotes_with_code_blocks.text | 11 + .../test/tests/case_insensitive_refs.html | 1 + .../test/tests/case_insensitive_refs.text | 3 + .../marked/test/tests/code_blocks.html | 18 + .../marked/test/tests/code_blocks.text | 14 + .../marked/test/tests/code_spans.html | 6 + .../marked/test/tests/code_spans.text | 6 + .../marked/test/tests/def_blocks.html | 28 + .../marked/test/tests/def_blocks.text | 21 + .../marked/test/tests/double_link.html | 5 + .../marked/test/tests/double_link.text | 5 + .../marked/test/tests/escaped_angles.html | 1 + .../marked/test/tests/escaped_angles.text | 1 + .../marked/test/tests/gfm_break.breaks.html | 1 + .../marked/test/tests/gfm_break.breaks.text | 3 + .../marked/test/tests/gfm_code.html | 5 + .../marked/test/tests/gfm_code.text | 16 + .../marked/test/tests/gfm_code_hr_list.html | 52 + .../marked/test/tests/gfm_code_hr_list.text | 53 + .../marked/test/tests/gfm_del.html | 1 + .../marked/test/tests/gfm_del.text | 1 + .../marked/test/tests/gfm_em.html | 1 + .../marked/test/tests/gfm_em.text | 1 + .../marked/test/tests/gfm_links.html | 2 + .../marked/test/tests/gfm_links.text | 1 + .../marked/test/tests/gfm_tables.html | 37 + .../marked/test/tests/gfm_tables.text | 21 + ...paragraphs_with_list_like_lines.nogfm.html | 8 + ...paragraphs_with_list_like_lines.nogfm.text | 8 + .../marked/test/tests/horizontal_rules.html | 71 + .../marked/test/tests/horizontal_rules.text | 67 + .../marked/test/tests/hr_list_break.html | 10 + .../marked/test/tests/hr_list_break.text | 6 + .../test/tests/inline_html_advanced.html | 15 + .../test/tests/inline_html_advanced.text | 15 + .../test/tests/inline_html_comments.html | 13 + .../test/tests/inline_html_comments.text | 13 + .../marked/test/tests/inline_html_simple.html | 72 + .../marked/test/tests/inline_html_simple.text | 69 + .../marked/test/tests/lazy_blockquotes.html | 4 + .../marked/test/tests/lazy_blockquotes.text | 2 + .../marked/test/tests/links_inline_style.html | 15 + .../marked/test/tests/links_inline_style.text | 15 + .../test/tests/links_reference_style.html | 52 + .../test/tests/links_reference_style.text | 71 + .../test/tests/links_shortcut_references.html | 9 + .../test/tests/links_shortcut_references.text | 20 + .../marked/test/tests/list_item_text.html | 1 + .../marked/test/tests/list_item_text.text | 5 + .../test/tests/literal_quotes_in_titles.html | 3 + .../test/tests/literal_quotes_in_titles.text | 7 + .../marked/test/tests/loose_lists.html | 62 + .../marked/test/tests/loose_lists.text | 59 + .../marked/test/tests/main.html | 4 + .../marked/test/tests/main.text | 55 + .../tests/markdown_documentation_basics.html | 314 + .../tests/markdown_documentation_basics.text | 306 + .../tests/markdown_documentation_syntax.html | 942 + .../tests/markdown_documentation_syntax.text | 888 + .../marked/test/tests/nested_blockquotes.html | 9 + .../marked/test/tests/nested_blockquotes.text | 5 + .../marked/test/tests/nested_code.html | 1 + .../marked/test/tests/nested_code.text | 1 + .../marked/test/tests/nested_em.html | 3 + .../marked/test/tests/nested_em.text | 3 + .../marked/test/tests/nested_square_link.html | 1 + .../marked/test/tests/nested_square_link.text | 1 + .../marked/test/tests/not_a_link.html | 1 + .../marked/test/tests/not_a_link.text | 1 + .../tests/ordered_and_unordered_lists.html | 148 + .../tests/ordered_and_unordered_lists.text | 131 + .../marked/test/tests/ref_paren.html | 1 + .../marked/test/tests/ref_paren.text | 3 + .../marked/test/tests/same_bullet.html | 5 + .../marked/test/tests/same_bullet.text | 3 + .../test/tests/strong_and_em_together.html | 7 + .../test/tests/strong_and_em_together.text | 7 + .../marked/test/tests/tabs.html | 25 + .../marked/test/tests/tabs.text | 21 + .../marked/test/tests/text.smartypants.html | 6 + .../marked/test/tests/text.smartypants.text | 6 + .../marked/test/tests/tidyness.html | 8 + .../marked/test/tests/tidyness.text | 5 + .../test/tests/toplevel_paragraphs.gfm.html | 34 + .../test/tests/toplevel_paragraphs.gfm.text | 37 + .../marked/test/tests/tricky_list.html | 23 + .../marked/test/tests/tricky_list.text | 15 + fks-chart/data/front-end.json | 1271 +- 336 files changed, 64096 insertions(+), 497 deletions(-) create mode 100644 fks-chart/bower_components/angular-marked/.bower.json create mode 100755 fks-chart/bower_components/angular-marked/README.md create mode 100644 fks-chart/bower_components/angular-marked/angular-marked.js create mode 100755 fks-chart/bower_components/angular-marked/angular-marked.min.js create mode 100755 fks-chart/bower_components/angular-marked/bower.json create mode 100755 fks-chart/bower_components/angular-marked/example/index.html create mode 100755 fks-chart/bower_components/angular-marked/gruntfile.js create mode 100755 fks-chart/bower_components/angular-marked/karma.conf.js create mode 100755 fks-chart/bower_components/angular-marked/package.json create mode 100755 fks-chart/bower_components/angular-marked/todo.md create mode 100644 fks-chart/bower_components/angular/.bower.json create mode 100644 fks-chart/bower_components/angular/README.md create mode 100644 fks-chart/bower_components/angular/angular-csp.css create mode 100644 fks-chart/bower_components/angular/angular.js create mode 100644 fks-chart/bower_components/angular/angular.min.js create mode 100644 fks-chart/bower_components/angular/angular.min.js.gzip create mode 100644 fks-chart/bower_components/angular/angular.min.js.map create mode 100644 fks-chart/bower_components/angular/bower.json create mode 100644 fks-chart/bower_components/angular/package.json create mode 100644 fks-chart/bower_components/d3/.bower.json create mode 100644 fks-chart/bower_components/d3/.spmignore create mode 100644 fks-chart/bower_components/d3/CONTRIBUTING.md create mode 100644 fks-chart/bower_components/d3/LICENSE create mode 100644 fks-chart/bower_components/d3/README.md create mode 100644 fks-chart/bower_components/d3/bower.json create mode 100644 fks-chart/bower_components/d3/composer.json create mode 100644 fks-chart/bower_components/d3/d3.js create mode 100644 fks-chart/bower_components/d3/d3.min.js create mode 100644 fks-chart/bower_components/jquery/.bower.json create mode 100644 fks-chart/bower_components/jquery/MIT-LICENSE.txt create mode 100644 fks-chart/bower_components/jquery/bower.json create mode 100644 fks-chart/bower_components/jquery/dist/jquery.js create mode 100644 fks-chart/bower_components/jquery/dist/jquery.min.js create mode 100644 fks-chart/bower_components/jquery/dist/jquery.min.map create mode 100644 fks-chart/bower_components/jquery/src/ajax.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/jsonp.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/load.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/parseJSON.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/parseXML.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/script.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/var/nonce.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/var/rquery.js create mode 100644 fks-chart/bower_components/jquery/src/ajax/xhr.js create mode 100644 fks-chart/bower_components/jquery/src/attributes.js create mode 100644 fks-chart/bower_components/jquery/src/attributes/attr.js create mode 100644 fks-chart/bower_components/jquery/src/attributes/classes.js create mode 100644 fks-chart/bower_components/jquery/src/attributes/prop.js create mode 100644 fks-chart/bower_components/jquery/src/attributes/support.js create mode 100644 fks-chart/bower_components/jquery/src/attributes/val.js create mode 100644 fks-chart/bower_components/jquery/src/callbacks.js create mode 100644 fks-chart/bower_components/jquery/src/core.js create mode 100644 fks-chart/bower_components/jquery/src/core/access.js create mode 100644 fks-chart/bower_components/jquery/src/core/init.js create mode 100644 fks-chart/bower_components/jquery/src/core/parseHTML.js create mode 100644 fks-chart/bower_components/jquery/src/core/ready.js create mode 100644 fks-chart/bower_components/jquery/src/core/var/rsingleTag.js create mode 100644 fks-chart/bower_components/jquery/src/css.js create mode 100644 fks-chart/bower_components/jquery/src/css/addGetHookIf.js create mode 100644 fks-chart/bower_components/jquery/src/css/curCSS.js create mode 100644 fks-chart/bower_components/jquery/src/css/defaultDisplay.js create mode 100644 fks-chart/bower_components/jquery/src/css/hiddenVisibleSelectors.js create mode 100644 fks-chart/bower_components/jquery/src/css/support.js create mode 100644 fks-chart/bower_components/jquery/src/css/swap.js create mode 100644 fks-chart/bower_components/jquery/src/css/var/cssExpand.js create mode 100644 fks-chart/bower_components/jquery/src/css/var/getStyles.js create mode 100644 fks-chart/bower_components/jquery/src/css/var/isHidden.js create mode 100644 fks-chart/bower_components/jquery/src/css/var/rmargin.js create mode 100644 fks-chart/bower_components/jquery/src/css/var/rnumnonpx.js create mode 100644 fks-chart/bower_components/jquery/src/data.js create mode 100644 fks-chart/bower_components/jquery/src/data/Data.js create mode 100644 fks-chart/bower_components/jquery/src/data/accepts.js create mode 100644 fks-chart/bower_components/jquery/src/data/var/data_priv.js create mode 100644 fks-chart/bower_components/jquery/src/data/var/data_user.js create mode 100644 fks-chart/bower_components/jquery/src/deferred.js create mode 100644 fks-chart/bower_components/jquery/src/deprecated.js create mode 100644 fks-chart/bower_components/jquery/src/dimensions.js create mode 100644 fks-chart/bower_components/jquery/src/effects.js create mode 100644 fks-chart/bower_components/jquery/src/effects/Tween.js create mode 100644 fks-chart/bower_components/jquery/src/effects/animatedSelector.js create mode 100644 fks-chart/bower_components/jquery/src/event.js create mode 100644 fks-chart/bower_components/jquery/src/event/ajax.js create mode 100644 fks-chart/bower_components/jquery/src/event/alias.js create mode 100644 fks-chart/bower_components/jquery/src/event/support.js create mode 100644 fks-chart/bower_components/jquery/src/exports/amd.js create mode 100644 fks-chart/bower_components/jquery/src/exports/global.js create mode 100644 fks-chart/bower_components/jquery/src/intro.js create mode 100644 fks-chart/bower_components/jquery/src/jquery.js create mode 100644 fks-chart/bower_components/jquery/src/manipulation.js create mode 100644 fks-chart/bower_components/jquery/src/manipulation/_evalUrl.js create mode 100644 fks-chart/bower_components/jquery/src/manipulation/support.js create mode 100644 fks-chart/bower_components/jquery/src/manipulation/var/rcheckableType.js create mode 100644 fks-chart/bower_components/jquery/src/offset.js create mode 100644 fks-chart/bower_components/jquery/src/outro.js create mode 100644 fks-chart/bower_components/jquery/src/queue.js create mode 100644 fks-chart/bower_components/jquery/src/queue/delay.js create mode 100644 fks-chart/bower_components/jquery/src/selector-native.js create mode 100644 fks-chart/bower_components/jquery/src/selector-sizzle.js create mode 100644 fks-chart/bower_components/jquery/src/selector.js create mode 100644 fks-chart/bower_components/jquery/src/serialize.js create mode 100644 fks-chart/bower_components/jquery/src/sizzle/dist/sizzle.js create mode 100644 fks-chart/bower_components/jquery/src/sizzle/dist/sizzle.min.js create mode 100644 fks-chart/bower_components/jquery/src/sizzle/dist/sizzle.min.map create mode 100644 fks-chart/bower_components/jquery/src/traversing.js create mode 100644 fks-chart/bower_components/jquery/src/traversing/findFilter.js create mode 100644 fks-chart/bower_components/jquery/src/traversing/var/rneedsContext.js create mode 100644 fks-chart/bower_components/jquery/src/var/arr.js create mode 100644 fks-chart/bower_components/jquery/src/var/class2type.js create mode 100644 fks-chart/bower_components/jquery/src/var/concat.js create mode 100644 fks-chart/bower_components/jquery/src/var/hasOwn.js create mode 100644 fks-chart/bower_components/jquery/src/var/indexOf.js create mode 100644 fks-chart/bower_components/jquery/src/var/pnum.js create mode 100644 fks-chart/bower_components/jquery/src/var/push.js create mode 100644 fks-chart/bower_components/jquery/src/var/rnotwhite.js create mode 100644 fks-chart/bower_components/jquery/src/var/slice.js create mode 100644 fks-chart/bower_components/jquery/src/var/strundefined.js create mode 100644 fks-chart/bower_components/jquery/src/var/support.js create mode 100644 fks-chart/bower_components/jquery/src/var/toString.js create mode 100644 fks-chart/bower_components/jquery/src/wrap.js create mode 100644 fks-chart/bower_components/marked/.bower.json create mode 100644 fks-chart/bower_components/marked/.gitignore create mode 100644 fks-chart/bower_components/marked/.npmignore create mode 100644 fks-chart/bower_components/marked/.travis.yml create mode 100644 fks-chart/bower_components/marked/LICENSE create mode 100644 fks-chart/bower_components/marked/Makefile create mode 100644 fks-chart/bower_components/marked/README.md create mode 100755 fks-chart/bower_components/marked/bin/marked create mode 100644 fks-chart/bower_components/marked/component.json create mode 100644 fks-chart/bower_components/marked/doc/broken.md create mode 100644 fks-chart/bower_components/marked/doc/todo.md create mode 100644 fks-chart/bower_components/marked/index.js create mode 100644 fks-chart/bower_components/marked/lib/marked.js create mode 100644 fks-chart/bower_components/marked/man/marked.1 create mode 100644 fks-chart/bower_components/marked/package.json create mode 100644 fks-chart/bower_components/marked/test/README create mode 100644 fks-chart/bower_components/marked/test/browser/index.html create mode 100644 fks-chart/bower_components/marked/test/browser/index.js create mode 100644 fks-chart/bower_components/marked/test/browser/test.js create mode 100644 fks-chart/bower_components/marked/test/index.js create mode 100644 fks-chart/bower_components/marked/test/new/autolink_lines.html create mode 100644 fks-chart/bower_components/marked/test/new/autolink_lines.text create mode 100644 fks-chart/bower_components/marked/test/new/blockquote_list_item.html create mode 100644 fks-chart/bower_components/marked/test/new/blockquote_list_item.text create mode 100644 fks-chart/bower_components/marked/test/new/case_insensitive_refs.html create mode 100644 fks-chart/bower_components/marked/test/new/case_insensitive_refs.text create mode 100644 fks-chart/bower_components/marked/test/new/def_blocks.html create mode 100644 fks-chart/bower_components/marked/test/new/def_blocks.text create mode 100644 fks-chart/bower_components/marked/test/new/double_link.html create mode 100644 fks-chart/bower_components/marked/test/new/double_link.text create mode 100644 fks-chart/bower_components/marked/test/new/escaped_angles.html create mode 100644 fks-chart/bower_components/marked/test/new/escaped_angles.text create mode 100644 fks-chart/bower_components/marked/test/new/gfm_break.breaks.html create mode 100644 fks-chart/bower_components/marked/test/new/gfm_break.breaks.text create mode 100644 fks-chart/bower_components/marked/test/new/gfm_code.html create mode 100644 fks-chart/bower_components/marked/test/new/gfm_code.text create mode 100644 fks-chart/bower_components/marked/test/new/gfm_code_hr_list.html create mode 100644 fks-chart/bower_components/marked/test/new/gfm_code_hr_list.text create mode 100644 fks-chart/bower_components/marked/test/new/gfm_del.html create mode 100644 fks-chart/bower_components/marked/test/new/gfm_del.text create mode 100644 fks-chart/bower_components/marked/test/new/gfm_em.html create mode 100644 fks-chart/bower_components/marked/test/new/gfm_em.text create mode 100644 fks-chart/bower_components/marked/test/new/gfm_links.html create mode 100644 fks-chart/bower_components/marked/test/new/gfm_links.text create mode 100644 fks-chart/bower_components/marked/test/new/gfm_tables.html create mode 100644 fks-chart/bower_components/marked/test/new/gfm_tables.text create mode 100644 fks-chart/bower_components/marked/test/new/hr_list_break.html create mode 100644 fks-chart/bower_components/marked/test/new/hr_list_break.text create mode 100644 fks-chart/bower_components/marked/test/new/lazy_blockquotes.html create mode 100644 fks-chart/bower_components/marked/test/new/lazy_blockquotes.text create mode 100644 fks-chart/bower_components/marked/test/new/list_item_text.html create mode 100644 fks-chart/bower_components/marked/test/new/list_item_text.text create mode 100644 fks-chart/bower_components/marked/test/new/loose_lists.html create mode 100644 fks-chart/bower_components/marked/test/new/loose_lists.text create mode 100644 fks-chart/bower_components/marked/test/new/main.html create mode 100644 fks-chart/bower_components/marked/test/new/main.text create mode 100644 fks-chart/bower_components/marked/test/new/nested_code.html create mode 100644 fks-chart/bower_components/marked/test/new/nested_code.text create mode 100644 fks-chart/bower_components/marked/test/new/nested_em.html create mode 100644 fks-chart/bower_components/marked/test/new/nested_em.text create mode 100644 fks-chart/bower_components/marked/test/new/nested_square_link.html create mode 100644 fks-chart/bower_components/marked/test/new/nested_square_link.text create mode 100644 fks-chart/bower_components/marked/test/new/not_a_link.html create mode 100644 fks-chart/bower_components/marked/test/new/not_a_link.text create mode 100644 fks-chart/bower_components/marked/test/new/ref_paren.html create mode 100644 fks-chart/bower_components/marked/test/new/ref_paren.text create mode 100644 fks-chart/bower_components/marked/test/new/same_bullet.html create mode 100644 fks-chart/bower_components/marked/test/new/same_bullet.text create mode 100644 fks-chart/bower_components/marked/test/new/text.smartypants.html create mode 100644 fks-chart/bower_components/marked/test/new/text.smartypants.text create mode 100644 fks-chart/bower_components/marked/test/new/toplevel_paragraphs.gfm.html create mode 100644 fks-chart/bower_components/marked/test/new/toplevel_paragraphs.gfm.text create mode 100644 fks-chart/bower_components/marked/test/new/tricky_list.html create mode 100644 fks-chart/bower_components/marked/test/new/tricky_list.text create mode 100644 fks-chart/bower_components/marked/test/original/amps_and_angles_encoding.html create mode 100644 fks-chart/bower_components/marked/test/original/amps_and_angles_encoding.text create mode 100644 fks-chart/bower_components/marked/test/original/auto_links.html create mode 100644 fks-chart/bower_components/marked/test/original/auto_links.text create mode 100644 fks-chart/bower_components/marked/test/original/backslash_escapes.html create mode 100644 fks-chart/bower_components/marked/test/original/backslash_escapes.text create mode 100644 fks-chart/bower_components/marked/test/original/blockquotes_with_code_blocks.html create mode 100644 fks-chart/bower_components/marked/test/original/blockquotes_with_code_blocks.text create mode 100644 fks-chart/bower_components/marked/test/original/code_blocks.html create mode 100644 fks-chart/bower_components/marked/test/original/code_blocks.text create mode 100644 fks-chart/bower_components/marked/test/original/code_spans.html create mode 100644 fks-chart/bower_components/marked/test/original/code_spans.text create mode 100644 fks-chart/bower_components/marked/test/original/hard_wrapped_paragraphs_with_list_like_lines.html create mode 100644 fks-chart/bower_components/marked/test/original/hard_wrapped_paragraphs_with_list_like_lines.text create mode 100644 fks-chart/bower_components/marked/test/original/horizontal_rules.html create mode 100644 fks-chart/bower_components/marked/test/original/horizontal_rules.text create mode 100644 fks-chart/bower_components/marked/test/original/inline_html_advanced.html create mode 100644 fks-chart/bower_components/marked/test/original/inline_html_advanced.text create mode 100644 fks-chart/bower_components/marked/test/original/inline_html_comments.html create mode 100644 fks-chart/bower_components/marked/test/original/inline_html_comments.text create mode 100644 fks-chart/bower_components/marked/test/original/inline_html_simple.html create mode 100644 fks-chart/bower_components/marked/test/original/inline_html_simple.text create mode 100644 fks-chart/bower_components/marked/test/original/links_inline_style.html create mode 100644 fks-chart/bower_components/marked/test/original/links_inline_style.text create mode 100644 fks-chart/bower_components/marked/test/original/links_reference_style.html create mode 100644 fks-chart/bower_components/marked/test/original/links_reference_style.text create mode 100644 fks-chart/bower_components/marked/test/original/links_shortcut_references.html create mode 100644 fks-chart/bower_components/marked/test/original/links_shortcut_references.text create mode 100644 fks-chart/bower_components/marked/test/original/literal_quotes_in_titles.html create mode 100644 fks-chart/bower_components/marked/test/original/literal_quotes_in_titles.text create mode 100644 fks-chart/bower_components/marked/test/original/markdown_documentation_basics.html create mode 100644 fks-chart/bower_components/marked/test/original/markdown_documentation_basics.text create mode 100644 fks-chart/bower_components/marked/test/original/markdown_documentation_syntax.html create mode 100644 fks-chart/bower_components/marked/test/original/markdown_documentation_syntax.text create mode 100644 fks-chart/bower_components/marked/test/original/nested_blockquotes.html create mode 100644 fks-chart/bower_components/marked/test/original/nested_blockquotes.text create mode 100644 fks-chart/bower_components/marked/test/original/ordered_and_unordered_lists.html create mode 100644 fks-chart/bower_components/marked/test/original/ordered_and_unordered_lists.text create mode 100644 fks-chart/bower_components/marked/test/original/strong_and_em_together.html create mode 100644 fks-chart/bower_components/marked/test/original/strong_and_em_together.text create mode 100644 fks-chart/bower_components/marked/test/original/tabs.html create mode 100644 fks-chart/bower_components/marked/test/original/tabs.text create mode 100644 fks-chart/bower_components/marked/test/original/tidyness.html create mode 100644 fks-chart/bower_components/marked/test/original/tidyness.text create mode 100644 fks-chart/bower_components/marked/test/tests/amps_and_angles_encoding.html create mode 100644 fks-chart/bower_components/marked/test/tests/amps_and_angles_encoding.text create mode 100644 fks-chart/bower_components/marked/test/tests/auto_links.html create mode 100644 fks-chart/bower_components/marked/test/tests/auto_links.text create mode 100644 fks-chart/bower_components/marked/test/tests/autolink_lines.html create mode 100644 fks-chart/bower_components/marked/test/tests/autolink_lines.text create mode 100644 fks-chart/bower_components/marked/test/tests/backslash_escapes.html create mode 100644 fks-chart/bower_components/marked/test/tests/backslash_escapes.text create mode 100644 fks-chart/bower_components/marked/test/tests/blockquote_list_item.html create mode 100644 fks-chart/bower_components/marked/test/tests/blockquote_list_item.text create mode 100644 fks-chart/bower_components/marked/test/tests/blockquotes_with_code_blocks.html create mode 100644 fks-chart/bower_components/marked/test/tests/blockquotes_with_code_blocks.text create mode 100644 fks-chart/bower_components/marked/test/tests/case_insensitive_refs.html create mode 100644 fks-chart/bower_components/marked/test/tests/case_insensitive_refs.text create mode 100644 fks-chart/bower_components/marked/test/tests/code_blocks.html create mode 100644 fks-chart/bower_components/marked/test/tests/code_blocks.text create mode 100644 fks-chart/bower_components/marked/test/tests/code_spans.html create mode 100644 fks-chart/bower_components/marked/test/tests/code_spans.text create mode 100644 fks-chart/bower_components/marked/test/tests/def_blocks.html create mode 100644 fks-chart/bower_components/marked/test/tests/def_blocks.text create mode 100644 fks-chart/bower_components/marked/test/tests/double_link.html create mode 100644 fks-chart/bower_components/marked/test/tests/double_link.text create mode 100644 fks-chart/bower_components/marked/test/tests/escaped_angles.html create mode 100644 fks-chart/bower_components/marked/test/tests/escaped_angles.text create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_break.breaks.html create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_break.breaks.text create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_code.html create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_code.text create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_code_hr_list.html create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_code_hr_list.text create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_del.html create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_del.text create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_em.html create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_em.text create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_links.html create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_links.text create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_tables.html create mode 100644 fks-chart/bower_components/marked/test/tests/gfm_tables.text create mode 100644 fks-chart/bower_components/marked/test/tests/hard_wrapped_paragraphs_with_list_like_lines.nogfm.html create mode 100644 fks-chart/bower_components/marked/test/tests/hard_wrapped_paragraphs_with_list_like_lines.nogfm.text create mode 100644 fks-chart/bower_components/marked/test/tests/horizontal_rules.html create mode 100644 fks-chart/bower_components/marked/test/tests/horizontal_rules.text create mode 100644 fks-chart/bower_components/marked/test/tests/hr_list_break.html create mode 100644 fks-chart/bower_components/marked/test/tests/hr_list_break.text create mode 100644 fks-chart/bower_components/marked/test/tests/inline_html_advanced.html create mode 100644 fks-chart/bower_components/marked/test/tests/inline_html_advanced.text create mode 100644 fks-chart/bower_components/marked/test/tests/inline_html_comments.html create mode 100644 fks-chart/bower_components/marked/test/tests/inline_html_comments.text create mode 100644 fks-chart/bower_components/marked/test/tests/inline_html_simple.html create mode 100644 fks-chart/bower_components/marked/test/tests/inline_html_simple.text create mode 100644 fks-chart/bower_components/marked/test/tests/lazy_blockquotes.html create mode 100644 fks-chart/bower_components/marked/test/tests/lazy_blockquotes.text create mode 100644 fks-chart/bower_components/marked/test/tests/links_inline_style.html create mode 100644 fks-chart/bower_components/marked/test/tests/links_inline_style.text create mode 100644 fks-chart/bower_components/marked/test/tests/links_reference_style.html create mode 100644 fks-chart/bower_components/marked/test/tests/links_reference_style.text create mode 100644 fks-chart/bower_components/marked/test/tests/links_shortcut_references.html create mode 100644 fks-chart/bower_components/marked/test/tests/links_shortcut_references.text create mode 100644 fks-chart/bower_components/marked/test/tests/list_item_text.html create mode 100644 fks-chart/bower_components/marked/test/tests/list_item_text.text create mode 100644 fks-chart/bower_components/marked/test/tests/literal_quotes_in_titles.html create mode 100644 fks-chart/bower_components/marked/test/tests/literal_quotes_in_titles.text create mode 100644 fks-chart/bower_components/marked/test/tests/loose_lists.html create mode 100644 fks-chart/bower_components/marked/test/tests/loose_lists.text create mode 100644 fks-chart/bower_components/marked/test/tests/main.html create mode 100644 fks-chart/bower_components/marked/test/tests/main.text create mode 100644 fks-chart/bower_components/marked/test/tests/markdown_documentation_basics.html create mode 100644 fks-chart/bower_components/marked/test/tests/markdown_documentation_basics.text create mode 100644 fks-chart/bower_components/marked/test/tests/markdown_documentation_syntax.html create mode 100644 fks-chart/bower_components/marked/test/tests/markdown_documentation_syntax.text create mode 100644 fks-chart/bower_components/marked/test/tests/nested_blockquotes.html create mode 100644 fks-chart/bower_components/marked/test/tests/nested_blockquotes.text create mode 100644 fks-chart/bower_components/marked/test/tests/nested_code.html create mode 100644 fks-chart/bower_components/marked/test/tests/nested_code.text create mode 100644 fks-chart/bower_components/marked/test/tests/nested_em.html create mode 100644 fks-chart/bower_components/marked/test/tests/nested_em.text create mode 100644 fks-chart/bower_components/marked/test/tests/nested_square_link.html create mode 100644 fks-chart/bower_components/marked/test/tests/nested_square_link.text create mode 100644 fks-chart/bower_components/marked/test/tests/not_a_link.html create mode 100644 fks-chart/bower_components/marked/test/tests/not_a_link.text create mode 100644 fks-chart/bower_components/marked/test/tests/ordered_and_unordered_lists.html create mode 100644 fks-chart/bower_components/marked/test/tests/ordered_and_unordered_lists.text create mode 100644 fks-chart/bower_components/marked/test/tests/ref_paren.html create mode 100644 fks-chart/bower_components/marked/test/tests/ref_paren.text create mode 100644 fks-chart/bower_components/marked/test/tests/same_bullet.html create mode 100644 fks-chart/bower_components/marked/test/tests/same_bullet.text create mode 100644 fks-chart/bower_components/marked/test/tests/strong_and_em_together.html create mode 100644 fks-chart/bower_components/marked/test/tests/strong_and_em_together.text create mode 100644 fks-chart/bower_components/marked/test/tests/tabs.html create mode 100644 fks-chart/bower_components/marked/test/tests/tabs.text create mode 100644 fks-chart/bower_components/marked/test/tests/text.smartypants.html create mode 100644 fks-chart/bower_components/marked/test/tests/text.smartypants.text create mode 100644 fks-chart/bower_components/marked/test/tests/tidyness.html create mode 100644 fks-chart/bower_components/marked/test/tests/tidyness.text create mode 100644 fks-chart/bower_components/marked/test/tests/toplevel_paragraphs.gfm.html create mode 100644 fks-chart/bower_components/marked/test/tests/toplevel_paragraphs.gfm.text create mode 100644 fks-chart/bower_components/marked/test/tests/tricky_list.html create mode 100644 fks-chart/bower_components/marked/test/tests/tricky_list.text diff --git a/bin/generate.js b/bin/generate.js index 31c5ceb..2a78fa2 100644 --- a/bin/generate.js +++ b/bin/generate.js @@ -82,4 +82,4 @@ var buildTree = function (list) { }; var tree = buildTree(formated); -fs.writeFileSync(path.join(__dirname, '../chart/f2e.json'), JSON.stringify(tree, null, ' ')); +fs.writeFileSync(path.join(__dirname, '../fks-chart/data/front-end.json'), JSON.stringify(tree, null, ' ')); diff --git a/fks-chart/bower_components/angular-marked/.bower.json b/fks-chart/bower_components/angular-marked/.bower.json new file mode 100644 index 0000000..daf999d --- /dev/null +++ b/fks-chart/bower_components/angular-marked/.bower.json @@ -0,0 +1,41 @@ +{ + "name": "angular-marked", + "version": "0.0.12", + "authors": [ + "J. Harshbarger" + ], + "description": "AngularJS Markdown using marked.", + "main": "angular-marked.js", + "keywords": [ + "angularjs", + "markdown", + "marked", + "directive", + "filter" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "dependencies": { + "angular": ">= 1.2.5", + "marked": "~0.3.1" + }, + "devDependencies": { + "angular-mocks": ">= 1.2.5" + }, + "homepage": "https://github.com/Hypercubed/angular-marked", + "_release": "0.0.12", + "_resolution": { + "type": "version", + "tag": "v0.0.12", + "commit": "acb0738d108ee5cd35f3812492d7590495cf9ecd" + }, + "_source": "git://github.com/Hypercubed/angular-marked.git", + "_target": "~0.0.12", + "_originalSource": "angular-marked" +} \ No newline at end of file diff --git a/fks-chart/bower_components/angular-marked/README.md b/fks-chart/bower_components/angular-marked/README.md new file mode 100755 index 0000000..f4cfbc5 --- /dev/null +++ b/fks-chart/bower_components/angular-marked/README.md @@ -0,0 +1,86 @@ +# angular-marked +AngularJS Markdown using [marked](https://github.com/chjj/marked). + +## Usage +1. `bower install angular-marked` or `bower install Hypercubed/angular-marked` +2. Include the `marked.js` script into your app. By default should be at `bower_components/marked/lib/marked.js`. +3. Include the `angular-marked.js` into your app. By default should be at `bower_components/angular-marked/angular-marked.js`. +4. Add `hc.marked` as a module dependency to your app. + +### Set default options (optional) + +```js + + app.config(['markedProvider', function(markedProvider) { + markedProvider.setOptions({gfm: true}); + }]); +``` + +Example using [highlight.js Javascript syntax highlighter](http://highlightjs.org/) (must include highlight.js script). + +```js + markedProvider.setOptions({ + gfm: true, + tables: true, + highlight: function (code) { + return hljs.highlightAuto(code).value; + } + }); +``` + +### As a directive + +```html + + + #Markdown directive + *It works!* + +``` + +Bind the markdown input to a scope variable: + +```html + +
+
+ +``` + +Include a markdown file: + +```html + +
+
+ +``` + +### As a service + +```js + + app.controller('myCtrl', ['marked', function(marked) { + $scope.html = marked('#TEST'); + }]); +``` + +## Testing + +Install npm and bower dependencies: + +``` + npm install + bower install + npm test +``` + +## Why? + +I wanted to use `marked` instead of `showdown` as used in `angular-markdown-directive` as well as expose the option to globally set defaults. Yes, it is probably best to avoid creating a bunch of angular wrapper modules... but I use this enough across multiple projects to make it worth while for me. Use it if you like. Pull requests are welcome. + +## Acknowledgments +Based on [angular-markdown-directive](https://github.com/btford/angular-markdown-directive) by [briantford](http://briantford.com/) which, in turn, is based on [this excellent tutorial](http://blog.angularjs.org/2012/05/custom-components-part-1.html) by [@johnlinquist](https://twitter.com/johnlindquist). + +## License +MIT diff --git a/fks-chart/bower_components/angular-marked/angular-marked.js b/fks-chart/bower_components/angular-marked/angular-marked.js new file mode 100644 index 0000000..f896610 --- /dev/null +++ b/fks-chart/bower_components/angular-marked/angular-marked.js @@ -0,0 +1,64 @@ +/* + * angular-marked + * (c) 2014 J. Harshbarger + * Licensed MIT + */ + +/* jshint undef: true, unused: true */ +/* global angular:true */ + +(function () { + 'use strict'; + + var app = angular.module('hc.marked', []); + + //app.constant('marked', window.marked); + + app.provider('marked', function () { + + var self = this; + + self.setOptions = function(opts) { // Store options for later + this.defaults = opts; + }; + + self.$get = ['$window',function ($window) { + var m = $window.marked; + + self.setOptions = m.setOptions; + m.setOptions(self.defaults); + + return m; + }]; + + }); + + // TODO: filter tests */ + //app.filter('marked', ['marked', function(marked) { + // return marked; + //}]); + + app.directive('marked', ['marked', function (marked) { + return { + restrict: 'AE', + replace: true, + scope: { + opts: '=', + marked: '=' + }, + link: function (scope, element, attrs) { + set(scope.marked || element.text() || ''); + + function set(val) { + element.html(marked(val || '', scope.opts || null)); + } + + if (attrs.marked) { + scope.$watch('marked', set); + } + + } + }; + }]); + +}()); \ No newline at end of file diff --git a/fks-chart/bower_components/angular-marked/angular-marked.min.js b/fks-chart/bower_components/angular-marked/angular-marked.min.js new file mode 100755 index 0000000..802febc --- /dev/null +++ b/fks-chart/bower_components/angular-marked/angular-marked.min.js @@ -0,0 +1,6 @@ +/* + * angular-marked 0.0.11 + * (c) 2014 J. Harshbarger + * Licensed MIT + */ +!function(){"use strict";var a=angular.module("hc.marked",[]);a.provider("marked",function(){var a=this;a.setOptions=function(a){this.defaults=a},a.$get=["$window",function(b){var c=b.marked;return a.setOptions=c.setOptions,c.setOptions(a.defaults),c}]}),a.directive("marked",["marked",function(a){return{restrict:"AE",replace:!0,scope:{opts:"=",marked:"="},link:function(b,c,d){function e(d){c.html(a(d||"",b.opts||null))}e(b.marked||c.text()||""),d.marked&&b.$watch("marked",e)}}}])}(); \ No newline at end of file diff --git a/fks-chart/bower_components/angular-marked/bower.json b/fks-chart/bower_components/angular-marked/bower.json new file mode 100755 index 0000000..3ac5bfb --- /dev/null +++ b/fks-chart/bower_components/angular-marked/bower.json @@ -0,0 +1,31 @@ +{ + "name": "angular-marked", + "version": "0.0.12", + "authors": [ + "J. Harshbarger" + ], + "description": "AngularJS Markdown using marked.", + "main": "angular-marked.js", + "keywords": [ + "angularjs", + "markdown", + "marked", + "directive", + "filter" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "dependencies": { + "angular": ">= 1.2.5", + "marked": "~0.3.1" + }, + "devDependencies": { + "angular-mocks": ">= 1.2.5" + } +} diff --git a/fks-chart/bower_components/angular-marked/example/index.html b/fks-chart/bower_components/angular-marked/example/index.html new file mode 100755 index 0000000..5e6559d --- /dev/null +++ b/fks-chart/bower_components/angular-marked/example/index.html @@ -0,0 +1,91 @@ + + + + + angular-marked example + + + + + + + +

angular-marked

+ +
+ + +### What? +Convert markdown to html at run time. + + +For example, this: +

+

+

+
+

+ +Becomes this: +
+
+ + +### Why? +I wanted to use `marked` instead of `showdown` as used in `angular-markdown-directive` as well as expose the option to globally set defaults. + +### How? + + +

A block of text:

+
    <marked>
+#Markdown directive   
+*It works!*
+    </marked>
+
+

Bind the markdown input to a scope variable:

+
    <div marked="my_markdown"> 
+    </div>
+    <!-- Uses $scope.my_markdown -->
+
+

Include a markdown file:

+
    <div marked ng-include="'README.md'"> 
+    </div>
+    <!-- Uses markdown content from README.md -->
+
+ + +Set default options + +```js +app.config(['markedProvider', function(markedProvider) { + markedProvider.setOptions({gfm: true}); +}]); + +``` + + + +
+ + + + \ No newline at end of file diff --git a/fks-chart/bower_components/angular-marked/gruntfile.js b/fks-chart/bower_components/angular-marked/gruntfile.js new file mode 100755 index 0000000..df34f0e --- /dev/null +++ b/fks-chart/bower_components/angular-marked/gruntfile.js @@ -0,0 +1,50 @@ +module.exports = function(grunt){ + 'use strict'; + + grunt.initConfig({ + pkg: grunt.file.readJSON('bower.json'), + jshint: { + options: { jshintrc: true }, + all: ['gruntfile.js', '<%= pkg.name %>.js'] + }, + bump: { + options: { + files: ['bower.json','package.json'], + commit: true, + commitMessage: 'release %VERSION%', + commitFiles: ['package.json','bower.json','<%= pkg.name %>.min.js'], // '-a' for all files + pushTo: 'origin', + } + }, + uglify: { + options: { + banner: '/*\n * <%= pkg.title || pkg.name %> <%= pkg.version %>\n' + + ' * (c) <%= grunt.template.today("yyyy") %> <%= pkg.authors.join(" ") %>\n' + + ' * Licensed <%= pkg.license %>\n */\n' + }, + src: { + files: { + '<%= pkg.name %>.min.js': '<%= pkg.name %>.js' + } + } + }, + karma: { + unit: { + configFile: 'karma.conf.js' + }, + once: { + configFile: 'karma.conf.js', + singleRun: true, + browsers: ['PhantomJS'] + } + } + }); + + require('load-grunt-tasks')(grunt); + + grunt.registerTask('default', ['build','test']); + grunt.registerTask('build', ['jshint', 'uglify']); + grunt.registerTask('test', ['karma:once']); + grunt.registerTask('publish', ['test','bump-only','uglify','bump-commit']); + +}; \ No newline at end of file diff --git a/fks-chart/bower_components/angular-marked/karma.conf.js b/fks-chart/bower_components/angular-marked/karma.conf.js new file mode 100755 index 0000000..e40a65f --- /dev/null +++ b/fks-chart/bower_components/angular-marked/karma.conf.js @@ -0,0 +1,55 @@ +// Karma configuration +// http://karma-runner.github.io/0.10/config/configuration-file.html + +module.exports = function(config) { + config.set({ + // base path, that will be used to resolve files and exclude + basePath: '', + + // testing framework to use (jasmine/mocha/qunit/...) + frameworks: ['jasmine'], + + preprocessors: {'*/.html': [] }, + + // list of files / patterns to load in the browser + files: [ + 'bower_components/angular/angular.js', + 'bower_components/angular-mocks/angular-mocks.js', + 'angular-marked.js', + 'bower_components/marked/lib/marked.js', + 'test/spec/**/*.js' + ], + + // list of files / patterns to exclude + exclude: [], + + progress: ['dots'], + + // web server port + port: 8080, + + // level of logging + // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: false, + + + // Start these browsers, currently available: + // - Chrome + // - ChromeCanary + // - Firefox + // - Opera + // - Safari (only Mac) + // - PhantomJS + // - IE (only Windows) + browsers: ['Chrome'], + + + // Continuous Integration mode + // if true, it capture browsers, run tests and exit + singleRun: false + }); +}; \ No newline at end of file diff --git a/fks-chart/bower_components/angular-marked/package.json b/fks-chart/bower_components/angular-marked/package.json new file mode 100755 index 0000000..5186d47 --- /dev/null +++ b/fks-chart/bower_components/angular-marked/package.json @@ -0,0 +1,39 @@ +{ + "name": "angular-marked", + "version": "0.0.12", + "description": "AngularJS Markdown using marked.", + "main": "angular-marked.js", + "directories": { + "test": "test" + }, + "dependencies": {}, + "devDependencies": { + "load-grunt-tasks": "^0.4.0", + "grunt-contrib-jshint": "^0.10.0", + "grunt": "^0.4.4", + "karma": "^0.12.9", + "karma-chrome-launcher": "^0.1.3", + "karma-jasmine": "^0.1.5", + "grunt-contrib-uglify": "^0.4.0", + "grunt-karma": "^0.8.2", + "karma-phantomjs-launcher": "^0.1.4", + "grunt-bump": "0.0.13" + }, + "scripts": { + "test": "grunt test" + }, + "repository": { + "type": "git", + "url": "git://github.com/Hypercubed/angular-marked.git" + }, + "keywords": [ + "marked", + "markdown" + ], + "author": "J. Harshbarger", + "license": "MIT", + "bugs": { + "url": "https://github.com/Hypercubed/angular-marked/issues" + }, + "homepage": "https://github.com/Hypercubed/angular-marked" +} diff --git a/fks-chart/bower_components/angular-marked/todo.md b/fks-chart/bower_components/angular-marked/todo.md new file mode 100755 index 0000000..7a5d6a1 --- /dev/null +++ b/fks-chart/bower_components/angular-marked/todo.md @@ -0,0 +1,8 @@ +# Todo list + +_\( managed using [todo-md](https://github.com/Hypercubed/todo-md) \)_ + +- [ ] Compatibility with RequireJS #3 +- [ ] Add testing to gruntfile +- [x] Minify? +- [ ] ngmin? \ No newline at end of file diff --git a/fks-chart/bower_components/angular/.bower.json b/fks-chart/bower_components/angular/.bower.json new file mode 100644 index 0000000..4bee40b --- /dev/null +++ b/fks-chart/bower_components/angular/.bower.json @@ -0,0 +1,17 @@ +{ + "name": "angular", + "version": "1.2.28", + "main": "./angular.js", + "ignore": [], + "dependencies": {}, + "homepage": "https://github.com/angular/bower-angular", + "_release": "1.2.28", + "_resolution": { + "type": "version", + "tag": "v1.2.28", + "commit": "d1369fe05d3a7d85961a2223292b67ee82b9f80a" + }, + "_source": "git://github.com/angular/bower-angular.git", + "_target": "~1.2.19", + "_originalSource": "angular" +} \ No newline at end of file diff --git a/fks-chart/bower_components/angular/README.md b/fks-chart/bower_components/angular/README.md new file mode 100644 index 0000000..897fb7f --- /dev/null +++ b/fks-chart/bower_components/angular/README.md @@ -0,0 +1,67 @@ +# packaged angular + +This repo is for distribution on `npm` and `bower`. The source for this module is in the +[main AngularJS repo](https://github.com/angular/angular.js). +Please file issues and pull requests against that repo. + +## Install + +You can install this package either with `npm` or with `bower`. + +### npm + +```shell +npm install angular +``` + +Then add a ` +``` + +Note that this package is not in CommonJS format, so doing `require('angular')` will return `undefined`. +If you're using [Browserify](https://github.com/substack/node-browserify), you can use +[exposify](https://github.com/thlorenz/exposify) to have `require('angular')` return the `angular` +global. + +### bower + +```shell +bower install angular +``` + +Then add a ` +``` + +## Documentation + +Documentation is available on the +[AngularJS docs site](http://docs.angularjs.org/). + +## License + +The MIT License + +Copyright (c) 2010-2012 Google, Inc. http://angularjs.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/fks-chart/bower_components/angular/angular-csp.css b/fks-chart/bower_components/angular/angular-csp.css new file mode 100644 index 0000000..3abb3a0 --- /dev/null +++ b/fks-chart/bower_components/angular/angular-csp.css @@ -0,0 +1,24 @@ +/* Include this file in your html if you are using the CSP mode. */ + +@charset "UTF-8"; + +[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], +.ng-cloak, .x-ng-cloak, +.ng-hide { + display: none !important; +} + +ng\:form { + display: block; +} + +.ng-animate-block-transitions { + transition:0s all!important; + -webkit-transition:0s all!important; +} + +/* show the element during a show/hide animation when the + * animation is ongoing, but the .ng-hide class is active */ +.ng-hide-add-active, .ng-hide-remove { + display: block!important; +} diff --git a/fks-chart/bower_components/angular/angular.js b/fks-chart/bower_components/angular/angular.js new file mode 100644 index 0000000..ccf3b4b --- /dev/null +++ b/fks-chart/bower_components/angular/angular.js @@ -0,0 +1,22154 @@ +/** + * @license AngularJS v1.2.28 + * (c) 2010-2014 Google, Inc. http://angularjs.org + * License: MIT + */ +(function(window, document, undefined) {'use strict'; + +/** + * @description + * + * This object provides a utility for producing rich Error messages within + * Angular. It can be called as follows: + * + * var exampleMinErr = minErr('example'); + * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); + * + * The above creates an instance of minErr in the example namespace. The + * resulting error will have a namespaced error code of example.one. The + * resulting error will replace {0} with the value of foo, and {1} with the + * value of bar. The object is not restricted in the number of arguments it can + * take. + * + * If fewer arguments are specified than necessary for interpolation, the extra + * interpolation markers will be preserved in the final string. + * + * Since data will be parsed statically during a build step, some restrictions + * are applied with respect to how minErr instances are created and called. + * Instances should have names of the form namespaceMinErr for a minErr created + * using minErr('namespace') . Error codes, namespaces and template strings + * should all be static strings, not variables or general expressions. + * + * @param {string} module The namespace to use for the new minErr instance. + * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance + */ + +function minErr(module) { + return function () { + var code = arguments[0], + prefix = '[' + (module ? module + ':' : '') + code + '] ', + template = arguments[1], + templateArgs = arguments, + stringify = function (obj) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (typeof obj === 'undefined') { + return 'undefined'; + } else if (typeof obj !== 'string') { + return JSON.stringify(obj); + } + return obj; + }, + message, i; + + message = prefix + template.replace(/\{\d+\}/g, function (match) { + var index = +match.slice(1, -1), arg; + + if (index + 2 < templateArgs.length) { + arg = templateArgs[index + 2]; + if (typeof arg === 'function') { + return arg.toString().replace(/ ?\{[\s\S]*$/, ''); + } else if (typeof arg === 'undefined') { + return 'undefined'; + } else if (typeof arg !== 'string') { + return toJson(arg); + } + return arg; + } + return match; + }); + + message = message + '\nhttp://errors.angularjs.org/1.2.28/' + + (module ? module + '/' : '') + code; + for (i = 2; i < arguments.length; i++) { + message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + + encodeURIComponent(stringify(arguments[i])); + } + + return new Error(message); + }; +} + +/* We need to tell jshint what variables are being exported */ +/* global angular: true, + msie: true, + jqLite: true, + jQuery: true, + slice: true, + push: true, + toString: true, + ngMinErr: true, + angularModule: true, + nodeName_: true, + uid: true, + VALIDITY_STATE_PROPERTY: true, + + lowercase: true, + uppercase: true, + manualLowercase: true, + manualUppercase: true, + nodeName_: true, + isArrayLike: true, + forEach: true, + sortedKeys: true, + forEachSorted: true, + reverseParams: true, + nextUid: true, + setHashKey: true, + extend: true, + int: true, + inherit: true, + noop: true, + identity: true, + valueFn: true, + isUndefined: true, + isDefined: true, + isObject: true, + isString: true, + isNumber: true, + isDate: true, + isArray: true, + isFunction: true, + isRegExp: true, + isWindow: true, + isScope: true, + isFile: true, + isBlob: true, + isBoolean: true, + isPromiseLike: true, + trim: true, + isElement: true, + makeMap: true, + map: true, + size: true, + includes: true, + indexOf: true, + arrayRemove: true, + isLeafNode: true, + copy: true, + shallowCopy: true, + equals: true, + csp: true, + concat: true, + sliceArgs: true, + bind: true, + toJsonReplacer: true, + toJson: true, + fromJson: true, + toBoolean: true, + startingTag: true, + tryDecodeURIComponent: true, + parseKeyValue: true, + toKeyValue: true, + encodeUriSegment: true, + encodeUriQuery: true, + angularInit: true, + bootstrap: true, + snake_case: true, + bindJQuery: true, + assertArg: true, + assertArgFn: true, + assertNotHasOwnProperty: true, + getter: true, + getBlockElements: true, + hasOwnProperty: true, +*/ + +//////////////////////////////////// + +/** + * @ngdoc module + * @name ng + * @module ng + * @description + * + * # ng (core module) + * The ng module is loaded by default when an AngularJS application is started. The module itself + * contains the essential components for an AngularJS application to function. The table below + * lists a high level breakdown of each of the services/factories, filters, directives and testing + * components available within this core module. + * + *
+ */ + +// The name of a form control's ValidityState property. +// This is used so that it's possible for internal tests to create mock ValidityStates. +var VALIDITY_STATE_PROPERTY = 'validity'; + +/** + * @ngdoc function + * @name angular.lowercase + * @module ng + * @kind function + * + * @description Converts the specified string to lowercase. + * @param {string} string String to be converted to lowercase. + * @returns {string} Lowercased string. + */ +var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * @ngdoc function + * @name angular.uppercase + * @module ng + * @kind function + * + * @description Converts the specified string to uppercase. + * @param {string} string String to be converted to uppercase. + * @returns {string} Uppercased string. + */ +var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; + + +var manualLowercase = function(s) { + /* jshint bitwise: false */ + return isString(s) + ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) + : s; +}; +var manualUppercase = function(s) { + /* jshint bitwise: false */ + return isString(s) + ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) + : s; +}; + + +// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish +// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods +// with correct but slower alternatives. +if ('i' !== 'I'.toLowerCase()) { + lowercase = manualLowercase; + uppercase = manualUppercase; +} + + +var + msie, // holds major version number for IE, or NaN if UA is not IE. + jqLite, // delay binding since jQuery could be loaded after us. + jQuery, // delay binding + slice = [].slice, + push = [].push, + toString = Object.prototype.toString, + ngMinErr = minErr('ng'), + + /** @name angular */ + angular = window.angular || (window.angular = {}), + angularModule, + nodeName_, + uid = ['0', '0', '0']; + +/** + * IE 11 changed the format of the UserAgent string. + * See http://msdn.microsoft.com/en-us/library/ms537503.aspx + */ +msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); +if (isNaN(msie)) { + msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); +} + + +/** + * @private + * @param {*} obj + * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, + * String ...) + */ +function isArrayLike(obj) { + if (obj == null || isWindow(obj)) { + return false; + } + + var length = obj.length; + + if (obj.nodeType === 1 && length) { + return true; + } + + return isString(obj) || isArray(obj) || length === 0 || + typeof length === 'number' && length > 0 && (length - 1) in obj; +} + +/** + * @ngdoc function + * @name angular.forEach + * @module ng + * @kind function + * + * @description + * Invokes the `iterator` function once for each item in `obj` collection, which can be either an + * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` + * is the value of an object property or an array element and `key` is the object property key or + * array element index. Specifying a `context` for the function is optional. + * + * It is worth noting that `.forEach` does not iterate over inherited properties because it filters + * using the `hasOwnProperty` method. + * + ```js + var values = {name: 'misko', gender: 'male'}; + var log = []; + angular.forEach(values, function(value, key) { + this.push(key + ': ' + value); + }, log); + expect(log).toEqual(['name: misko', 'gender: male']); + ``` + * + * @param {Object|Array} obj Object to iterate over. + * @param {Function} iterator Iterator function. + * @param {Object=} context Object to become context (`this`) for the iterator function. + * @returns {Object|Array} Reference to `obj`. + */ +function forEach(obj, iterator, context) { + var key; + if (obj) { + if (isFunction(obj)) { + for (key in obj) { + // Need to check if hasOwnProperty exists, + // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function + if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { + iterator.call(context, obj[key], key); + } + } + } else if (isArray(obj) || isArrayLike(obj)) { + for (key = 0; key < obj.length; key++) { + iterator.call(context, obj[key], key); + } + } else if (obj.forEach && obj.forEach !== forEach) { + obj.forEach(iterator, context); + } else { + for (key in obj) { + if (obj.hasOwnProperty(key)) { + iterator.call(context, obj[key], key); + } + } + } + } + return obj; +} + +function sortedKeys(obj) { + var keys = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + keys.push(key); + } + } + return keys.sort(); +} + +function forEachSorted(obj, iterator, context) { + var keys = sortedKeys(obj); + for ( var i = 0; i < keys.length; i++) { + iterator.call(context, obj[keys[i]], keys[i]); + } + return keys; +} + + +/** + * when using forEach the params are value, key, but it is often useful to have key, value. + * @param {function(string, *)} iteratorFn + * @returns {function(*, string)} + */ +function reverseParams(iteratorFn) { + return function(value, key) { iteratorFn(key, value); }; +} + +/** + * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric + * characters such as '012ABC'. The reason why we are not using simply a number counter is that + * the number string gets longer over time, and it can also overflow, where as the nextId + * will grow much slower, it is a string, and it will never overflow. + * + * @returns {string} an unique alpha-numeric string + */ +function nextUid() { + var index = uid.length; + var digit; + + while(index) { + index--; + digit = uid[index].charCodeAt(0); + if (digit == 57 /*'9'*/) { + uid[index] = 'A'; + return uid.join(''); + } + if (digit == 90 /*'Z'*/) { + uid[index] = '0'; + } else { + uid[index] = String.fromCharCode(digit + 1); + return uid.join(''); + } + } + uid.unshift('0'); + return uid.join(''); +} + + +/** + * Set or clear the hashkey for an object. + * @param obj object + * @param h the hashkey (!truthy to delete the hashkey) + */ +function setHashKey(obj, h) { + if (h) { + obj.$$hashKey = h; + } + else { + delete obj.$$hashKey; + } +} + +/** + * @ngdoc function + * @name angular.extend + * @module ng + * @kind function + * + * @description + * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) + * to `dst`. You can specify multiple `src` objects. + * + * @param {Object} dst Destination object. + * @param {...Object} src Source object(s). + * @returns {Object} Reference to `dst`. + */ +function extend(dst) { + var h = dst.$$hashKey; + forEach(arguments, function(obj) { + if (obj !== dst) { + forEach(obj, function(value, key) { + dst[key] = value; + }); + } + }); + + setHashKey(dst,h); + return dst; +} + +function int(str) { + return parseInt(str, 10); +} + + +function inherit(parent, extra) { + return extend(new (extend(function() {}, {prototype:parent}))(), extra); +} + +/** + * @ngdoc function + * @name angular.noop + * @module ng + * @kind function + * + * @description + * A function that performs no operations. This function can be useful when writing code in the + * functional style. + ```js + function foo(callback) { + var result = calculateResult(); + (callback || angular.noop)(result); + } + ``` + */ +function noop() {} +noop.$inject = []; + + +/** + * @ngdoc function + * @name angular.identity + * @module ng + * @kind function + * + * @description + * A function that returns its first argument. This function is useful when writing code in the + * functional style. + * + ```js + function transformer(transformationFn, value) { + return (transformationFn || angular.identity)(value); + }; + ``` + */ +function identity($) {return $;} +identity.$inject = []; + + +function valueFn(value) {return function() {return value;};} + +/** + * @ngdoc function + * @name angular.isUndefined + * @module ng + * @kind function + * + * @description + * Determines if a reference is undefined. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is undefined. + */ +function isUndefined(value){return typeof value === 'undefined';} + + +/** + * @ngdoc function + * @name angular.isDefined + * @module ng + * @kind function + * + * @description + * Determines if a reference is defined. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is defined. + */ +function isDefined(value){return typeof value !== 'undefined';} + + +/** + * @ngdoc function + * @name angular.isObject + * @module ng + * @kind function + * + * @description + * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not + * considered to be objects. Note that JavaScript arrays are objects. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is an `Object` but not `null`. + */ +function isObject(value){return value != null && typeof value === 'object';} + + +/** + * @ngdoc function + * @name angular.isString + * @module ng + * @kind function + * + * @description + * Determines if a reference is a `String`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `String`. + */ +function isString(value){return typeof value === 'string';} + + +/** + * @ngdoc function + * @name angular.isNumber + * @module ng + * @kind function + * + * @description + * Determines if a reference is a `Number`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `Number`. + */ +function isNumber(value){return typeof value === 'number';} + + +/** + * @ngdoc function + * @name angular.isDate + * @module ng + * @kind function + * + * @description + * Determines if a value is a date. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `Date`. + */ +function isDate(value) { + return toString.call(value) === '[object Date]'; +} + + +/** + * @ngdoc function + * @name angular.isArray + * @module ng + * @kind function + * + * @description + * Determines if a reference is an `Array`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is an `Array`. + */ +var isArray = (function() { + if (!isFunction(Array.isArray)) { + return function(value) { + return toString.call(value) === '[object Array]'; + }; + } + return Array.isArray; +})(); + +/** + * @ngdoc function + * @name angular.isFunction + * @module ng + * @kind function + * + * @description + * Determines if a reference is a `Function`. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `Function`. + */ +function isFunction(value){return typeof value === 'function';} + + +/** + * Determines if a value is a regular expression object. + * + * @private + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a `RegExp`. + */ +function isRegExp(value) { + return toString.call(value) === '[object RegExp]'; +} + + +/** + * Checks if `obj` is a window object. + * + * @private + * @param {*} obj Object to check + * @returns {boolean} True if `obj` is a window obj. + */ +function isWindow(obj) { + return obj && obj.document && obj.location && obj.alert && obj.setInterval; +} + + +function isScope(obj) { + return obj && obj.$evalAsync && obj.$watch; +} + + +function isFile(obj) { + return toString.call(obj) === '[object File]'; +} + + +function isBlob(obj) { + return toString.call(obj) === '[object Blob]'; +} + + +function isBoolean(value) { + return typeof value === 'boolean'; +} + + +function isPromiseLike(obj) { + return obj && isFunction(obj.then); +} + + +var trim = (function() { + // native trim is way faster: http://jsperf.com/angular-trim-test + // but IE doesn't have it... :-( + // TODO: we should move this into IE/ES5 polyfill + if (!String.prototype.trim) { + return function(value) { + return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; + }; + } + return function(value) { + return isString(value) ? value.trim() : value; + }; +})(); + + +/** + * @ngdoc function + * @name angular.isElement + * @module ng + * @kind function + * + * @description + * Determines if a reference is a DOM element (or wrapped jQuery element). + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). + */ +function isElement(node) { + return !!(node && + (node.nodeName // we are a direct element + || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API +} + +/** + * @param str 'key1,key2,...' + * @returns {object} in the form of {key1:true, key2:true, ...} + */ +function makeMap(str) { + var obj = {}, items = str.split(","), i; + for ( i = 0; i < items.length; i++ ) + obj[ items[i] ] = true; + return obj; +} + + +if (msie < 9) { + nodeName_ = function(element) { + element = element.nodeName ? element : element[0]; + return (element.scopeName && element.scopeName != 'HTML') + ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; + }; +} else { + nodeName_ = function(element) { + return element.nodeName ? element.nodeName : element[0].nodeName; + }; +} + + +function map(obj, iterator, context) { + var results = []; + forEach(obj, function(value, index, list) { + results.push(iterator.call(context, value, index, list)); + }); + return results; +} + + +/** + * @description + * Determines the number of elements in an array, the number of properties an object has, or + * the length of a string. + * + * Note: This function is used to augment the Object type in Angular expressions. See + * {@link angular.Object} for more information about Angular arrays. + * + * @param {Object|Array|string} obj Object, array, or string to inspect. + * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object + * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. + */ +function size(obj, ownPropsOnly) { + var count = 0, key; + + if (isArray(obj) || isString(obj)) { + return obj.length; + } else if (isObject(obj)) { + for (key in obj) + if (!ownPropsOnly || obj.hasOwnProperty(key)) + count++; + } + + return count; +} + + +function includes(array, obj) { + return indexOf(array, obj) != -1; +} + +function indexOf(array, obj) { + if (array.indexOf) return array.indexOf(obj); + + for (var i = 0; i < array.length; i++) { + if (obj === array[i]) return i; + } + return -1; +} + +function arrayRemove(array, value) { + var index = indexOf(array, value); + if (index >=0) + array.splice(index, 1); + return value; +} + +function isLeafNode (node) { + if (node) { + switch (node.nodeName) { + case "OPTION": + case "PRE": + case "TITLE": + return true; + } + } + return false; +} + +/** + * @ngdoc function + * @name angular.copy + * @module ng + * @kind function + * + * @description + * Creates a deep copy of `source`, which should be an object or an array. + * + * * If no destination is supplied, a copy of the object or array is created. + * * If a destination is provided, all of its elements (for array) or properties (for objects) + * are deleted and then all elements/properties from the source are copied to it. + * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. + * * If `source` is identical to 'destination' an exception will be thrown. + * + * @param {*} source The source that will be used to make a copy. + * Can be any type, including primitives, `null`, and `undefined`. + * @param {(Object|Array)=} destination Destination into which the source is copied. If + * provided, must be of the same type as `source`. + * @returns {*} The copy or updated `destination`, if `destination` was specified. + * + * @example + + +
+
+ Name:
+ E-mail:
+ Gender: male + female
+ + +
+
form = {{user | json}}
+
master = {{master | json}}
+
+ + +
+
+ */ +function copy(source, destination, stackSource, stackDest) { + if (isWindow(source) || isScope(source)) { + throw ngMinErr('cpws', + "Can't copy! Making copies of Window or Scope instances is not supported."); + } + + if (!destination) { + destination = source; + if (source) { + if (isArray(source)) { + destination = copy(source, [], stackSource, stackDest); + } else if (isDate(source)) { + destination = new Date(source.getTime()); + } else if (isRegExp(source)) { + destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); + destination.lastIndex = source.lastIndex; + } else if (isObject(source)) { + destination = copy(source, {}, stackSource, stackDest); + } + } + } else { + if (source === destination) throw ngMinErr('cpi', + "Can't copy! Source and destination are identical."); + + stackSource = stackSource || []; + stackDest = stackDest || []; + + if (isObject(source)) { + var index = indexOf(stackSource, source); + if (index !== -1) return stackDest[index]; + + stackSource.push(source); + stackDest.push(destination); + } + + var result; + if (isArray(source)) { + destination.length = 0; + for ( var i = 0; i < source.length; i++) { + result = copy(source[i], null, stackSource, stackDest); + if (isObject(source[i])) { + stackSource.push(source[i]); + stackDest.push(result); + } + destination.push(result); + } + } else { + var h = destination.$$hashKey; + if (isArray(destination)) { + destination.length = 0; + } else { + forEach(destination, function(value, key) { + delete destination[key]; + }); + } + for ( var key in source) { + result = copy(source[key], null, stackSource, stackDest); + if (isObject(source[key])) { + stackSource.push(source[key]); + stackDest.push(result); + } + destination[key] = result; + } + setHashKey(destination,h); + } + + } + return destination; +} + +/** + * Creates a shallow copy of an object, an array or a primitive + */ +function shallowCopy(src, dst) { + if (isArray(src)) { + dst = dst || []; + + for ( var i = 0; i < src.length; i++) { + dst[i] = src[i]; + } + } else if (isObject(src)) { + dst = dst || {}; + + for (var key in src) { + if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { + dst[key] = src[key]; + } + } + } + + return dst || src; +} + + +/** + * @ngdoc function + * @name angular.equals + * @module ng + * @kind function + * + * @description + * Determines if two objects or two values are equivalent. Supports value types, regular + * expressions, arrays and objects. + * + * Two objects or values are considered equivalent if at least one of the following is true: + * + * * Both objects or values pass `===` comparison. + * * Both objects or values are of the same type and all of their properties are equal by + * comparing them with `angular.equals`. + * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) + * * Both values represent the same regular expression (In JavaScript, + * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual + * representation matches). + * + * During a property comparison, properties of `function` type and properties with names + * that begin with `$` are ignored. + * + * Scope and DOMWindow objects are being compared only by identify (`===`). + * + * @param {*} o1 Object or value to compare. + * @param {*} o2 Object or value to compare. + * @returns {boolean} True if arguments are equal. + */ +function equals(o1, o2) { + if (o1 === o2) return true; + if (o1 === null || o2 === null) return false; + if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN + var t1 = typeof o1, t2 = typeof o2, length, key, keySet; + if (t1 == t2) { + if (t1 == 'object') { + if (isArray(o1)) { + if (!isArray(o2)) return false; + if ((length = o1.length) == o2.length) { + for(key=0; key 2 ? sliceArgs(arguments, 2) : []; + if (isFunction(fn) && !(fn instanceof RegExp)) { + return curryArgs.length + ? function() { + return arguments.length + ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) + : fn.apply(self, curryArgs); + } + : function() { + return arguments.length + ? fn.apply(self, arguments) + : fn.call(self); + }; + } else { + // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) + return fn; + } +} + + +function toJsonReplacer(key, value) { + var val = value; + + if (typeof key === 'string' && key.charAt(0) === '$') { + val = undefined; + } else if (isWindow(value)) { + val = '$WINDOW'; + } else if (value && document === value) { + val = '$DOCUMENT'; + } else if (isScope(value)) { + val = '$SCOPE'; + } + + return val; +} + + +/** + * @ngdoc function + * @name angular.toJson + * @module ng + * @kind function + * + * @description + * Serializes input into a JSON-formatted string. Properties with leading $ characters will be + * stripped since angular uses this notation internally. + * + * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. + * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. + * @returns {string|undefined} JSON-ified string representing `obj`. + */ +function toJson(obj, pretty) { + if (typeof obj === 'undefined') return undefined; + return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); +} + + +/** + * @ngdoc function + * @name angular.fromJson + * @module ng + * @kind function + * + * @description + * Deserializes a JSON string. + * + * @param {string} json JSON string to deserialize. + * @returns {Object|Array|string|number} Deserialized thingy. + */ +function fromJson(json) { + return isString(json) + ? JSON.parse(json) + : json; +} + + +function toBoolean(value) { + if (typeof value === 'function') { + value = true; + } else if (value && value.length !== 0) { + var v = lowercase("" + value); + value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); + } else { + value = false; + } + return value; +} + +/** + * @returns {string} Returns the string representation of the element. + */ +function startingTag(element) { + element = jqLite(element).clone(); + try { + // turns out IE does not let you set .html() on elements which + // are not allowed to have children. So we just ignore it. + element.empty(); + } catch(e) {} + // As Per DOM Standards + var TEXT_NODE = 3; + var elemHtml = jqLite('
').append(element).html(); + try { + return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : + elemHtml. + match(/^(<[^>]+>)/)[1]. + replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); + } catch(e) { + return lowercase(elemHtml); + } + +} + + +///////////////////////////////////////////////// + +/** + * Tries to decode the URI component without throwing an exception. + * + * @private + * @param str value potential URI component to check. + * @returns {boolean} True if `value` can be decoded + * with the decodeURIComponent function. + */ +function tryDecodeURIComponent(value) { + try { + return decodeURIComponent(value); + } catch(e) { + // Ignore any invalid uri component + } +} + + +/** + * Parses an escaped url query string into key-value pairs. + * @returns {Object.} + */ +function parseKeyValue(/**string*/keyValue) { + var obj = {}, key_value, key; + forEach((keyValue || "").split('&'), function(keyValue) { + if ( keyValue ) { + key_value = keyValue.replace(/\+/g,'%20').split('='); + key = tryDecodeURIComponent(key_value[0]); + if ( isDefined(key) ) { + var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; + if (!hasOwnProperty.call(obj, key)) { + obj[key] = val; + } else if(isArray(obj[key])) { + obj[key].push(val); + } else { + obj[key] = [obj[key],val]; + } + } + } + }); + return obj; +} + +function toKeyValue(obj) { + var parts = []; + forEach(obj, function(value, key) { + if (isArray(value)) { + forEach(value, function(arrayValue) { + parts.push(encodeUriQuery(key, true) + + (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); + }); + } else { + parts.push(encodeUriQuery(key, true) + + (value === true ? '' : '=' + encodeUriQuery(value, true))); + } + }); + return parts.length ? parts.join('&') : ''; +} + + +/** + * We need our custom method because encodeURIComponent is too aggressive and doesn't follow + * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path + * segments: + * segment = *pchar + * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + * pct-encoded = "%" HEXDIG HEXDIG + * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + * / "*" / "+" / "," / ";" / "=" + */ +function encodeUriSegment(val) { + return encodeUriQuery(val, true). + replace(/%26/gi, '&'). + replace(/%3D/gi, '='). + replace(/%2B/gi, '+'); +} + + +/** + * This method is intended for encoding *key* or *value* parts of query component. We need a custom + * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be + * encoded per http://tools.ietf.org/html/rfc3986: + * query = *( pchar / "/" / "?" ) + * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * pct-encoded = "%" HEXDIG HEXDIG + * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + * / "*" / "+" / "," / ";" / "=" + */ +function encodeUriQuery(val, pctEncodeSpaces) { + return encodeURIComponent(val). + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); +} + + +/** + * @ngdoc directive + * @name ngApp + * @module ng + * + * @element ANY + * @param {angular.Module} ngApp an optional application + * {@link angular.module module} name to load. + * + * @description + * + * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive + * designates the **root element** of the application and is typically placed near the root element + * of the page - e.g. on the `` or `` tags. + * + * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` + * found in the document will be used to define the root element to auto-bootstrap as an + * application. To run multiple applications in an HTML document you must manually bootstrap them using + * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. + * + * You can specify an **AngularJS module** to be used as the root module for the application. This + * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and + * should contain the application code needed or have dependencies on other modules that will + * contain the code. See {@link angular.module} for more information. + * + * In the example below if the `ngApp` directive were not placed on the `html` element then the + * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` + * would not be resolved to `3`. + * + * `ngApp` is the easiest, and most common, way to bootstrap an application. + * + + +
+ I can add: {{a}} + {{b}} = {{ a+b }} +
+
+ + angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { + $scope.a = 1; + $scope.b = 2; + }); + +
+ * + */ +function angularInit(element, bootstrap) { + var elements = [element], + appElement, + module, + names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], + NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; + + function append(element) { + element && elements.push(element); + } + + forEach(names, function(name) { + names[name] = true; + append(document.getElementById(name)); + name = name.replace(':', '\\:'); + if (element.querySelectorAll) { + forEach(element.querySelectorAll('.' + name), append); + forEach(element.querySelectorAll('.' + name + '\\:'), append); + forEach(element.querySelectorAll('[' + name + ']'), append); + } + }); + + forEach(elements, function(element) { + if (!appElement) { + var className = ' ' + element.className + ' '; + var match = NG_APP_CLASS_REGEXP.exec(className); + if (match) { + appElement = element; + module = (match[2] || '').replace(/\s+/g, ','); + } else { + forEach(element.attributes, function(attr) { + if (!appElement && names[attr.name]) { + appElement = element; + module = attr.value; + } + }); + } + } + }); + if (appElement) { + bootstrap(appElement, module ? [module] : []); + } +} + +/** + * @ngdoc function + * @name angular.bootstrap + * @module ng + * @description + * Use this function to manually start up angular application. + * + * See: {@link guide/bootstrap Bootstrap} + * + * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually. + * They must use {@link ng.directive:ngApp ngApp}. + * + * Angular will detect if it has been loaded into the browser more than once and only allow the + * first loaded script to be bootstrapped and will report a warning to the browser console for + * each of the subsequent scripts. This prevents strange results in applications, where otherwise + * multiple instances of Angular try to work on the DOM. + * + * + * + * + *
+ * + * + * + * + * + * + * + *
{{heading}}
{{fill}}
+ *
+ *
+ * + * var app = angular.module('multi-bootstrap', []) + * + * .controller('BrokenTable', function($scope) { + * $scope.headings = ['One', 'Two', 'Three']; + * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]]; + * }); + * + * + * it('should only insert one table cell for each item in $scope.fillings', function() { + * expect(element.all(by.css('td')).count()) + * .toBe(9); + * }); + * + *
+ * + * @param {DOMElement} element DOM element which is the root of angular application. + * @param {Array=} modules an array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a run block. + * See: {@link angular.module modules} + * @returns {auto.$injector} Returns the newly created injector for this app. + */ +function bootstrap(element, modules) { + var doBootstrap = function() { + element = jqLite(element); + + if (element.injector()) { + var tag = (element[0] === document) ? 'document' : startingTag(element); + //Encode angle brackets to prevent input from being sanitized to empty string #8683 + throw ngMinErr( + 'btstrpd', + "App Already Bootstrapped with this Element '{0}'", + tag.replace(//,'>')); + } + + modules = modules || []; + modules.unshift(['$provide', function($provide) { + $provide.value('$rootElement', element); + }]); + modules.unshift('ng'); + var injector = createInjector(modules); + injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', + function(scope, element, compile, injector, animate) { + scope.$apply(function() { + element.data('$injector', injector); + compile(element)(scope); + }); + }] + ); + return injector; + }; + + var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; + + if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { + return doBootstrap(); + } + + window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); + angular.resumeBootstrap = function(extraModules) { + forEach(extraModules, function(module) { + modules.push(module); + }); + doBootstrap(); + }; +} + +var SNAKE_CASE_REGEXP = /[A-Z]/g; +function snake_case(name, separator) { + separator = separator || '_'; + return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { + return (pos ? separator : '') + letter.toLowerCase(); + }); +} + +function bindJQuery() { + // bind to jQuery if present; + jQuery = window.jQuery; + // Use jQuery if it exists with proper functionality, otherwise default to us. + // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support. + if (jQuery && jQuery.fn.on) { + jqLite = jQuery; + extend(jQuery.fn, { + scope: JQLitePrototype.scope, + isolateScope: JQLitePrototype.isolateScope, + controller: JQLitePrototype.controller, + injector: JQLitePrototype.injector, + inheritedData: JQLitePrototype.inheritedData + }); + // Method signature: + // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) + jqLitePatchJQueryRemove('remove', true, true, false); + jqLitePatchJQueryRemove('empty', false, false, false); + jqLitePatchJQueryRemove('html', false, false, true); + } else { + jqLite = JQLite; + } + angular.element = jqLite; +} + +/** + * throw error if the argument is falsy. + */ +function assertArg(arg, name, reason) { + if (!arg) { + throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); + } + return arg; +} + +function assertArgFn(arg, name, acceptArrayAnnotation) { + if (acceptArrayAnnotation && isArray(arg)) { + arg = arg[arg.length - 1]; + } + + assertArg(isFunction(arg), name, 'not a function, got ' + + (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); + return arg; +} + +/** + * throw error if the name given is hasOwnProperty + * @param {String} name the name to test + * @param {String} context the context in which the name is used, such as module or directive + */ +function assertNotHasOwnProperty(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); + } +} + +/** + * Return the value accessible from the object by path. Any undefined traversals are ignored + * @param {Object} obj starting object + * @param {String} path path to traverse + * @param {boolean} [bindFnToScope=true] + * @returns {Object} value as accessible by path + */ +//TODO(misko): this function needs to be removed +function getter(obj, path, bindFnToScope) { + if (!path) return obj; + var keys = path.split('.'); + var key; + var lastInstance = obj; + var len = keys.length; + + for (var i = 0; i < len; i++) { + key = keys[i]; + if (obj) { + obj = (lastInstance = obj)[key]; + } + } + if (!bindFnToScope && isFunction(obj)) { + return bind(lastInstance, obj); + } + return obj; +} + +/** + * Return the DOM siblings between the first and last node in the given array. + * @param {Array} array like object + * @returns {DOMElement} object containing the elements + */ +function getBlockElements(nodes) { + var startNode = nodes[0], + endNode = nodes[nodes.length - 1]; + if (startNode === endNode) { + return jqLite(startNode); + } + + var element = startNode; + var elements = [element]; + + do { + element = element.nextSibling; + if (!element) break; + elements.push(element); + } while (element !== endNode); + + return jqLite(elements); +} + +/** + * @ngdoc type + * @name angular.Module + * @module ng + * @description + * + * Interface for configuring angular {@link angular.module modules}. + */ + +function setupModuleLoader(window) { + + var $injectorMinErr = minErr('$injector'); + var ngMinErr = minErr('ng'); + + function ensure(obj, name, factory) { + return obj[name] || (obj[name] = factory()); + } + + var angular = ensure(window, 'angular', Object); + + // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap + angular.$$minErr = angular.$$minErr || minErr; + + return ensure(angular, 'module', function() { + /** @type {Object.} */ + var modules = {}; + + /** + * @ngdoc function + * @name angular.module + * @module ng + * @description + * + * The `angular.module` is a global place for creating, registering and retrieving Angular + * modules. + * All modules (angular core or 3rd party) that should be available to an application must be + * registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an + * existing module (the name passed as the first argument to `module`) is retrieved. + * + * + * # Module + * + * A module is a collection of services, directives, controllers, filters, and configuration information. + * `angular.module` is used to configure the {@link auto.$injector $injector}. + * + * ```js + * // Create a new module + * var myModule = angular.module('myModule', []); + * + * // register a new service + * myModule.value('appName', 'MyCoolApp'); + * + * // configure existing services inside initialization blocks. + * myModule.config(['$locationProvider', function($locationProvider) { + * // Configure existing providers + * $locationProvider.hashPrefix('!'); + * }]); + * ``` + * + * Then you can create an injector and load your modules like this: + * + * ```js + * var injector = angular.injector(['ng', 'myModule']) + * ``` + * + * However it's more likely that you'll just use + * {@link ng.directive:ngApp ngApp} or + * {@link angular.bootstrap} to simplify this process for you. + * + * @param {!string} name The name of the module to create or retrieve. + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as + * {@link angular.Module#config Module#config()}. + * @returns {module} new module with the {@link angular.Module} api. + */ + return function module(name, requires, configFn) { + var assertNotHasOwnProperty = function(name, context) { + if (name === 'hasOwnProperty') { + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); + } + }; + + assertNotHasOwnProperty(name, 'module'); + if (requires && modules.hasOwnProperty(name)) { + modules[name] = null; + } + return ensure(modules, name, function() { + if (!requires) { + throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + + "the module name or forgot to load it. If registering a module ensure that you " + + "specify the dependencies as the second argument.", name); + } + + /** @type {!Array.>} */ + var invokeQueue = []; + + /** @type {!Array.} */ + var runBlocks = []; + + var config = invokeLater('$injector', 'invoke'); + + /** @type {angular.Module} */ + var moduleInstance = { + // Private state + _invokeQueue: invokeQueue, + _runBlocks: runBlocks, + + /** + * @ngdoc property + * @name angular.Module#requires + * @module ng + * + * @description + * Holds the list of modules which the injector will load before the current module is + * loaded. + */ + requires: requires, + + /** + * @ngdoc property + * @name angular.Module#name + * @module ng + * + * @description + * Name of the module. + */ + name: name, + + + /** + * @ngdoc method + * @name angular.Module#provider + * @module ng + * @param {string} name service name + * @param {Function} providerType Construction function for creating new instance of the + * service. + * @description + * See {@link auto.$provide#provider $provide.provider()}. + */ + provider: invokeLater('$provide', 'provider'), + + /** + * @ngdoc method + * @name angular.Module#factory + * @module ng + * @param {string} name service name + * @param {Function} providerFunction Function for creating new instance of the service. + * @description + * See {@link auto.$provide#factory $provide.factory()}. + */ + factory: invokeLater('$provide', 'factory'), + + /** + * @ngdoc method + * @name angular.Module#service + * @module ng + * @param {string} name service name + * @param {Function} constructor A constructor function that will be instantiated. + * @description + * See {@link auto.$provide#service $provide.service()}. + */ + service: invokeLater('$provide', 'service'), + + /** + * @ngdoc method + * @name angular.Module#value + * @module ng + * @param {string} name service name + * @param {*} object Service instance object. + * @description + * See {@link auto.$provide#value $provide.value()}. + */ + value: invokeLater('$provide', 'value'), + + /** + * @ngdoc method + * @name angular.Module#constant + * @module ng + * @param {string} name constant name + * @param {*} object Constant value. + * @description + * Because the constant are fixed, they get applied before other provide methods. + * See {@link auto.$provide#constant $provide.constant()}. + */ + constant: invokeLater('$provide', 'constant', 'unshift'), + + /** + * @ngdoc method + * @name angular.Module#animation + * @module ng + * @param {string} name animation name + * @param {Function} animationFactory Factory function for creating new instance of an + * animation. + * @description + * + * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. + * + * + * Defines an animation hook that can be later used with + * {@link ngAnimate.$animate $animate} service and directives that use this service. + * + * ```js + * module.animation('.animation-name', function($inject1, $inject2) { + * return { + * eventName : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction(element) { + * //code to cancel the animation + * } + * } + * } + * }) + * ``` + * + * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and + * {@link ngAnimate ngAnimate module} for more information. + */ + animation: invokeLater('$animateProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#filter + * @module ng + * @param {string} name Filter name. + * @param {Function} filterFactory Factory function for creating new instance of filter. + * @description + * See {@link ng.$filterProvider#register $filterProvider.register()}. + */ + filter: invokeLater('$filterProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#controller + * @module ng + * @param {string|Object} name Controller name, or an object map of controllers where the + * keys are the names and the values are the constructors. + * @param {Function} constructor Controller constructor function. + * @description + * See {@link ng.$controllerProvider#register $controllerProvider.register()}. + */ + controller: invokeLater('$controllerProvider', 'register'), + + /** + * @ngdoc method + * @name angular.Module#directive + * @module ng + * @param {string|Object} name Directive name, or an object map of directives where the + * keys are the names and the values are the factories. + * @param {Function} directiveFactory Factory function for creating new instance of + * directives. + * @description + * See {@link ng.$compileProvider#directive $compileProvider.directive()}. + */ + directive: invokeLater('$compileProvider', 'directive'), + + /** + * @ngdoc method + * @name angular.Module#config + * @module ng + * @param {Function} configFn Execute this function on module load. Useful for service + * configuration. + * @description + * Use this method to register work which needs to be performed on module loading. + * For more about how to configure services, see + * {@link providers#providers_provider-recipe Provider Recipe}. + */ + config: config, + + /** + * @ngdoc method + * @name angular.Module#run + * @module ng + * @param {Function} initializationFn Execute this function after injector creation. + * Useful for application initialization. + * @description + * Use this method to register work which should be performed when the injector is done + * loading all modules. + */ + run: function(block) { + runBlocks.push(block); + return this; + } + }; + + if (configFn) { + config(configFn); + } + + return moduleInstance; + + /** + * @param {string} provider + * @param {string} method + * @param {String=} insertMethod + * @returns {angular.Module} + */ + function invokeLater(provider, method, insertMethod) { + return function() { + invokeQueue[insertMethod || 'push']([provider, method, arguments]); + return moduleInstance; + }; + } + }); + }; + }); + +} + +/* global angularModule: true, + version: true, + + $LocaleProvider, + $CompileProvider, + + htmlAnchorDirective, + inputDirective, + inputDirective, + formDirective, + scriptDirective, + selectDirective, + styleDirective, + optionDirective, + ngBindDirective, + ngBindHtmlDirective, + ngBindTemplateDirective, + ngClassDirective, + ngClassEvenDirective, + ngClassOddDirective, + ngCspDirective, + ngCloakDirective, + ngControllerDirective, + ngFormDirective, + ngHideDirective, + ngIfDirective, + ngIncludeDirective, + ngIncludeFillContentDirective, + ngInitDirective, + ngNonBindableDirective, + ngPluralizeDirective, + ngRepeatDirective, + ngShowDirective, + ngStyleDirective, + ngSwitchDirective, + ngSwitchWhenDirective, + ngSwitchDefaultDirective, + ngOptionsDirective, + ngTranscludeDirective, + ngModelDirective, + ngListDirective, + ngChangeDirective, + requiredDirective, + requiredDirective, + ngValueDirective, + ngAttributeAliasDirectives, + ngEventDirectives, + + $AnchorScrollProvider, + $AnimateProvider, + $BrowserProvider, + $CacheFactoryProvider, + $ControllerProvider, + $DocumentProvider, + $ExceptionHandlerProvider, + $FilterProvider, + $InterpolateProvider, + $IntervalProvider, + $HttpProvider, + $HttpBackendProvider, + $LocationProvider, + $LogProvider, + $ParseProvider, + $RootScopeProvider, + $QProvider, + $$SanitizeUriProvider, + $SceProvider, + $SceDelegateProvider, + $SnifferProvider, + $TemplateCacheProvider, + $TimeoutProvider, + $$RAFProvider, + $$AsyncCallbackProvider, + $WindowProvider +*/ + + +/** + * @ngdoc object + * @name angular.version + * @module ng + * @description + * An object that contains information about the current AngularJS version. This object has the + * following properties: + * + * - `full` – `{string}` – Full version string, such as "0.9.18". + * - `major` – `{number}` – Major version number, such as "0". + * - `minor` – `{number}` – Minor version number, such as "9". + * - `dot` – `{number}` – Dot version number, such as "18". + * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". + */ +var version = { + full: '1.2.28', // all of these placeholder strings will be replaced by grunt's + major: 1, // package task + minor: 2, + dot: 28, + codeName: 'finnish-disembarkation' +}; + + +function publishExternalAPI(angular){ + extend(angular, { + 'bootstrap': bootstrap, + 'copy': copy, + 'extend': extend, + 'equals': equals, + 'element': jqLite, + 'forEach': forEach, + 'injector': createInjector, + 'noop': noop, + 'bind': bind, + 'toJson': toJson, + 'fromJson': fromJson, + 'identity': identity, + 'isUndefined': isUndefined, + 'isDefined': isDefined, + 'isString': isString, + 'isFunction': isFunction, + 'isObject': isObject, + 'isNumber': isNumber, + 'isElement': isElement, + 'isArray': isArray, + 'version': version, + 'isDate': isDate, + 'lowercase': lowercase, + 'uppercase': uppercase, + 'callbacks': {counter: 0}, + '$$minErr': minErr, + '$$csp': csp + }); + + angularModule = setupModuleLoader(window); + try { + angularModule('ngLocale'); + } catch (e) { + angularModule('ngLocale', []).provider('$locale', $LocaleProvider); + } + + angularModule('ng', ['ngLocale'], ['$provide', + function ngModule($provide) { + // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. + $provide.provider({ + $$sanitizeUri: $$SanitizeUriProvider + }); + $provide.provider('$compile', $CompileProvider). + directive({ + a: htmlAnchorDirective, + input: inputDirective, + textarea: inputDirective, + form: formDirective, + script: scriptDirective, + select: selectDirective, + style: styleDirective, + option: optionDirective, + ngBind: ngBindDirective, + ngBindHtml: ngBindHtmlDirective, + ngBindTemplate: ngBindTemplateDirective, + ngClass: ngClassDirective, + ngClassEven: ngClassEvenDirective, + ngClassOdd: ngClassOddDirective, + ngCloak: ngCloakDirective, + ngController: ngControllerDirective, + ngForm: ngFormDirective, + ngHide: ngHideDirective, + ngIf: ngIfDirective, + ngInclude: ngIncludeDirective, + ngInit: ngInitDirective, + ngNonBindable: ngNonBindableDirective, + ngPluralize: ngPluralizeDirective, + ngRepeat: ngRepeatDirective, + ngShow: ngShowDirective, + ngStyle: ngStyleDirective, + ngSwitch: ngSwitchDirective, + ngSwitchWhen: ngSwitchWhenDirective, + ngSwitchDefault: ngSwitchDefaultDirective, + ngOptions: ngOptionsDirective, + ngTransclude: ngTranscludeDirective, + ngModel: ngModelDirective, + ngList: ngListDirective, + ngChange: ngChangeDirective, + required: requiredDirective, + ngRequired: requiredDirective, + ngValue: ngValueDirective + }). + directive({ + ngInclude: ngIncludeFillContentDirective + }). + directive(ngAttributeAliasDirectives). + directive(ngEventDirectives); + $provide.provider({ + $anchorScroll: $AnchorScrollProvider, + $animate: $AnimateProvider, + $browser: $BrowserProvider, + $cacheFactory: $CacheFactoryProvider, + $controller: $ControllerProvider, + $document: $DocumentProvider, + $exceptionHandler: $ExceptionHandlerProvider, + $filter: $FilterProvider, + $interpolate: $InterpolateProvider, + $interval: $IntervalProvider, + $http: $HttpProvider, + $httpBackend: $HttpBackendProvider, + $location: $LocationProvider, + $log: $LogProvider, + $parse: $ParseProvider, + $rootScope: $RootScopeProvider, + $q: $QProvider, + $sce: $SceProvider, + $sceDelegate: $SceDelegateProvider, + $sniffer: $SnifferProvider, + $templateCache: $TemplateCacheProvider, + $timeout: $TimeoutProvider, + $window: $WindowProvider, + $$rAF: $$RAFProvider, + $$asyncCallback : $$AsyncCallbackProvider + }); + } + ]); +} + +/* global JQLitePrototype: true, + addEventListenerFn: true, + removeEventListenerFn: true, + BOOLEAN_ATTR: true +*/ + +////////////////////////////////// +//JQLite +////////////////////////////////// + +/** + * @ngdoc function + * @name angular.element + * @module ng + * @kind function + * + * @description + * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. + * + * If jQuery is available, `angular.element` is an alias for the + * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` + * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + * + *
jqLite is a tiny, API-compatible subset of jQuery that allows + * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most + * commonly needed functionality with the goal of having a very small footprint.
+ * + * To use jQuery, simply load it before `DOMContentLoaded` event fired. + * + *
**Note:** all element references in Angular are always wrapped with jQuery or + * jqLite; they are never raw DOM references.
+ * + * ## Angular's jqLite + * jqLite provides only the following jQuery methods: + * + * - [`addClass()`](http://api.jquery.com/addClass/) + * - [`after()`](http://api.jquery.com/after/) + * - [`append()`](http://api.jquery.com/append/) + * - [`attr()`](http://api.jquery.com/attr/) + * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData + * - [`children()`](http://api.jquery.com/children/) - Does not support selectors + * - [`clone()`](http://api.jquery.com/clone/) + * - [`contents()`](http://api.jquery.com/contents/) + * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyles()` + * - [`data()`](http://api.jquery.com/data/) + * - [`empty()`](http://api.jquery.com/empty/) + * - [`eq()`](http://api.jquery.com/eq/) + * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name + * - [`hasClass()`](http://api.jquery.com/hasClass/) + * - [`html()`](http://api.jquery.com/html/) + * - [`next()`](http://api.jquery.com/next/) - Does not support selectors + * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData + * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors + * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors + * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors + * - [`prepend()`](http://api.jquery.com/prepend/) + * - [`prop()`](http://api.jquery.com/prop/) + * - [`ready()`](http://api.jquery.com/ready/) + * - [`remove()`](http://api.jquery.com/remove/) + * - [`removeAttr()`](http://api.jquery.com/removeAttr/) + * - [`removeClass()`](http://api.jquery.com/removeClass/) + * - [`removeData()`](http://api.jquery.com/removeData/) + * - [`replaceWith()`](http://api.jquery.com/replaceWith/) + * - [`text()`](http://api.jquery.com/text/) + * - [`toggleClass()`](http://api.jquery.com/toggleClass/) + * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. + * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces + * - [`val()`](http://api.jquery.com/val/) + * - [`wrap()`](http://api.jquery.com/wrap/) + * + * ## jQuery/jqLite Extras + * Angular also provides the following additional methods and events to both jQuery and jqLite: + * + * ### Events + * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event + * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM + * element before it is removed. + * + * ### Methods + * - `controller(name)` - retrieves the controller of the current element or its parent. By default + * retrieves controller associated with the `ngController` directive. If `name` is provided as + * camelCase directive name, then the controller for this directive will be retrieved (e.g. + * `'ngModel'`). + * - `injector()` - retrieves the injector of the current element or its parent. + * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current + * element or its parent. + * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the + * current element. This getter should be used only on elements that contain a directive which starts a new isolate + * scope. Calling `scope()` on this element always returns the original non-isolate scope. + * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top + * parent element is reached. + * + * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. + * @returns {Object} jQuery object. + */ + +JQLite.expando = 'ng339'; + +var jqCache = JQLite.cache = {}, + jqId = 1, + addEventListenerFn = (window.document.addEventListener + ? function(element, type, fn) {element.addEventListener(type, fn, false);} + : function(element, type, fn) {element.attachEvent('on' + type, fn);}), + removeEventListenerFn = (window.document.removeEventListener + ? function(element, type, fn) {element.removeEventListener(type, fn, false); } + : function(element, type, fn) {element.detachEvent('on' + type, fn); }); + +/* + * !!! This is an undocumented "private" function !!! + */ +var jqData = JQLite._data = function(node) { + //jQuery always returns an object on cache miss + return this.cache[node[this.expando]] || {}; +}; + +function jqNextId() { return ++jqId; } + + +var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; +var MOZ_HACK_REGEXP = /^moz([A-Z])/; +var jqLiteMinErr = minErr('jqLite'); + +/** + * Converts snake_case to camelCase. + * Also there is special case for Moz prefix starting with upper case letter. + * @param name Name to normalize + */ +function camelCase(name) { + return name. + replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { + return offset ? letter.toUpperCase() : letter; + }). + replace(MOZ_HACK_REGEXP, 'Moz$1'); +} + +///////////////////////////////////////////// +// jQuery mutation patch +// +// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a +// $destroy event on all DOM nodes being removed. +// +///////////////////////////////////////////// + +function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) { + var originalJqFn = jQuery.fn[name]; + originalJqFn = originalJqFn.$original || originalJqFn; + removePatch.$original = originalJqFn; + jQuery.fn[name] = removePatch; + + function removePatch(param) { + // jshint -W040 + var list = filterElems && param ? [this.filter(param)] : [this], + fireEvent = dispatchThis, + set, setIndex, setLength, + element, childIndex, childLength, children; + + if (!getterIfNoArguments || param != null) { + while(list.length) { + set = list.shift(); + for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { + element = jqLite(set[setIndex]); + if (fireEvent) { + element.triggerHandler('$destroy'); + } else { + fireEvent = !fireEvent; + } + for(childIndex = 0, childLength = (children = element.children()).length; + childIndex < childLength; + childIndex++) { + list.push(jQuery(children[childIndex])); + } + } + } + } + return originalJqFn.apply(this, arguments); + } +} + +var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; +var HTML_REGEXP = /<|&#?\w+;/; +var TAG_NAME_REGEXP = /<([\w:]+)/; +var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; + +var wrapMap = { + 'option': [1, ''], + + 'thead': [1, '', '
'], + 'col': [2, '', '
'], + 'tr': [2, '', '
'], + 'td': [3, '', '
'], + '_default': [0, "", ""] +}; + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function jqLiteIsTextNode(html) { + return !HTML_REGEXP.test(html); +} + +function jqLiteBuildFragment(html, context) { + var elem, tmp, tag, wrap, + fragment = context.createDocumentFragment(), + nodes = [], i, j, jj; + + if (jqLiteIsTextNode(html)) { + // Convert non-html into a text node + nodes.push(context.createTextNode(html)); + } else { + tmp = fragment.appendChild(context.createElement('div')); + // Convert html into DOM nodes + tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); + wrap = wrapMap[tag] || wrapMap._default; + tmp.innerHTML = '
 
' + + wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1>") + wrap[2]; + tmp.removeChild(tmp.firstChild); + + // Descend through wrappers to the right content + i = wrap[0]; + while (i--) { + tmp = tmp.lastChild; + } + + for (j=0, jj=tmp.childNodes.length; j -1); +} + +function jqLiteRemoveClass(element, cssClasses) { + if (cssClasses && element.setAttribute) { + forEach(cssClasses.split(' '), function(cssClass) { + element.setAttribute('class', trim( + (" " + (element.getAttribute('class') || '') + " ") + .replace(/[\n\t]/g, " ") + .replace(" " + trim(cssClass) + " ", " ")) + ); + }); + } +} + +function jqLiteAddClass(element, cssClasses) { + if (cssClasses && element.setAttribute) { + var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') + .replace(/[\n\t]/g, " "); + + forEach(cssClasses.split(' '), function(cssClass) { + cssClass = trim(cssClass); + if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { + existingClasses += cssClass + ' '; + } + }); + + element.setAttribute('class', trim(existingClasses)); + } +} + +function jqLiteAddNodes(root, elements) { + if (elements) { + elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) + ? elements + : [ elements ]; + for(var i=0; i < elements.length; i++) { + root.push(elements[i]); + } + } +} + +function jqLiteController(element, name) { + return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); +} + +function jqLiteInheritedData(element, name, value) { + // if element is the document object work with the html element instead + // this makes $(document).scope() possible + if(element.nodeType == 9) { + element = element.documentElement; + } + var names = isArray(name) ? name : [name]; + + while (element) { + for (var i = 0, ii = names.length; i < ii; i++) { + if ((value = jqLite.data(element, names[i])) !== undefined) return value; + } + + // If dealing with a document fragment node with a host element, and no parent, use the host + // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM + // to lookup parent controllers. + element = element.parentNode || (element.nodeType === 11 && element.host); + } +} + +function jqLiteEmpty(element) { + for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { + jqLiteDealoc(childNodes[i]); + } + while (element.firstChild) { + element.removeChild(element.firstChild); + } +} + +////////////////////////////////////////// +// Functions which are declared directly. +////////////////////////////////////////// +var JQLitePrototype = JQLite.prototype = { + ready: function(fn) { + var fired = false; + + function trigger() { + if (fired) return; + fired = true; + fn(); + } + + // check if document already is loaded + if (document.readyState === 'complete'){ + setTimeout(trigger); + } else { + this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 + // we can not use jqLite since we are not done loading and jQuery could be loaded later. + // jshint -W064 + JQLite(window).on('load', trigger); // fallback to window.onload for others + // jshint +W064 + } + }, + toString: function() { + var value = []; + forEach(this, function(e){ value.push('' + e);}); + return '[' + value.join(', ') + ']'; + }, + + eq: function(index) { + return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); + }, + + length: 0, + push: push, + sort: [].sort, + splice: [].splice +}; + +////////////////////////////////////////// +// Functions iterating getter/setters. +// these functions return self on setter and +// value on get. +////////////////////////////////////////// +var BOOLEAN_ATTR = {}; +forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { + BOOLEAN_ATTR[lowercase(value)] = value; +}); +var BOOLEAN_ELEMENTS = {}; +forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { + BOOLEAN_ELEMENTS[uppercase(value)] = true; +}); + +function getBooleanAttrName(element, name) { + // check dom last since we will most likely fail on name + var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; + + // booleanAttr is here twice to minimize DOM access + return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; +} + +forEach({ + data: jqLiteData, + removeData: jqLiteRemoveData +}, function(fn, name) { + JQLite[name] = fn; +}); + +forEach({ + data: jqLiteData, + inheritedData: jqLiteInheritedData, + + scope: function(element) { + // Can't use jqLiteData here directly so we stay compatible with jQuery! + return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); + }, + + isolateScope: function(element) { + // Can't use jqLiteData here directly so we stay compatible with jQuery! + return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); + }, + + controller: jqLiteController, + + injector: function(element) { + return jqLiteInheritedData(element, '$injector'); + }, + + removeAttr: function(element,name) { + element.removeAttribute(name); + }, + + hasClass: jqLiteHasClass, + + css: function(element, name, value) { + name = camelCase(name); + + if (isDefined(value)) { + element.style[name] = value; + } else { + var val; + + if (msie <= 8) { + // this is some IE specific weirdness that jQuery 1.6.4 does not sure why + val = element.currentStyle && element.currentStyle[name]; + if (val === '') val = 'auto'; + } + + val = val || element.style[name]; + + if (msie <= 8) { + // jquery weirdness :-/ + val = (val === '') ? undefined : val; + } + + return val; + } + }, + + attr: function(element, name, value){ + var lowercasedName = lowercase(name); + if (BOOLEAN_ATTR[lowercasedName]) { + if (isDefined(value)) { + if (!!value) { + element[name] = true; + element.setAttribute(name, lowercasedName); + } else { + element[name] = false; + element.removeAttribute(lowercasedName); + } + } else { + return (element[name] || + (element.attributes.getNamedItem(name)|| noop).specified) + ? lowercasedName + : undefined; + } + } else if (isDefined(value)) { + element.setAttribute(name, value); + } else if (element.getAttribute) { + // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code + // some elements (e.g. Document) don't have get attribute, so return undefined + var ret = element.getAttribute(name, 2); + // normalize non-existing attributes to undefined (as jQuery) + return ret === null ? undefined : ret; + } + }, + + prop: function(element, name, value) { + if (isDefined(value)) { + element[name] = value; + } else { + return element[name]; + } + }, + + text: (function() { + var NODE_TYPE_TEXT_PROPERTY = []; + if (msie < 9) { + NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ + NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ + } else { + NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ + NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ + } + getText.$dv = ''; + return getText; + + function getText(element, value) { + var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType]; + if (isUndefined(value)) { + return textProp ? element[textProp] : ''; + } + element[textProp] = value; + } + })(), + + val: function(element, value) { + if (isUndefined(value)) { + if (nodeName_(element) === 'SELECT' && element.multiple) { + var result = []; + forEach(element.options, function (option) { + if (option.selected) { + result.push(option.value || option.text); + } + }); + return result.length === 0 ? null : result; + } + return element.value; + } + element.value = value; + }, + + html: function(element, value) { + if (isUndefined(value)) { + return element.innerHTML; + } + for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { + jqLiteDealoc(childNodes[i]); + } + element.innerHTML = value; + }, + + empty: jqLiteEmpty +}, function(fn, name){ + /** + * Properties: writes return selection, reads return first value + */ + JQLite.prototype[name] = function(arg1, arg2) { + var i, key; + var nodeCount = this.length; + + // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it + // in a way that survives minification. + // jqLiteEmpty takes no arguments but is a setter. + if (fn !== jqLiteEmpty && + (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { + if (isObject(arg1)) { + + // we are a write, but the object properties are the key/values + for (i = 0; i < nodeCount; i++) { + if (fn === jqLiteData) { + // data() takes the whole object in jQuery + fn(this[i], arg1); + } else { + for (key in arg1) { + fn(this[i], key, arg1[key]); + } + } + } + // return self for chaining + return this; + } else { + // we are a read, so read the first child. + // TODO: do we still need this? + var value = fn.$dv; + // Only if we have $dv do we iterate over all, otherwise it is just the first element. + var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount; + for (var j = 0; j < jj; j++) { + var nodeValue = fn(this[j], arg1, arg2); + value = value ? value + nodeValue : nodeValue; + } + return value; + } + } else { + // we are a write, so apply to all children + for (i = 0; i < nodeCount; i++) { + fn(this[i], arg1, arg2); + } + // return self for chaining + return this; + } + }; +}); + +function createEventHandler(element, events) { + var eventHandler = function (event, type) { + if (!event.preventDefault) { + event.preventDefault = function() { + event.returnValue = false; //ie + }; + } + + if (!event.stopPropagation) { + event.stopPropagation = function() { + event.cancelBubble = true; //ie + }; + } + + if (!event.target) { + event.target = event.srcElement || document; + } + + if (isUndefined(event.defaultPrevented)) { + var prevent = event.preventDefault; + event.preventDefault = function() { + event.defaultPrevented = true; + prevent.call(event); + }; + event.defaultPrevented = false; + } + + event.isDefaultPrevented = function() { + return event.defaultPrevented || event.returnValue === false; + }; + + // Copy event handlers in case event handlers array is modified during execution. + var eventHandlersCopy = shallowCopy(events[type || event.type] || []); + + forEach(eventHandlersCopy, function(fn) { + fn.call(element, event); + }); + + // Remove monkey-patched methods (IE), + // as they would cause memory leaks in IE8. + if (msie <= 8) { + // IE7/8 does not allow to delete property on native object + event.preventDefault = null; + event.stopPropagation = null; + event.isDefaultPrevented = null; + } else { + // It shouldn't affect normal browsers (native methods are defined on prototype). + delete event.preventDefault; + delete event.stopPropagation; + delete event.isDefaultPrevented; + } + }; + eventHandler.elem = element; + return eventHandler; +} + +////////////////////////////////////////// +// Functions iterating traversal. +// These functions chain results into a single +// selector. +////////////////////////////////////////// +forEach({ + removeData: jqLiteRemoveData, + + dealoc: jqLiteDealoc, + + on: function onFn(element, type, fn, unsupported){ + if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); + + var events = jqLiteExpandoStore(element, 'events'), + handle = jqLiteExpandoStore(element, 'handle'); + + if (!events) jqLiteExpandoStore(element, 'events', events = {}); + if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); + + forEach(type.split(' '), function(type){ + var eventFns = events[type]; + + if (!eventFns) { + if (type == 'mouseenter' || type == 'mouseleave') { + var contains = document.body.contains || document.body.compareDocumentPosition ? + function( a, b ) { + // jshint bitwise: false + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + events[type] = []; + + // Refer to jQuery's implementation of mouseenter & mouseleave + // Read about mouseenter and mouseleave: + // http://www.quirksmode.org/js/events_mouse.html#link8 + var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; + + onFn(element, eventmap[type], function(event) { + var target = this, related = event.relatedTarget; + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !contains(target, related)) ){ + handle(event, type); + } + }); + + } else { + addEventListenerFn(element, type, handle); + events[type] = []; + } + eventFns = events[type]; + } + eventFns.push(fn); + }); + }, + + off: jqLiteOff, + + one: function(element, type, fn) { + element = jqLite(element); + + //add the listener twice so that when it is called + //you can remove the original function and still be + //able to call element.off(ev, fn) normally + element.on(type, function onFn() { + element.off(type, fn); + element.off(type, onFn); + }); + element.on(type, fn); + }, + + replaceWith: function(element, replaceNode) { + var index, parent = element.parentNode; + jqLiteDealoc(element); + forEach(new JQLite(replaceNode), function(node){ + if (index) { + parent.insertBefore(node, index.nextSibling); + } else { + parent.replaceChild(node, element); + } + index = node; + }); + }, + + children: function(element) { + var children = []; + forEach(element.childNodes, function(element){ + if (element.nodeType === 1) + children.push(element); + }); + return children; + }, + + contents: function(element) { + return element.contentDocument || element.childNodes || []; + }, + + append: function(element, node) { + forEach(new JQLite(node), function(child){ + if (element.nodeType === 1 || element.nodeType === 11) { + element.appendChild(child); + } + }); + }, + + prepend: function(element, node) { + if (element.nodeType === 1) { + var index = element.firstChild; + forEach(new JQLite(node), function(child){ + element.insertBefore(child, index); + }); + } + }, + + wrap: function(element, wrapNode) { + wrapNode = jqLite(wrapNode)[0]; + var parent = element.parentNode; + if (parent) { + parent.replaceChild(wrapNode, element); + } + wrapNode.appendChild(element); + }, + + remove: function(element) { + jqLiteDealoc(element); + var parent = element.parentNode; + if (parent) parent.removeChild(element); + }, + + after: function(element, newElement) { + var index = element, parent = element.parentNode; + forEach(new JQLite(newElement), function(node){ + parent.insertBefore(node, index.nextSibling); + index = node; + }); + }, + + addClass: jqLiteAddClass, + removeClass: jqLiteRemoveClass, + + toggleClass: function(element, selector, condition) { + if (selector) { + forEach(selector.split(' '), function(className){ + var classCondition = condition; + if (isUndefined(classCondition)) { + classCondition = !jqLiteHasClass(element, className); + } + (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); + }); + } + }, + + parent: function(element) { + var parent = element.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + + next: function(element) { + if (element.nextElementSibling) { + return element.nextElementSibling; + } + + // IE8 doesn't have nextElementSibling + var elm = element.nextSibling; + while (elm != null && elm.nodeType !== 1) { + elm = elm.nextSibling; + } + return elm; + }, + + find: function(element, selector) { + if (element.getElementsByTagName) { + return element.getElementsByTagName(selector); + } else { + return []; + } + }, + + clone: jqLiteClone, + + triggerHandler: function(element, event, extraParameters) { + + var dummyEvent, eventFnsCopy, handlerArgs; + var eventName = event.type || event; + var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName]; + + if (eventFns) { + + // Create a dummy event to pass to the handlers + dummyEvent = { + preventDefault: function() { this.defaultPrevented = true; }, + isDefaultPrevented: function() { return this.defaultPrevented === true; }, + stopPropagation: noop, + type: eventName, + target: element + }; + + // If a custom event was provided then extend our dummy event with it + if (event.type) { + dummyEvent = extend(dummyEvent, event); + } + + // Copy event handlers in case event handlers array is modified during execution. + eventFnsCopy = shallowCopy(eventFns); + handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; + + forEach(eventFnsCopy, function(fn) { + fn.apply(element, handlerArgs); + }); + + } + } +}, function(fn, name){ + /** + * chaining functions + */ + JQLite.prototype[name] = function(arg1, arg2, arg3) { + var value; + for(var i=0; i < this.length; i++) { + if (isUndefined(value)) { + value = fn(this[i], arg1, arg2, arg3); + if (isDefined(value)) { + // any function which returns a value needs to be wrapped + value = jqLite(value); + } + } else { + jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); + } + } + return isDefined(value) ? value : this; + }; + + // bind legacy bind/unbind to on/off + JQLite.prototype.bind = JQLite.prototype.on; + JQLite.prototype.unbind = JQLite.prototype.off; +}); + +/** + * Computes a hash of an 'obj'. + * Hash of a: + * string is string + * number is number as string + * object is either result of calling $$hashKey function on the object or uniquely generated id, + * that is also assigned to the $$hashKey property of the object. + * + * @param obj + * @returns {string} hash string such that the same input will have the same hash string. + * The resulting string key is in 'type:hashKey' format. + */ +function hashKey(obj, nextUidFn) { + var objType = typeof obj, + key; + + if (objType == 'function' || (objType == 'object' && obj !== null)) { + if (typeof (key = obj.$$hashKey) == 'function') { + // must invoke on object to keep the right this + key = obj.$$hashKey(); + } else if (key === undefined) { + key = obj.$$hashKey = (nextUidFn || nextUid)(); + } + } else { + key = obj; + } + + return objType + ':' + key; +} + +/** + * HashMap which can use objects as keys + */ +function HashMap(array, isolatedUid) { + if (isolatedUid) { + var uid = 0; + this.nextUid = function() { + return ++uid; + }; + } + forEach(array, this.put, this); +} +HashMap.prototype = { + /** + * Store key value pair + * @param key key to store can be any type + * @param value value to store can be any type + */ + put: function(key, value) { + this[hashKey(key, this.nextUid)] = value; + }, + + /** + * @param key + * @returns {Object} the value for the key + */ + get: function(key) { + return this[hashKey(key, this.nextUid)]; + }, + + /** + * Remove the key/value pair + * @param key + */ + remove: function(key) { + var value = this[key = hashKey(key, this.nextUid)]; + delete this[key]; + return value; + } +}; + +/** + * @ngdoc function + * @module ng + * @name angular.injector + * @kind function + * + * @description + * Creates an injector object that can be used for retrieving services as well as for + * dependency injection (see {@link guide/di dependency injection}). + * + + * @param {Array.} modules A list of module functions or their aliases. See + * {@link angular.module}. The `ng` module must be explicitly added. + * @returns {injector} Injector object. See {@link auto.$injector $injector}. + * + * @example + * Typical usage + * ```js + * // create an injector + * var $injector = angular.injector(['ng']); + * + * // use the injector to kick off your application + * // use the type inference to auto inject arguments, or use implicit injection + * $injector.invoke(function($rootScope, $compile, $document){ + * $compile($document)($rootScope); + * $rootScope.$digest(); + * }); + * ``` + * + * Sometimes you want to get access to the injector of a currently running Angular app + * from outside Angular. Perhaps, you want to inject and compile some markup after the + * application has been bootstrapped. You can do this using the extra `injector()` added + * to JQuery/jqLite elements. See {@link angular.element}. + * + * *This is fairly rare but could be the case if a third party library is injecting the + * markup.* + * + * In the following example a new block of HTML containing a `ng-controller` + * directive is added to the end of the document body by JQuery. We then compile and link + * it into the current AngularJS scope. + * + * ```js + * var $div = $('
{{content.label}}
'); + * $(document.body).append($div); + * + * angular.element(document).injector().invoke(function($compile) { + * var scope = angular.element($div).scope(); + * $compile($div)(scope); + * }); + * ``` + */ + + +/** + * @ngdoc module + * @name auto + * @description + * + * Implicit module which gets automatically added to each {@link auto.$injector $injector}. + */ + +var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; +var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; +var $injectorMinErr = minErr('$injector'); +function annotate(fn) { + var $inject, + fnText, + argDecl, + last; + + if (typeof fn === 'function') { + if (!($inject = fn.$inject)) { + $inject = []; + if (fn.length) { + fnText = fn.toString().replace(STRIP_COMMENTS, ''); + argDecl = fnText.match(FN_ARGS); + forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ + arg.replace(FN_ARG, function(all, underscore, name){ + $inject.push(name); + }); + }); + } + fn.$inject = $inject; + } + } else if (isArray(fn)) { + last = fn.length - 1; + assertArgFn(fn[last], 'fn'); + $inject = fn.slice(0, last); + } else { + assertArgFn(fn, 'fn', true); + } + return $inject; +} + +/////////////////////////////////////// + +/** + * @ngdoc service + * @name $injector + * + * @description + * + * `$injector` is used to retrieve object instances as defined by + * {@link auto.$provide provider}, instantiate types, invoke methods, + * and load modules. + * + * The following always holds true: + * + * ```js + * var $injector = angular.injector(); + * expect($injector.get('$injector')).toBe($injector); + * expect($injector.invoke(function($injector){ + * return $injector; + * })).toBe($injector); + * ``` + * + * # Injection Function Annotation + * + * JavaScript does not have annotations, and annotations are needed for dependency injection. The + * following are all valid ways of annotating function with injection arguments and are equivalent. + * + * ```js + * // inferred (only works if code not minified/obfuscated) + * $injector.invoke(function(serviceA){}); + * + * // annotated + * function explicit(serviceA) {}; + * explicit.$inject = ['serviceA']; + * $injector.invoke(explicit); + * + * // inline + * $injector.invoke(['serviceA', function(serviceA){}]); + * ``` + * + * ## Inference + * + * In JavaScript calling `toString()` on a function returns the function definition. The definition + * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with + * minification, and obfuscation tools since these tools change the argument names. + * + * ## `$inject` Annotation + * By adding an `$inject` property onto a function the injection parameters can be specified. + * + * ## Inline + * As an array of injection names, where the last item in the array is the function to call. + */ + +/** + * @ngdoc method + * @name $injector#get + * + * @description + * Return an instance of the service. + * + * @param {string} name The name of the instance to retrieve. + * @return {*} The instance. + */ + +/** + * @ngdoc method + * @name $injector#invoke + * + * @description + * Invoke the method and supply the method arguments from the `$injector`. + * + * @param {!Function} fn The function to invoke. Function parameters are injected according to the + * {@link guide/di $inject Annotation} rules. + * @param {Object=} self The `this` for the invoked method. + * @param {Object=} locals Optional object. If preset then any argument names are read from this + * object first, before the `$injector` is consulted. + * @returns {*} the value returned by the invoked `fn` function. + */ + +/** + * @ngdoc method + * @name $injector#has + * + * @description + * Allows the user to query if the particular service exists. + * + * @param {string} name Name of the service to query. + * @returns {boolean} `true` if injector has given service. + */ + +/** + * @ngdoc method + * @name $injector#instantiate + * @description + * Create a new instance of JS type. The method takes a constructor function, invokes the new + * operator, and supplies all of the arguments to the constructor function as specified by the + * constructor annotation. + * + * @param {Function} Type Annotated constructor function. + * @param {Object=} locals Optional object. If preset then any argument names are read from this + * object first, before the `$injector` is consulted. + * @returns {Object} new instance of `Type`. + */ + +/** + * @ngdoc method + * @name $injector#annotate + * + * @description + * Returns an array of service names which the function is requesting for injection. This API is + * used by the injector to determine which services need to be injected into the function when the + * function is invoked. There are three ways in which the function can be annotated with the needed + * dependencies. + * + * # Argument names + * + * The simplest form is to extract the dependencies from the arguments of the function. This is done + * by converting the function into a string using `toString()` method and extracting the argument + * names. + * ```js + * // Given + * function MyController($scope, $route) { + * // ... + * } + * + * // Then + * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); + * ``` + * + * This method does not work with code minification / obfuscation. For this reason the following + * annotation strategies are supported. + * + * # The `$inject` property + * + * If a function has an `$inject` property and its value is an array of strings, then the strings + * represent names of services to be injected into the function. + * ```js + * // Given + * var MyController = function(obfuscatedScope, obfuscatedRoute) { + * // ... + * } + * // Define function dependencies + * MyController['$inject'] = ['$scope', '$route']; + * + * // Then + * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); + * ``` + * + * # The array notation + * + * It is often desirable to inline Injected functions and that's when setting the `$inject` property + * is very inconvenient. In these situations using the array notation to specify the dependencies in + * a way that survives minification is a better choice: + * + * ```js + * // We wish to write this (not minification / obfuscation safe) + * injector.invoke(function($compile, $rootScope) { + * // ... + * }); + * + * // We are forced to write break inlining + * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { + * // ... + * }; + * tmpFn.$inject = ['$compile', '$rootScope']; + * injector.invoke(tmpFn); + * + * // To better support inline function the inline annotation is supported + * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { + * // ... + * }]); + * + * // Therefore + * expect(injector.annotate( + * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) + * ).toEqual(['$compile', '$rootScope']); + * ``` + * + * @param {Function|Array.} fn Function for which dependent service names need to + * be retrieved as described above. + * + * @returns {Array.} The names of the services which the function requires. + */ + + + + +/** + * @ngdoc service + * @name $provide + * + * @description + * + * The {@link auto.$provide $provide} service has a number of methods for registering components + * with the {@link auto.$injector $injector}. Many of these functions are also exposed on + * {@link angular.Module}. + * + * An Angular **service** is a singleton object created by a **service factory**. These **service + * factories** are functions which, in turn, are created by a **service provider**. + * The **service providers** are constructor functions. When instantiated they must contain a + * property called `$get`, which holds the **service factory** function. + * + * When you request a service, the {@link auto.$injector $injector} is responsible for finding the + * correct **service provider**, instantiating it and then calling its `$get` **service factory** + * function to get the instance of the **service**. + * + * Often services have no configuration options and there is no need to add methods to the service + * provider. The provider will be no more than a constructor function with a `$get` property. For + * these cases the {@link auto.$provide $provide} service has additional helper methods to register + * services without specifying a provider. + * + * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the + * {@link auto.$injector $injector} + * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by + * providers and services. + * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by + * services, not providers. + * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, + * that will be wrapped in a **service provider** object, whose `$get` property will contain the + * given factory function. + * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` + * that will be wrapped in a **service provider** object, whose `$get` property will instantiate + * a new object using the given constructor function. + * + * See the individual methods for more information and examples. + */ + +/** + * @ngdoc method + * @name $provide#provider + * @description + * + * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions + * are constructor functions, whose instances are responsible for "providing" a factory for a + * service. + * + * Service provider names start with the name of the service they provide followed by `Provider`. + * For example, the {@link ng.$log $log} service has a provider called + * {@link ng.$logProvider $logProvider}. + * + * Service provider objects can have additional methods which allow configuration of the provider + * and its service. Importantly, you can configure what kind of service is created by the `$get` + * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a + * method {@link ng.$logProvider#debugEnabled debugEnabled} + * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the + * console or not. + * + * @param {string} name The name of the instance. NOTE: the provider will be available under `name + + 'Provider'` key. + * @param {(Object|function())} provider If the provider is: + * + * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using + * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. + * - `Constructor`: a new instance of the provider will be created using + * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. + * + * @returns {Object} registered provider instance + + * @example + * + * The following example shows how to create a simple event tracking service and register it using + * {@link auto.$provide#provider $provide.provider()}. + * + * ```js + * // Define the eventTracker provider + * function EventTrackerProvider() { + * var trackingUrl = '/track'; + * + * // A provider method for configuring where the tracked events should been saved + * this.setTrackingUrl = function(url) { + * trackingUrl = url; + * }; + * + * // The service factory function + * this.$get = ['$http', function($http) { + * var trackedEvents = {}; + * return { + * // Call this to track an event + * event: function(event) { + * var count = trackedEvents[event] || 0; + * count += 1; + * trackedEvents[event] = count; + * return count; + * }, + * // Call this to save the tracked events to the trackingUrl + * save: function() { + * $http.post(trackingUrl, trackedEvents); + * } + * }; + * }]; + * } + * + * describe('eventTracker', function() { + * var postSpy; + * + * beforeEach(module(function($provide) { + * // Register the eventTracker provider + * $provide.provider('eventTracker', EventTrackerProvider); + * })); + * + * beforeEach(module(function(eventTrackerProvider) { + * // Configure eventTracker provider + * eventTrackerProvider.setTrackingUrl('/custom-track'); + * })); + * + * it('tracks events', inject(function(eventTracker) { + * expect(eventTracker.event('login')).toEqual(1); + * expect(eventTracker.event('login')).toEqual(2); + * })); + * + * it('saves to the tracking url', inject(function(eventTracker, $http) { + * postSpy = spyOn($http, 'post'); + * eventTracker.event('login'); + * eventTracker.save(); + * expect(postSpy).toHaveBeenCalled(); + * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); + * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); + * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); + * })); + * }); + * ``` + */ + +/** + * @ngdoc method + * @name $provide#factory + * @description + * + * Register a **service factory**, which will be called to return the service instance. + * This is short for registering a service where its provider consists of only a `$get` property, + * which is the given service factory function. + * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to + * configure your service in a provider. + * + * @param {string} name The name of the instance. + * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand + * for `$provide.provider(name, {$get: $getFn})`. + * @returns {Object} registered provider instance + * + * @example + * Here is an example of registering a service + * ```js + * $provide.factory('ping', ['$http', function($http) { + * return function ping() { + * return $http.send('/ping'); + * }; + * }]); + * ``` + * You would then inject and use this service like this: + * ```js + * someModule.controller('Ctrl', ['ping', function(ping) { + * ping(); + * }]); + * ``` + */ + + +/** + * @ngdoc method + * @name $provide#service + * @description + * + * Register a **service constructor**, which will be invoked with `new` to create the service + * instance. + * This is short for registering a service where its provider's `$get` property is the service + * constructor function that will be used to instantiate the service instance. + * + * You should use {@link auto.$provide#service $provide.service(class)} if you define your service + * as a type/class. + * + * @param {string} name The name of the instance. + * @param {Function} constructor A class (constructor function) that will be instantiated. + * @returns {Object} registered provider instance + * + * @example + * Here is an example of registering a service using + * {@link auto.$provide#service $provide.service(class)}. + * ```js + * var Ping = function($http) { + * this.$http = $http; + * }; + * + * Ping.$inject = ['$http']; + * + * Ping.prototype.send = function() { + * return this.$http.get('/ping'); + * }; + * $provide.service('ping', Ping); + * ``` + * You would then inject and use this service like this: + * ```js + * someModule.controller('Ctrl', ['ping', function(ping) { + * ping.send(); + * }]); + * ``` + */ + + +/** + * @ngdoc method + * @name $provide#value + * @description + * + * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a + * number, an array, an object or a function. This is short for registering a service where its + * provider's `$get` property is a factory function that takes no arguments and returns the **value + * service**. + * + * Value services are similar to constant services, except that they cannot be injected into a + * module configuration function (see {@link angular.Module#config}) but they can be overridden by + * an Angular + * {@link auto.$provide#decorator decorator}. + * + * @param {string} name The name of the instance. + * @param {*} value The value. + * @returns {Object} registered provider instance + * + * @example + * Here are some examples of creating value services. + * ```js + * $provide.value('ADMIN_USER', 'admin'); + * + * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); + * + * $provide.value('halfOf', function(value) { + * return value / 2; + * }); + * ``` + */ + + +/** + * @ngdoc method + * @name $provide#constant + * @description + * + * Register a **constant service**, such as a string, a number, an array, an object or a function, + * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be + * injected into a module configuration function (see {@link angular.Module#config}) and it cannot + * be overridden by an Angular {@link auto.$provide#decorator decorator}. + * + * @param {string} name The name of the constant. + * @param {*} value The constant value. + * @returns {Object} registered instance + * + * @example + * Here a some examples of creating constants: + * ```js + * $provide.constant('SHARD_HEIGHT', 306); + * + * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); + * + * $provide.constant('double', function(value) { + * return value * 2; + * }); + * ``` + */ + + +/** + * @ngdoc method + * @name $provide#decorator + * @description + * + * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator + * intercepts the creation of a service, allowing it to override or modify the behaviour of the + * service. The object returned by the decorator may be the original service, or a new service + * object which replaces or wraps and delegates to the original service. + * + * @param {string} name The name of the service to decorate. + * @param {function()} decorator This function will be invoked when the service needs to be + * instantiated and should return the decorated service instance. The function is called using + * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. + * Local injection arguments: + * + * * `$delegate` - The original service instance, which can be monkey patched, configured, + * decorated or delegated to. + * + * @example + * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting + * calls to {@link ng.$log#error $log.warn()}. + * ```js + * $provide.decorator('$log', ['$delegate', function($delegate) { + * $delegate.warn = $delegate.error; + * return $delegate; + * }]); + * ``` + */ + + +function createInjector(modulesToLoad) { + var INSTANTIATING = {}, + providerSuffix = 'Provider', + path = [], + loadedModules = new HashMap([], true), + providerCache = { + $provide: { + provider: supportObject(provider), + factory: supportObject(factory), + service: supportObject(service), + value: supportObject(value), + constant: supportObject(constant), + decorator: decorator + } + }, + providerInjector = (providerCache.$injector = + createInternalInjector(providerCache, function() { + throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); + })), + instanceCache = {}, + instanceInjector = (instanceCache.$injector = + createInternalInjector(instanceCache, function(servicename) { + var provider = providerInjector.get(servicename + providerSuffix); + return instanceInjector.invoke(provider.$get, provider); + })); + + + forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); + + return instanceInjector; + + //////////////////////////////////// + // $provider + //////////////////////////////////// + + function supportObject(delegate) { + return function(key, value) { + if (isObject(key)) { + forEach(key, reverseParams(delegate)); + } else { + return delegate(key, value); + } + }; + } + + function provider(name, provider_) { + assertNotHasOwnProperty(name, 'service'); + if (isFunction(provider_) || isArray(provider_)) { + provider_ = providerInjector.instantiate(provider_); + } + if (!provider_.$get) { + throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); + } + return providerCache[name + providerSuffix] = provider_; + } + + function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } + + function service(name, constructor) { + return factory(name, ['$injector', function($injector) { + return $injector.instantiate(constructor); + }]); + } + + function value(name, val) { return factory(name, valueFn(val)); } + + function constant(name, value) { + assertNotHasOwnProperty(name, 'constant'); + providerCache[name] = value; + instanceCache[name] = value; + } + + function decorator(serviceName, decorFn) { + var origProvider = providerInjector.get(serviceName + providerSuffix), + orig$get = origProvider.$get; + + origProvider.$get = function() { + var origInstance = instanceInjector.invoke(orig$get, origProvider); + return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); + }; + } + + //////////////////////////////////// + // Module Loading + //////////////////////////////////// + function loadModules(modulesToLoad){ + var runBlocks = [], moduleFn, invokeQueue, i, ii; + forEach(modulesToLoad, function(module) { + if (loadedModules.get(module)) return; + loadedModules.put(module, true); + + try { + if (isString(module)) { + moduleFn = angularModule(module); + runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); + + for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { + var invokeArgs = invokeQueue[i], + provider = providerInjector.get(invokeArgs[0]); + + provider[invokeArgs[1]].apply(provider, invokeArgs[2]); + } + } else if (isFunction(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else if (isArray(module)) { + runBlocks.push(providerInjector.invoke(module)); + } else { + assertArgFn(module, 'module'); + } + } catch (e) { + if (isArray(module)) { + module = module[module.length - 1]; + } + if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { + // Safari & FF's stack traces don't contain error.message content + // unlike those of Chrome and IE + // So if stack doesn't contain message, we create a new string that contains both. + // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. + /* jshint -W022 */ + e = e.message + '\n' + e.stack; + } + throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", + module, e.stack || e.message || e); + } + }); + return runBlocks; + } + + //////////////////////////////////// + // internal Injector + //////////////////////////////////// + + function createInternalInjector(cache, factory) { + + function getService(serviceName) { + if (cache.hasOwnProperty(serviceName)) { + if (cache[serviceName] === INSTANTIATING) { + throw $injectorMinErr('cdep', 'Circular dependency found: {0}', + serviceName + ' <- ' + path.join(' <- ')); + } + return cache[serviceName]; + } else { + try { + path.unshift(serviceName); + cache[serviceName] = INSTANTIATING; + return cache[serviceName] = factory(serviceName); + } catch (err) { + if (cache[serviceName] === INSTANTIATING) { + delete cache[serviceName]; + } + throw err; + } finally { + path.shift(); + } + } + } + + function invoke(fn, self, locals){ + var args = [], + $inject = annotate(fn), + length, i, + key; + + for(i = 0, length = $inject.length; i < length; i++) { + key = $inject[i]; + if (typeof key !== 'string') { + throw $injectorMinErr('itkn', + 'Incorrect injection token! Expected service name as string, got {0}', key); + } + args.push( + locals && locals.hasOwnProperty(key) + ? locals[key] + : getService(key) + ); + } + if (isArray(fn)) { + fn = fn[length]; + } + + // http://jsperf.com/angularjs-invoke-apply-vs-switch + // #5388 + return fn.apply(self, args); + } + + function instantiate(Type, locals) { + var Constructor = function() {}, + instance, returnedValue; + + // Check if Type is annotated and use just the given function at n-1 as parameter + // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); + Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; + instance = new Constructor(); + returnedValue = invoke(Type, instance, locals); + + return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; + } + + return { + invoke: invoke, + instantiate: instantiate, + get: getService, + annotate: annotate, + has: function(name) { + return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); + } + }; + } +} + +/** + * @ngdoc service + * @name $anchorScroll + * @kind function + * @requires $window + * @requires $location + * @requires $rootScope + * + * @description + * When called, it checks current value of `$location.hash()` and scrolls to the related element, + * according to rules specified in + * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). + * + * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor. + * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. + * + * @example + + +
+ Go to bottom + You're at the bottom! +
+
+ + function ScrollCtrl($scope, $location, $anchorScroll) { + $scope.gotoBottom = function (){ + // set the location.hash to the id of + // the element you wish to scroll to. + $location.hash('bottom'); + + // call $anchorScroll() + $anchorScroll(); + }; + } + + + #scrollArea { + height: 350px; + overflow: auto; + } + + #bottom { + display: block; + margin-top: 2000px; + } + +
+ */ +function $AnchorScrollProvider() { + + var autoScrollingEnabled = true; + + /** + * @ngdoc method + * @name $anchorScrollProvider#disableAutoScrolling + * + * @description + * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to + * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
+ * Use this method to disable automatic scrolling. + * + * If automatic scrolling is disabled, one must explicitly call + * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the + * current hash. + */ + this.disableAutoScrolling = function() { + autoScrollingEnabled = false; + }; + + this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { + var document = $window.document; + + // helper function to get first anchor from a NodeList + // can't use filter.filter, as it accepts only instances of Array + // and IE can't convert NodeList to an array using [].slice + // TODO(vojta): use filter if we change it to accept lists as well + function getFirstAnchor(list) { + var result = null; + forEach(list, function(element) { + if (!result && lowercase(element.nodeName) === 'a') result = element; + }); + return result; + } + + function scroll() { + var hash = $location.hash(), elm; + + // empty hash, scroll to the top of the page + if (!hash) $window.scrollTo(0, 0); + + // element with given id + else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); + + // first anchor with given name :-D + else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); + + // no element and hash == 'top', scroll to the top of the page + else if (hash === 'top') $window.scrollTo(0, 0); + } + + // does not scroll when user clicks on anchor link that is currently on + // (no url change, no $location.hash() change), browser native does scroll + if (autoScrollingEnabled) { + $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, + function autoScrollWatchAction() { + $rootScope.$evalAsync(scroll); + }); + } + + return scroll; + }]; +} + +var $animateMinErr = minErr('$animate'); + +/** + * @ngdoc provider + * @name $animateProvider + * + * @description + * Default implementation of $animate that doesn't perform any animations, instead just + * synchronously performs DOM + * updates and calls done() callbacks. + * + * In order to enable animations the ngAnimate module has to be loaded. + * + * To see the functional implementation check out src/ngAnimate/animate.js + */ +var $AnimateProvider = ['$provide', function($provide) { + + + this.$$selectors = {}; + + + /** + * @ngdoc method + * @name $animateProvider#register + * + * @description + * Registers a new injectable animation factory function. The factory function produces the + * animation object which contains callback functions for each event that is expected to be + * animated. + * + * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` + * must be called once the element animation is complete. If a function is returned then the + * animation service will use this function to cancel the animation whenever a cancel event is + * triggered. + * + * + * ```js + * return { + * eventFn : function(element, done) { + * //code to run the animation + * //once complete, then run done() + * return function cancellationFunction() { + * //code to cancel the animation + * } + * } + * } + * ``` + * + * @param {string} name The name of the animation. + * @param {Function} factory The factory function that will be executed to return the animation + * object. + */ + this.register = function(name, factory) { + var key = name + '-animation'; + if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', + "Expecting class selector starting with '.' got '{0}'.", name); + this.$$selectors[name.substr(1)] = key; + $provide.factory(key, factory); + }; + + /** + * @ngdoc method + * @name $animateProvider#classNameFilter + * + * @description + * Sets and/or returns the CSS class regular expression that is checked when performing + * an animation. Upon bootstrap the classNameFilter value is not set at all and will + * therefore enable $animate to attempt to perform an animation on any element. + * When setting the classNameFilter value, animations will only be performed on elements + * that successfully match the filter expression. This in turn can boost performance + * for low-powered devices as well as applications containing a lot of structural operations. + * @param {RegExp=} expression The className expression which will be checked against all animations + * @return {RegExp} The current CSS className expression value. If null then there is no expression value + */ + this.classNameFilter = function(expression) { + if(arguments.length === 1) { + this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; + } + return this.$$classNameFilter; + }; + + this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) { + + function async(fn) { + fn && $$asyncCallback(fn); + } + + /** + * + * @ngdoc service + * @name $animate + * @description The $animate service provides rudimentary DOM manipulation functions to + * insert, remove and move elements within the DOM, as well as adding and removing classes. + * This service is the core service used by the ngAnimate $animator service which provides + * high-level animation hooks for CSS and JavaScript. + * + * $animate is available in the AngularJS core, however, the ngAnimate module must be included + * to enable full out animation support. Otherwise, $animate will only perform simple DOM + * manipulation operations. + * + * To learn more about enabling animation support, click here to visit the {@link ngAnimate + * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service + * page}. + */ + return { + + /** + * + * @ngdoc method + * @name $animate#enter + * @kind function + * @description Inserts the element into the DOM either after the `after` element or within + * the `parent` element. Once complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will be inserted into the DOM + * @param {DOMElement} parent the parent element which will append the element as + * a child (if the after element is not present) + * @param {DOMElement} after the sibling element which will append the element + * after itself + * @param {Function=} done callback function that will be called after the element has been + * inserted into the DOM + */ + enter : function(element, parent, after, done) { + if (after) { + after.after(element); + } else { + if (!parent || !parent[0]) { + parent = after.parent(); + } + parent.append(element); + } + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#leave + * @kind function + * @description Removes the element from the DOM. Once complete, the done() callback will be + * fired (if provided). + * @param {DOMElement} element the element which will be removed from the DOM + * @param {Function=} done callback function that will be called after the element has been + * removed from the DOM + */ + leave : function(element, done) { + element.remove(); + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#move + * @kind function + * @description Moves the position of the provided element within the DOM to be placed + * either after the `after` element or inside of the `parent` element. Once complete, the + * done() callback will be fired (if provided). + * + * @param {DOMElement} element the element which will be moved around within the + * DOM + * @param {DOMElement} parent the parent element where the element will be + * inserted into (if the after element is not present) + * @param {DOMElement} after the sibling element where the element will be + * positioned next to + * @param {Function=} done the callback function (if provided) that will be fired after the + * element has been moved to its new position + */ + move : function(element, parent, after, done) { + // Do not remove element before insert. Removing will cause data associated with the + // element to be dropped. Insert will implicitly do the remove. + this.enter(element, parent, after, done); + }, + + /** + * + * @ngdoc method + * @name $animate#addClass + * @kind function + * @description Adds the provided className CSS class value to the provided element. Once + * complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will have the className value + * added to it + * @param {string} className the CSS class which will be added to the element + * @param {Function=} done the callback function (if provided) that will be fired after the + * className value has been added to the element + */ + addClass : function(element, className, done) { + className = isString(className) ? + className : + isArray(className) ? className.join(' ') : ''; + forEach(element, function (element) { + jqLiteAddClass(element, className); + }); + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#removeClass + * @kind function + * @description Removes the provided className CSS class value from the provided element. + * Once complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will have the className value + * removed from it + * @param {string} className the CSS class which will be removed from the element + * @param {Function=} done the callback function (if provided) that will be fired after the + * className value has been removed from the element + */ + removeClass : function(element, className, done) { + className = isString(className) ? + className : + isArray(className) ? className.join(' ') : ''; + forEach(element, function (element) { + jqLiteRemoveClass(element, className); + }); + async(done); + }, + + /** + * + * @ngdoc method + * @name $animate#setClass + * @kind function + * @description Adds and/or removes the given CSS classes to and from the element. + * Once complete, the done() callback will be fired (if provided). + * @param {DOMElement} element the element which will have its CSS classes changed + * removed from it + * @param {string} add the CSS classes which will be added to the element + * @param {string} remove the CSS class which will be removed from the element + * @param {Function=} done the callback function (if provided) that will be fired after the + * CSS classes have been set on the element + */ + setClass : function(element, add, remove, done) { + forEach(element, function (element) { + jqLiteAddClass(element, add); + jqLiteRemoveClass(element, remove); + }); + async(done); + }, + + enabled : noop + }; + }]; +}]; + +function $$AsyncCallbackProvider(){ + this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { + return $$rAF.supported + ? function(fn) { return $$rAF(fn); } + : function(fn) { + return $timeout(fn, 0, false); + }; + }]; +} + +/* global stripHash: true */ + +/** + * ! This is a private undocumented service ! + * + * @name $browser + * @requires $log + * @description + * This object has two goals: + * + * - hide all the global state in the browser caused by the window object + * - abstract away all the browser specific features and inconsistencies + * + * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` + * service, which can be used for convenient testing of the application without the interaction with + * the real browser apis. + */ +/** + * @param {object} window The global window object. + * @param {object} document jQuery wrapped document. + * @param {function()} XHR XMLHttpRequest constructor. + * @param {object} $log console.log or an object with the same interface. + * @param {object} $sniffer $sniffer service + */ +function Browser(window, document, $log, $sniffer) { + var self = this, + rawDocument = document[0], + location = window.location, + history = window.history, + setTimeout = window.setTimeout, + clearTimeout = window.clearTimeout, + pendingDeferIds = {}; + + self.isMock = false; + + var outstandingRequestCount = 0; + var outstandingRequestCallbacks = []; + + // TODO(vojta): remove this temporary api + self.$$completeOutstandingRequest = completeOutstandingRequest; + self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; + + /** + * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` + * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. + */ + function completeOutstandingRequest(fn) { + try { + fn.apply(null, sliceArgs(arguments, 1)); + } finally { + outstandingRequestCount--; + if (outstandingRequestCount === 0) { + while(outstandingRequestCallbacks.length) { + try { + outstandingRequestCallbacks.pop()(); + } catch (e) { + $log.error(e); + } + } + } + } + } + + /** + * @private + * Note: this method is used only by scenario runner + * TODO(vojta): prefix this method with $$ ? + * @param {function()} callback Function that will be called when no outstanding request + */ + self.notifyWhenNoOutstandingRequests = function(callback) { + // force browser to execute all pollFns - this is needed so that cookies and other pollers fire + // at some deterministic time in respect to the test runner's actions. Leaving things up to the + // regular poller would result in flaky tests. + forEach(pollFns, function(pollFn){ pollFn(); }); + + if (outstandingRequestCount === 0) { + callback(); + } else { + outstandingRequestCallbacks.push(callback); + } + }; + + ////////////////////////////////////////////////////////////// + // Poll Watcher API + ////////////////////////////////////////////////////////////// + var pollFns = [], + pollTimeout; + + /** + * @name $browser#addPollFn + * + * @param {function()} fn Poll function to add + * + * @description + * Adds a function to the list of functions that poller periodically executes, + * and starts polling if not started yet. + * + * @returns {function()} the added function + */ + self.addPollFn = function(fn) { + if (isUndefined(pollTimeout)) startPoller(100, setTimeout); + pollFns.push(fn); + return fn; + }; + + /** + * @param {number} interval How often should browser call poll functions (ms) + * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. + * + * @description + * Configures the poller to run in the specified intervals, using the specified + * setTimeout fn and kicks it off. + */ + function startPoller(interval, setTimeout) { + (function check() { + forEach(pollFns, function(pollFn){ pollFn(); }); + pollTimeout = setTimeout(check, interval); + })(); + } + + ////////////////////////////////////////////////////////////// + // URL API + ////////////////////////////////////////////////////////////// + + var lastBrowserUrl = location.href, + baseElement = document.find('base'), + reloadLocation = null; + + /** + * @name $browser#url + * + * @description + * GETTER: + * Without any argument, this method just returns current value of location.href. + * + * SETTER: + * With at least one argument, this method sets url to new value. + * If html5 history api supported, pushState/replaceState is used, otherwise + * location.href/location.replace is used. + * Returns its own instance to allow chaining + * + * NOTE: this api is intended for use only by the $location service. Please use the + * {@link ng.$location $location service} to change url. + * + * @param {string} url New url (when used as setter) + * @param {boolean=} replace Should new url replace current history record ? + */ + self.url = function(url, replace) { + // Android Browser BFCache causes location, history reference to become stale. + if (location !== window.location) location = window.location; + if (history !== window.history) history = window.history; + + // setter + if (url) { + if (lastBrowserUrl == url) return; + var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); + lastBrowserUrl = url; + // Don't use history API if only the hash changed + // due to a bug in IE10/IE11 which leads + // to not firing a `hashchange` nor `popstate` event + // in some cases (see #9143). + if (!sameBase && $sniffer.history) { + if (replace) history.replaceState(null, '', url); + else { + history.pushState(null, '', url); + // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 + baseElement.attr('href', baseElement.attr('href')); + } + } else { + if (!sameBase) { + reloadLocation = url; + } + if (replace) { + location.replace(url); + } else { + location.href = url; + } + } + return self; + // getter + } else { + // - reloadLocation is needed as browsers don't allow to read out + // the new location.href if a reload happened. + // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 + return reloadLocation || location.href.replace(/%27/g,"'"); + } + }; + + var urlChangeListeners = [], + urlChangeInit = false; + + function fireUrlChange() { + if (lastBrowserUrl == self.url()) return; + + lastBrowserUrl = self.url(); + forEach(urlChangeListeners, function(listener) { + listener(self.url()); + }); + } + + /** + * @name $browser#onUrlChange + * + * @description + * Register callback function that will be called, when url changes. + * + * It's only called when the url is changed from outside of angular: + * - user types different url into address bar + * - user clicks on history (forward/back) button + * - user clicks on a link + * + * It's not called when url is changed by $browser.url() method + * + * The listener gets called with new url as parameter. + * + * NOTE: this api is intended for use only by the $location service. Please use the + * {@link ng.$location $location service} to monitor url changes in angular apps. + * + * @param {function(string)} listener Listener function to be called when url changes. + * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. + */ + self.onUrlChange = function(callback) { + // TODO(vojta): refactor to use node's syntax for events + if (!urlChangeInit) { + // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) + // don't fire popstate when user change the address bar and don't fire hashchange when url + // changed by push/replaceState + + // html5 history api - popstate event + if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); + // hashchange event + if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); + // polling + else self.addPollFn(fireUrlChange); + + urlChangeInit = true; + } + + urlChangeListeners.push(callback); + return callback; + }; + + /** + * Checks whether the url has changed outside of Angular. + * Needs to be exported to be able to check for changes that have been done in sync, + * as hashchange/popstate events fire in async. + */ + self.$$checkUrlChange = fireUrlChange; + + ////////////////////////////////////////////////////////////// + // Misc API + ////////////////////////////////////////////////////////////// + + /** + * @name $browser#baseHref + * + * @description + * Returns current + * (always relative - without domain) + * + * @returns {string} The current base href + */ + self.baseHref = function() { + var href = baseElement.attr('href'); + return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; + }; + + ////////////////////////////////////////////////////////////// + // Cookies API + ////////////////////////////////////////////////////////////// + var lastCookies = {}; + var lastCookieString = ''; + var cookiePath = self.baseHref(); + + /** + * @name $browser#cookies + * + * @param {string=} name Cookie name + * @param {string=} value Cookie value + * + * @description + * The cookies method provides a 'private' low level access to browser cookies. + * It is not meant to be used directly, use the $cookie service instead. + * + * The return values vary depending on the arguments that the method was called with as follows: + * + * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify + * it + * - cookies(name, value) -> set name to value, if value is undefined delete the cookie + * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that + * way) + * + * @returns {Object} Hash of all cookies (if called without any parameter) + */ + self.cookies = function(name, value) { + /* global escape: false, unescape: false */ + var cookieLength, cookieArray, cookie, i, index; + + if (name) { + if (value === undefined) { + rawDocument.cookie = escape(name) + "=;path=" + cookiePath + + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; + } else { + if (isString(value)) { + cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + + ';path=' + cookiePath).length + 1; + + // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: + // - 300 cookies + // - 20 cookies per unique domain + // - 4096 bytes per cookie + if (cookieLength > 4096) { + $log.warn("Cookie '"+ name + + "' possibly not set or overflowed because it was too large ("+ + cookieLength + " > 4096 bytes)!"); + } + } + } + } else { + if (rawDocument.cookie !== lastCookieString) { + lastCookieString = rawDocument.cookie; + cookieArray = lastCookieString.split("; "); + lastCookies = {}; + + for (i = 0; i < cookieArray.length; i++) { + cookie = cookieArray[i]; + index = cookie.indexOf('='); + if (index > 0) { //ignore nameless cookies + name = unescape(cookie.substring(0, index)); + // the first value that is seen for a cookie is the most + // specific one. values for the same cookie name that + // follow are for less specific paths. + if (lastCookies[name] === undefined) { + lastCookies[name] = unescape(cookie.substring(index + 1)); + } + } + } + } + return lastCookies; + } + }; + + + /** + * @name $browser#defer + * @param {function()} fn A function, who's execution should be deferred. + * @param {number=} [delay=0] of milliseconds to defer the function execution. + * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. + * + * @description + * Executes a fn asynchronously via `setTimeout(fn, delay)`. + * + * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using + * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed + * via `$browser.defer.flush()`. + * + */ + self.defer = function(fn, delay) { + var timeoutId; + outstandingRequestCount++; + timeoutId = setTimeout(function() { + delete pendingDeferIds[timeoutId]; + completeOutstandingRequest(fn); + }, delay || 0); + pendingDeferIds[timeoutId] = true; + return timeoutId; + }; + + + /** + * @name $browser#defer.cancel + * + * @description + * Cancels a deferred task identified with `deferId`. + * + * @param {*} deferId Token returned by the `$browser.defer` function. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. + */ + self.defer.cancel = function(deferId) { + if (pendingDeferIds[deferId]) { + delete pendingDeferIds[deferId]; + clearTimeout(deferId); + completeOutstandingRequest(noop); + return true; + } + return false; + }; + +} + +function $BrowserProvider(){ + this.$get = ['$window', '$log', '$sniffer', '$document', + function( $window, $log, $sniffer, $document){ + return new Browser($window, $document, $log, $sniffer); + }]; +} + +/** + * @ngdoc service + * @name $cacheFactory + * + * @description + * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to + * them. + * + * ```js + * + * var cache = $cacheFactory('cacheId'); + * expect($cacheFactory.get('cacheId')).toBe(cache); + * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); + * + * cache.put("key", "value"); + * cache.put("another key", "another value"); + * + * // We've specified no options on creation + * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); + * + * ``` + * + * + * @param {string} cacheId Name or id of the newly created cache. + * @param {object=} options Options object that specifies the cache behavior. Properties: + * + * - `{number=}` `capacity` — turns the cache into LRU cache. + * + * @returns {object} Newly created cache object with the following set of methods: + * + * - `{object}` `info()` — Returns id, size, and options of cache. + * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns + * it. + * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. + * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. + * - `{void}` `removeAll()` — Removes all cached values. + * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. + * + * @example + + +
+ + + + +

Cached Values

+
+ + : + +
+ +

Cache Info

+
+ + : + +
+
+
+ + angular.module('cacheExampleApp', []). + controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { + $scope.keys = []; + $scope.cache = $cacheFactory('cacheId'); + $scope.put = function(key, value) { + if ($scope.cache.get(key) === undefined) { + $scope.keys.push(key); + } + $scope.cache.put(key, value === undefined ? null : value); + }; + }]); + + + p { + margin: 10px 0 3px; + } + +
+ */ +function $CacheFactoryProvider() { + + this.$get = function() { + var caches = {}; + + function cacheFactory(cacheId, options) { + if (cacheId in caches) { + throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); + } + + var size = 0, + stats = extend({}, options, {id: cacheId}), + data = {}, + capacity = (options && options.capacity) || Number.MAX_VALUE, + lruHash = {}, + freshEnd = null, + staleEnd = null; + + /** + * @ngdoc type + * @name $cacheFactory.Cache + * + * @description + * A cache object used to store and retrieve data, primarily used by + * {@link $http $http} and the {@link ng.directive:script script} directive to cache + * templates and other data. + * + * ```js + * angular.module('superCache') + * .factory('superCache', ['$cacheFactory', function($cacheFactory) { + * return $cacheFactory('super-cache'); + * }]); + * ``` + * + * Example test: + * + * ```js + * it('should behave like a cache', inject(function(superCache) { + * superCache.put('key', 'value'); + * superCache.put('another key', 'another value'); + * + * expect(superCache.info()).toEqual({ + * id: 'super-cache', + * size: 2 + * }); + * + * superCache.remove('another key'); + * expect(superCache.get('another key')).toBeUndefined(); + * + * superCache.removeAll(); + * expect(superCache.info()).toEqual({ + * id: 'super-cache', + * size: 0 + * }); + * })); + * ``` + */ + return caches[cacheId] = { + + /** + * @ngdoc method + * @name $cacheFactory.Cache#put + * @kind function + * + * @description + * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be + * retrieved later, and incrementing the size of the cache if the key was not already + * present in the cache. If behaving like an LRU cache, it will also remove stale + * entries from the set. + * + * It will not insert undefined values into the cache. + * + * @param {string} key the key under which the cached data is stored. + * @param {*} value the value to store alongside the key. If it is undefined, the key + * will not be stored. + * @returns {*} the value stored. + */ + put: function(key, value) { + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); + + refresh(lruEntry); + } + + if (isUndefined(value)) return; + if (!(key in data)) size++; + data[key] = value; + + if (size > capacity) { + this.remove(staleEnd.key); + } + + return value; + }, + + /** + * @ngdoc method + * @name $cacheFactory.Cache#get + * @kind function + * + * @description + * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. + * + * @param {string} key the key of the data to be retrieved + * @returns {*} the value stored. + */ + get: function(key) { + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key]; + + if (!lruEntry) return; + + refresh(lruEntry); + } + + return data[key]; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#remove + * @kind function + * + * @description + * Removes an entry from the {@link $cacheFactory.Cache Cache} object. + * + * @param {string} key the key of the entry to be removed + */ + remove: function(key) { + if (capacity < Number.MAX_VALUE) { + var lruEntry = lruHash[key]; + + if (!lruEntry) return; + + if (lruEntry == freshEnd) freshEnd = lruEntry.p; + if (lruEntry == staleEnd) staleEnd = lruEntry.n; + link(lruEntry.n,lruEntry.p); + + delete lruHash[key]; + } + + delete data[key]; + size--; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#removeAll + * @kind function + * + * @description + * Clears the cache object of any entries. + */ + removeAll: function() { + data = {}; + size = 0; + lruHash = {}; + freshEnd = staleEnd = null; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#destroy + * @kind function + * + * @description + * Destroys the {@link $cacheFactory.Cache Cache} object entirely, + * removing it from the {@link $cacheFactory $cacheFactory} set. + */ + destroy: function() { + data = null; + stats = null; + lruHash = null; + delete caches[cacheId]; + }, + + + /** + * @ngdoc method + * @name $cacheFactory.Cache#info + * @kind function + * + * @description + * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. + * + * @returns {object} an object with the following properties: + *
    + *
  • **id**: the id of the cache instance
  • + *
  • **size**: the number of entries kept in the cache instance
  • + *
  • **...**: any additional properties from the options object when creating the + * cache.
  • + *
+ */ + info: function() { + return extend({}, stats, {size: size}); + } + }; + + + /** + * makes the `entry` the freshEnd of the LRU linked list + */ + function refresh(entry) { + if (entry != freshEnd) { + if (!staleEnd) { + staleEnd = entry; + } else if (staleEnd == entry) { + staleEnd = entry.n; + } + + link(entry.n, entry.p); + link(entry, freshEnd); + freshEnd = entry; + freshEnd.n = null; + } + } + + + /** + * bidirectionally links two entries of the LRU linked list + */ + function link(nextEntry, prevEntry) { + if (nextEntry != prevEntry) { + if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify + if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify + } + } + } + + + /** + * @ngdoc method + * @name $cacheFactory#info + * + * @description + * Get information about all the caches that have been created + * + * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` + */ + cacheFactory.info = function() { + var info = {}; + forEach(caches, function(cache, cacheId) { + info[cacheId] = cache.info(); + }); + return info; + }; + + + /** + * @ngdoc method + * @name $cacheFactory#get + * + * @description + * Get access to a cache object by the `cacheId` used when it was created. + * + * @param {string} cacheId Name or id of a cache to access. + * @returns {object} Cache object identified by the cacheId or undefined if no such cache. + */ + cacheFactory.get = function(cacheId) { + return caches[cacheId]; + }; + + + return cacheFactory; + }; +} + +/** + * @ngdoc service + * @name $templateCache + * + * @description + * The first time a template is used, it is loaded in the template cache for quick retrieval. You + * can load templates directly into the cache in a `script` tag, or by consuming the + * `$templateCache` service directly. + * + * Adding via the `script` tag: + * + * ```html + * + * ``` + * + * **Note:** the `script` tag containing the template does not need to be included in the `head` of + * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE, + * element with ng-app attribute), otherwise the template will be ignored. + * + * Adding via the $templateCache service: + * + * ```js + * var myApp = angular.module('myApp', []); + * myApp.run(function($templateCache) { + * $templateCache.put('templateId.html', 'This is the content of the template'); + * }); + * ``` + * + * To retrieve the template later, simply use it in your HTML: + * ```html + *
+ * ``` + * + * or get it via Javascript: + * ```js + * $templateCache.get('templateId.html') + * ``` + * + * See {@link ng.$cacheFactory $cacheFactory}. + * + */ +function $TemplateCacheProvider() { + this.$get = ['$cacheFactory', function($cacheFactory) { + return $cacheFactory('templates'); + }]; +} + +/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! + * + * DOM-related variables: + * + * - "node" - DOM Node + * - "element" - DOM Element or Node + * - "$node" or "$element" - jqLite-wrapped node or element + * + * + * Compiler related stuff: + * + * - "linkFn" - linking fn of a single directive + * - "nodeLinkFn" - function that aggregates all linking fns for a particular node + * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node + * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) + */ + + +/** + * @ngdoc service + * @name $compile + * @kind function + * + * @description + * Compiles an HTML string or DOM into a template and produces a template function, which + * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. + * + * The compilation is a process of walking the DOM tree and matching DOM elements to + * {@link ng.$compileProvider#directive directives}. + * + *
+ * **Note:** This document is an in-depth reference of all directive options. + * For a gentle introduction to directives with examples of common use cases, + * see the {@link guide/directive directive guide}. + *
+ * + * ## Comprehensive Directive API + * + * There are many different options for a directive. + * + * The difference resides in the return value of the factory function. + * You can either return a "Directive Definition Object" (see below) that defines the directive properties, + * or just the `postLink` function (all other properties will have the default values). + * + *
+ * **Best Practice:** It's recommended to use the "directive definition object" form. + *
+ * + * Here's an example directive declared with a Directive Definition Object: + * + * ```js + * var myModule = angular.module(...); + * + * myModule.directive('directiveName', function factory(injectables) { + * var directiveDefinitionObject = { + * priority: 0, + * template: '
', // or // function(tElement, tAttrs) { ... }, + * // or + * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, + * transclude: false, + * restrict: 'A', + * scope: false, + * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, + * controllerAs: 'stringAlias', + * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], + * compile: function compile(tElement, tAttrs, transclude) { + * return { + * pre: function preLink(scope, iElement, iAttrs, controller) { ... }, + * post: function postLink(scope, iElement, iAttrs, controller) { ... } + * } + * // or + * // return function postLink( ... ) { ... } + * }, + * // or + * // link: { + * // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, + * // post: function postLink(scope, iElement, iAttrs, controller) { ... } + * // } + * // or + * // link: function postLink( ... ) { ... } + * }; + * return directiveDefinitionObject; + * }); + * ``` + * + *
+ * **Note:** Any unspecified options will use the default value. You can see the default values below. + *
+ * + * Therefore the above can be simplified as: + * + * ```js + * var myModule = angular.module(...); + * + * myModule.directive('directiveName', function factory(injectables) { + * var directiveDefinitionObject = { + * link: function postLink(scope, iElement, iAttrs) { ... } + * }; + * return directiveDefinitionObject; + * // or + * // return function postLink(scope, iElement, iAttrs) { ... } + * }); + * ``` + * + * + * + * ### Directive Definition Object + * + * The directive definition object provides instructions to the {@link ng.$compile + * compiler}. The attributes are: + * + * #### `priority` + * When there are multiple directives defined on a single DOM element, sometimes it + * is necessary to specify the order in which the directives are applied. The `priority` is used + * to sort the directives before their `compile` functions get called. Priority is defined as a + * number. Directives with greater numerical `priority` are compiled first. Pre-link functions + * are also run in priority order, but post-link functions are run in reverse order. The order + * of directives with the same priority is undefined. The default priority is `0`. + * + * #### `terminal` + * If set to true then the current `priority` will be the last set of directives + * which will execute (any directives at the current priority will still execute + * as the order of execution on same `priority` is undefined). + * + * #### `scope` + * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the + * same element request a new scope, only one new scope is created. The new scope rule does not + * apply for the root of the template since the root of the template always gets a new scope. + * + * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from + * normal scope in that it does not prototypically inherit from the parent scope. This is useful + * when creating reusable components, which should not accidentally read or modify data in the + * parent scope. + * + * The 'isolate' scope takes an object hash which defines a set of local scope properties + * derived from the parent scope. These local properties are useful for aliasing values for + * templates. Locals definition is a hash of local scope property to its source: + * + * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is + * always a string since DOM attributes are strings. If no `attr` name is specified then the + * attribute name is assumed to be the same as the local name. + * Given `` and widget definition + * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect + * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the + * `localName` property on the widget scope. The `name` is read from the parent scope (not + * component scope). + * + * * `=` or `=attr` - set up bi-directional binding between a local scope property and the + * parent scope property of name defined via the value of the `attr` attribute. If no `attr` + * name is specified then the attribute name is assumed to be the same as the local name. + * Given `` and widget definition of + * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the + * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected + * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent + * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You + * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. + * + * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. + * If no `attr` name is specified then the attribute name is assumed to be the same as the + * local name. Given `` and widget definition of + * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to + * a function wrapper for the `count = count + value` expression. Often it's desirable to + * pass data from the isolated scope via an expression to the parent scope, this can be + * done by passing a map of local variable names and values into the expression wrapper fn. + * For example, if the expression is `increment(amount)` then we can specify the amount value + * by calling the `localFn` as `localFn({amount: 22})`. + * + * + * + * #### `controller` + * Controller constructor function. The controller is instantiated before the + * pre-linking phase and it is shared with other directives (see + * `require` attribute). This allows the directives to communicate with each other and augment + * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: + * + * * `$scope` - Current scope associated with the element + * * `$element` - Current element + * * `$attrs` - Current attributes object for the element + * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope. + * The scope can be overridden by an optional first argument. + * `function([scope], cloneLinkingFn)`. + * + * + * #### `require` + * Require another directive and inject its controller as the fourth argument to the linking function. The + * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the + * injected argument will be an array in corresponding order. If no such directive can be + * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: + * + * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. + * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. + * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. + * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass + * `null` to the `link` fn if not found. + * + * + * #### `controllerAs` + * Controller alias at the directive scope. An alias for the controller so it + * can be referenced at the directive template. The directive needs to define a scope for this + * configuration to be used. Useful in the case when directive is used as component. + * + * + * #### `restrict` + * String of subset of `EACM` which restricts the directive to a specific directive + * declaration style. If omitted, the default (attributes only) is used. + * + * * `E` - Element name: `` + * * `A` - Attribute (default): `
` + * * `C` - Class: `
` + * * `M` - Comment: `` + * + * + * #### `template` + * HTML markup that may: + * * Replace the contents of the directive's element (default). + * * Replace the directive's element itself (if `replace` is true - DEPRECATED). + * * Wrap the contents of the directive's element (if `transclude` is true). + * + * Value may be: + * + * * A string. For example `
{{delete_str}}
`. + * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` + * function api below) and returns a string value. + * + * + * #### `templateUrl` + * Same as `template` but the template is loaded from the specified URL. Because + * the template loading is asynchronous the compilation/linking is suspended until the template + * is loaded. + * + * You can specify `templateUrl` as a string representing the URL or as a function which takes two + * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns + * a string value representing the url. In either case, the template URL is passed through {@link + * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. + * + * + * #### `replace` ([*DEPRECATED*!], will be removed in next major release) + * specify what the template should replace. Defaults to `false`. + * + * * `true` - the template will replace the directive's element. + * * `false` - the template will replace the contents of the directive's element. + * + * The replacement process migrates all of the attributes / classes from the old element to the new + * one. See the {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive + * Directives Guide} for an example. + * + * #### `transclude` + * compile the content of the element and make it available to the directive. + * Typically used with {@link ng.directive:ngTransclude + * ngTransclude}. The advantage of transclusion is that the linking function receives a + * transclusion function which is pre-bound to the correct scope. In a typical setup the widget + * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate` + * scope. This makes it possible for the widget to have private state, and the transclusion to + * be bound to the parent (pre-`isolate`) scope. + * + * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the + * directive's element or the entire element: + * + * * `true` - transclude the content (i.e. the child nodes) of the directive's element. + * * `'element'` - transclude the whole of the directive's element including any directives on this + * element that defined at a lower priority than this directive. When used, the `template` + * property is ignored. + * + *
+ * **Note:** When testing an element transclude directive you must not place the directive at the root of the + * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives + * Testing Transclusion Directives}. + *
+ * + * #### `compile` + * + * ```js + * function compile(tElement, tAttrs, transclude) { ... } + * ``` + * + * The compile function deals with transforming the template DOM. Since most directives do not do + * template transformation, it is not used often. The compile function takes the following arguments: + * + * * `tElement` - template element - The element where the directive has been declared. It is + * safe to do template transformation on the element and child elements only. + * + * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared + * between all directive compile functions. + * + * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` + * + *
+ * **Note:** The template instance and the link instance may be different objects if the template has + * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that + * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration + * should be done in a linking function rather than in a compile function. + *
+ + *
+ * **Note:** The compile function cannot handle directives that recursively use themselves in their + * own templates or compile functions. Compiling these directives results in an infinite loop and a + * stack overflow errors. + * + * This can be avoided by manually using $compile in the postLink function to imperatively compile + * a directive's template instead of relying on automatic template compilation via `template` or + * `templateUrl` declaration or manual compilation inside the compile function. + *
+ * + *
+ * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it + * e.g. does not know about the right outer scope. Please use the transclude function that is passed + * to the link function instead. + *
+ + * A compile function can have a return value which can be either a function or an object. + * + * * returning a (post-link) function - is equivalent to registering the linking function via the + * `link` property of the config object when the compile function is empty. + * + * * returning an object with function(s) registered via `pre` and `post` properties - allows you to + * control when a linking function should be called during the linking phase. See info about + * pre-linking and post-linking functions below. + * + * + * #### `link` + * This property is used only if the `compile` property is not defined. + * + * ```js + * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } + * ``` + * + * The link function is responsible for registering DOM listeners as well as updating the DOM. It is + * executed after the template has been cloned. This is where most of the directive logic will be + * put. + * + * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the + * directive for registering {@link ng.$rootScope.Scope#$watch watches}. + * + * * `iElement` - instance element - The element where the directive is to be used. It is safe to + * manipulate the children of the element only in `postLink` function since the children have + * already been linked. + * + * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared + * between all directive linking functions. + * + * * `controller` - a controller instance - A controller instance if at least one directive on the + * element defines a controller. The controller is shared among all the directives, which allows + * the directives to use the controllers as a communication channel. + * + * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. + * The scope can be overridden by an optional first argument. This is the same as the `$transclude` + * parameter of directive controllers. + * `function([scope], cloneLinkingFn)`. + * + * + * #### Pre-linking function + * + * Executed before the child elements are linked. Not safe to do DOM transformation since the + * compiler linking function will fail to locate the correct elements for linking. + * + * #### Post-linking function + * + * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. + * + * + * ### Attributes + * + * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the + * `link()` or `compile()` functions. It has a variety of uses. + * + * accessing *Normalized attribute names:* + * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. + * the attributes object allows for normalized access to + * the attributes. + * + * * *Directive inter-communication:* All directives share the same instance of the attributes + * object which allows the directives to use the attributes object as inter directive + * communication. + * + * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object + * allowing other directives to read the interpolated value. + * + * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes + * that contain interpolation (e.g. `src="https://github.com/%7B%7Bbar%7D%7D"`). Not only is this very efficient but it's also + * the only way to easily get the actual value because during the linking phase the interpolation + * hasn't been evaluated yet and so the value is at this time set to `undefined`. + * + * ```js + * function linkingFn(scope, elm, attrs, ctrl) { + * // get the attribute value + * console.log(attrs.ngModel); + * + * // change the attribute + * attrs.$set('ngModel', 'new value'); + * + * // observe changes to interpolated attribute + * attrs.$observe('ngModel', function(value) { + * console.log('ngModel has changed value to ' + value); + * }); + * } + * ``` + * + * ## Example + * + *
+ * **Note**: Typically directives are registered with `module.directive`. The example below is + * to illustrate how `$compile` works. + *
+ * + + + +
+
+
+
+
+
+ + it('should auto compile', function() { + var textarea = $('textarea'); + var output = $('div[compile]'); + // The initial state reads 'Hello Angular'. + expect(output.getText()).toBe('Hello Angular'); + textarea.clear(); + textarea.sendKeys('{{name}}!'); + expect(output.getText()).toBe('Angular!'); + }); + +
+ + * + * + * @param {string|DOMElement} element Element or HTML string to compile into a template function. + * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives. + * @param {number} maxPriority only apply directives lower than given priority (Only effects the + * root element(s), not their children) + * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template + * (a DOM element/tree) to a scope. Where: + * + * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. + * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the + * `template` and call the `cloneAttachFn` function allowing the caller to attach the + * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is + * called as:
`cloneAttachFn(clonedElement, scope)` where: + * + * * `clonedElement` - is a clone of the original `element` passed into the compiler. + * * `scope` - is the current scope with which the linking function is working with. + * + * Calling the linking function returns the element of the template. It is either the original + * element passed in, or the clone of the element if the `cloneAttachFn` is provided. + * + * After linking the view is not updated until after a call to $digest which typically is done by + * Angular automatically. + * + * If you need access to the bound view, there are two ways to do it: + * + * - If you are not asking the linking function to clone the template, create the DOM element(s) + * before you send them to the compiler and keep this reference around. + * ```js + * var element = $compile('

{{total}}

')(scope); + * ``` + * + * - if on the other hand, you need the element to be cloned, the view reference from the original + * example would not point to the clone, but rather to the original template that was cloned. In + * this case, you can access the clone via the cloneAttachFn: + * ```js + * var templateElement = angular.element('

{{total}}

'), + * scope = ....; + * + * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { + * //attach the clone to DOM document at the right place + * }); + * + * //now we have reference to the cloned DOM via `clonedElement` + * ``` + * + * + * For information on how the compiler works, see the + * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. + */ + +var $compileMinErr = minErr('$compile'); + +/** + * @ngdoc provider + * @name $compileProvider + * @kind function + * + * @description + */ +$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; +function $CompileProvider($provide, $$sanitizeUriProvider) { + var hasDirectives = {}, + Suffix = 'Directive', + COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/, + CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/; + + // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes + // The assumption is that future DOM event attribute names will begin with + // 'on' and be composed of only English letters. + var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; + + /** + * @ngdoc method + * @name $compileProvider#directive + * @kind function + * + * @description + * Register a new directive with the compiler. + * + * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which + * will match as ng-bind), or an object map of directives where the keys are the + * names and the values are the factories. + * @param {Function|Array} directiveFactory An injectable directive factory function. See + * {@link guide/directive} for more info. + * @returns {ng.$compileProvider} Self for chaining. + */ + this.directive = function registerDirective(name, directiveFactory) { + assertNotHasOwnProperty(name, 'directive'); + if (isString(name)) { + assertArg(directiveFactory, 'directiveFactory'); + if (!hasDirectives.hasOwnProperty(name)) { + hasDirectives[name] = []; + $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', + function($injector, $exceptionHandler) { + var directives = []; + forEach(hasDirectives[name], function(directiveFactory, index) { + try { + var directive = $injector.invoke(directiveFactory); + if (isFunction(directive)) { + directive = { compile: valueFn(directive) }; + } else if (!directive.compile && directive.link) { + directive.compile = valueFn(directive.link); + } + directive.priority = directive.priority || 0; + directive.index = index; + directive.name = directive.name || name; + directive.require = directive.require || (directive.controller && directive.name); + directive.restrict = directive.restrict || 'A'; + directives.push(directive); + } catch (e) { + $exceptionHandler(e); + } + }); + return directives; + }]); + } + hasDirectives[name].push(directiveFactory); + } else { + forEach(name, reverseParams(registerDirective)); + } + return this; + }; + + + /** + * @ngdoc method + * @name $compileProvider#aHrefSanitizationWhitelist + * @kind function + * + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during a[href] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to a[href] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.aHrefSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); + return this; + } else { + return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); + } + }; + + + /** + * @ngdoc method + * @name $compileProvider#imgSrcSanitizationWhitelist + * @kind function + * + * @description + * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * urls during img[src] sanitization. + * + * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * + * Any url about to be assigned to img[src] via data-binding is first normalized and turned into + * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` + * regular expression. If a match is found, the original url is written into the dom. Otherwise, + * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. + * + * @param {RegExp=} regexp New regexp to whitelist urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.imgSrcSanitizationWhitelist = function(regexp) { + if (isDefined(regexp)) { + $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); + return this; + } else { + return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); + } + }; + + this.$get = [ + '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', + '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', + function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, + $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { + + var Attributes = function(element, attr) { + this.$$element = element; + this.$attr = attr || {}; + }; + + Attributes.prototype = { + /** + * @ngdoc method + * @name $compile.directive.Attributes#$normalize + * @kind function + * + * @description + * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or + * `data-`) to its normalized, camelCase form. + * + * Also there is special case for Moz prefix starting with upper case letter. + * + * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} + * + * @param {string} name Name to normalize + */ + $normalize: directiveNormalize, + + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$addClass + * @kind function + * + * @description + * Adds the CSS class value specified by the classVal parameter to the element. If animations + * are enabled then an animation will be triggered for the class addition. + * + * @param {string} classVal The className value that will be added to the element + */ + $addClass : function(classVal) { + if(classVal && classVal.length > 0) { + $animate.addClass(this.$$element, classVal); + } + }, + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$removeClass + * @kind function + * + * @description + * Removes the CSS class value specified by the classVal parameter from the element. If + * animations are enabled then an animation will be triggered for the class removal. + * + * @param {string} classVal The className value that will be removed from the element + */ + $removeClass : function(classVal) { + if(classVal && classVal.length > 0) { + $animate.removeClass(this.$$element, classVal); + } + }, + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$updateClass + * @kind function + * + * @description + * Adds and removes the appropriate CSS class values to the element based on the difference + * between the new and old CSS class values (specified as newClasses and oldClasses). + * + * @param {string} newClasses The current CSS className value + * @param {string} oldClasses The former CSS className value + */ + $updateClass : function(newClasses, oldClasses) { + var toAdd = tokenDifference(newClasses, oldClasses); + var toRemove = tokenDifference(oldClasses, newClasses); + + if(toAdd.length === 0) { + $animate.removeClass(this.$$element, toRemove); + } else if(toRemove.length === 0) { + $animate.addClass(this.$$element, toAdd); + } else { + $animate.setClass(this.$$element, toAdd, toRemove); + } + }, + + /** + * Set a normalized attribute on the element in a way such that all directives + * can share the attribute. This function properly handles boolean attributes. + * @param {string} key Normalized key. (ie ngAttribute) + * @param {string|boolean} value The value to set. If `null` attribute will be deleted. + * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. + * Defaults to true. + * @param {string=} attrName Optional none normalized name. Defaults to key. + */ + $set: function(key, value, writeAttr, attrName) { + // TODO: decide whether or not to throw an error if "class" + //is set through this function since it may cause $updateClass to + //become unstable. + + var booleanKey = getBooleanAttrName(this.$$element[0], key), + normalizedVal, + nodeName; + + if (booleanKey) { + this.$$element.prop(key, value); + attrName = booleanKey; + } + + this[key] = value; + + // translate normalized key to actual key + if (attrName) { + this.$attr[key] = attrName; + } else { + attrName = this.$attr[key]; + if (!attrName) { + this.$attr[key] = attrName = snake_case(key, '-'); + } + } + + nodeName = nodeName_(this.$$element); + + // sanitize a[href] and img[src] values + if ((nodeName === 'A' && key === 'href') || + (nodeName === 'IMG' && key === 'src')) { + this[key] = value = $$sanitizeUri(value, key === 'src'); + } + + if (writeAttr !== false) { + if (value === null || value === undefined) { + this.$$element.removeAttr(attrName); + } else { + this.$$element.attr(attrName, value); + } + } + + // fire observers + var $$observers = this.$$observers; + $$observers && forEach($$observers[key], function(fn) { + try { + fn(value); + } catch (e) { + $exceptionHandler(e); + } + }); + }, + + + /** + * @ngdoc method + * @name $compile.directive.Attributes#$observe + * @kind function + * + * @description + * Observes an interpolated attribute. + * + * The observer function will be invoked once during the next `$digest` following + * compilation. The observer is then invoked whenever the interpolated value + * changes. + * + * @param {string} key Normalized key. (ie ngAttribute) . + * @param {function(interpolatedValue)} fn Function that will be called whenever + the interpolated value of the attribute changes. + * See the {@link guide/directive#Attributes Directives} guide for more info. + * @returns {function()} the `fn` parameter. + */ + $observe: function(key, fn) { + var attrs = this, + $$observers = (attrs.$$observers || (attrs.$$observers = {})), + listeners = ($$observers[key] || ($$observers[key] = [])); + + listeners.push(fn); + $rootScope.$evalAsync(function() { + if (!listeners.$$inter) { + // no one registered attribute interpolation function, so lets call it manually + fn(attrs[key]); + } + }); + return fn; + } + }; + + var startSymbol = $interpolate.startSymbol(), + endSymbol = $interpolate.endSymbol(), + denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') + ? identity + : function denormalizeTemplate(template) { + return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); + }, + NG_ATTR_BINDING = /^ngAttr[A-Z]/; + + + return compile; + + //================================ + + function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, + previousCompileContext) { + if (!($compileNodes instanceof jqLite)) { + // jquery always rewraps, whereas we need to preserve the original selector so that we can + // modify it. + $compileNodes = jqLite($compileNodes); + } + // We can not compile top level text elements since text nodes can be merged and we will + // not be able to attach scope data to them, so we will wrap them in + forEach($compileNodes, function(node, index){ + if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { + $compileNodes[index] = node = jqLite(node).wrap('').parent()[0]; + } + }); + var compositeLinkFn = + compileNodes($compileNodes, transcludeFn, $compileNodes, + maxPriority, ignoreDirective, previousCompileContext); + safeAddClass($compileNodes, 'ng-scope'); + return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){ + assertArg(scope, 'scope'); + // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart + // and sometimes changes the structure of the DOM. + var $linkNode = cloneConnectFn + ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! + : $compileNodes; + + forEach(transcludeControllers, function(instance, name) { + $linkNode.data('$' + name + 'Controller', instance); + }); + + // Attach scope only to non-text nodes. + for(var i = 0, ii = $linkNode.length; i + addDirective(directives, + directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); + + // iterate over the attributes + for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes, + j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { + var attrStartName = false; + var attrEndName = false; + + attr = nAttrs[j]; + if (!msie || msie >= 8 || attr.specified) { + name = attr.name; + value = trim(attr.value); + + // support ngAttr attribute binding + ngAttrName = directiveNormalize(name); + if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) { + name = snake_case(ngAttrName.substr(6), '-'); + } + + var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); + if (ngAttrName === directiveNName + 'Start') { + attrStartName = name; + attrEndName = name.substr(0, name.length - 5) + 'end'; + name = name.substr(0, name.length - 6); + } + + nName = directiveNormalize(name.toLowerCase()); + attrsMap[nName] = name; + if (isNgAttr || !attrs.hasOwnProperty(nName)) { + attrs[nName] = value; + if (getBooleanAttrName(node, nName)) { + attrs[nName] = true; // presence means true + } + } + addAttrInterpolateDirective(node, directives, value, nName); + addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, + attrEndName); + } + } + + // use class as directive + className = node.className; + if (isString(className) && className !== '') { + while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { + nName = directiveNormalize(match[2]); + if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { + attrs[nName] = trim(match[3]); + } + className = className.substr(match.index + match[0].length); + } + } + break; + case 3: /* Text Node */ + addTextInterpolateDirective(directives, node.nodeValue); + break; + case 8: /* Comment */ + try { + match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); + if (match) { + nName = directiveNormalize(match[1]); + if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { + attrs[nName] = trim(match[2]); + } + } + } catch (e) { + // turns out that under some circumstances IE9 throws errors when one attempts to read + // comment's node value. + // Just ignore it and continue. (Can't seem to reproduce in test case.) + } + break; + } + + directives.sort(byPriority); + return directives; + } + + /** + * Given a node with an directive-start it collects all of the siblings until it finds + * directive-end. + * @param node + * @param attrStart + * @param attrEnd + * @returns {*} + */ + function groupScan(node, attrStart, attrEnd) { + var nodes = []; + var depth = 0; + if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { + var startNode = node; + do { + if (!node) { + throw $compileMinErr('uterdir', + "Unterminated attribute, found '{0}' but no matching '{1}' found.", + attrStart, attrEnd); + } + if (node.nodeType == 1 /** Element **/) { + if (node.hasAttribute(attrStart)) depth++; + if (node.hasAttribute(attrEnd)) depth--; + } + nodes.push(node); + node = node.nextSibling; + } while (depth > 0); + } else { + nodes.push(node); + } + + return jqLite(nodes); + } + + /** + * Wrapper for linking function which converts normal linking function into a grouped + * linking function. + * @param linkFn + * @param attrStart + * @param attrEnd + * @returns {Function} + */ + function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { + return function(scope, element, attrs, controllers, transcludeFn) { + element = groupScan(element[0], attrStart, attrEnd); + return linkFn(scope, element, attrs, controllers, transcludeFn); + }; + } + + /** + * Once the directives have been collected, their compile functions are executed. This method + * is responsible for inlining directive templates as well as terminating the application + * of the directives if the terminal directive has been reached. + * + * @param {Array} directives Array of collected directives to execute their compile function. + * this needs to be pre-sorted by priority order. + * @param {Node} compileNode The raw DOM node to apply the compile functions to + * @param {Object} templateAttrs The shared attribute function + * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the + * scope argument is auto-generated to the new + * child of the transcluded parent scope. + * @param {JQLite} jqCollection If we are working on the root of the compile tree then this + * argument has the root jqLite array so that we can replace nodes + * on it. + * @param {Object=} originalReplaceDirective An optional directive that will be ignored when + * compiling the transclusion. + * @param {Array.} preLinkFns + * @param {Array.} postLinkFns + * @param {Object} previousCompileContext Context used for previous compilation of the current + * node + * @returns {Function} linkFn + */ + function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, + jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, + previousCompileContext) { + previousCompileContext = previousCompileContext || {}; + + var terminalPriority = -Number.MAX_VALUE, + newScopeDirective, + controllerDirectives = previousCompileContext.controllerDirectives, + newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, + templateDirective = previousCompileContext.templateDirective, + nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, + hasTranscludeDirective = false, + hasTemplate = false, + hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, + $compileNode = templateAttrs.$$element = jqLite(compileNode), + directive, + directiveName, + $template, + replaceDirective = originalReplaceDirective, + childTranscludeFn = transcludeFn, + linkFn, + directiveValue; + + // executes all directives on the current element + for(var i = 0, ii = directives.length; i < ii; i++) { + directive = directives[i]; + var attrStart = directive.$$start; + var attrEnd = directive.$$end; + + // collect multiblock sections + if (attrStart) { + $compileNode = groupScan(compileNode, attrStart, attrEnd); + } + $template = undefined; + + if (terminalPriority > directive.priority) { + break; // prevent further processing of directives + } + + if (directiveValue = directive.scope) { + newScopeDirective = newScopeDirective || directive; + + // skip the check for directives with async templates, we'll check the derived sync + // directive when the template arrives + if (!directive.templateUrl) { + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, + $compileNode); + if (isObject(directiveValue)) { + newIsolateScopeDirective = directive; + } + } + } + + directiveName = directive.name; + + if (!directive.templateUrl && directive.controller) { + directiveValue = directive.controller; + controllerDirectives = controllerDirectives || {}; + assertNoDuplicate("'" + directiveName + "' controller", + controllerDirectives[directiveName], directive, $compileNode); + controllerDirectives[directiveName] = directive; + } + + if (directiveValue = directive.transclude) { + hasTranscludeDirective = true; + + // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. + // This option should only be used by directives that know how to safely handle element transclusion, + // where the transcluded nodes are added or replaced after linking. + if (!directive.$$tlb) { + assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); + nonTlbTranscludeDirective = directive; + } + + if (directiveValue == 'element') { + hasElementTranscludeDirective = true; + terminalPriority = directive.priority; + $template = $compileNode; + $compileNode = templateAttrs.$$element = + jqLite(document.createComment(' ' + directiveName + ': ' + + templateAttrs[directiveName] + ' ')); + compileNode = $compileNode[0]; + replaceWith(jqCollection, sliceArgs($template), compileNode); + + childTranscludeFn = compile($template, transcludeFn, terminalPriority, + replaceDirective && replaceDirective.name, { + // Don't pass in: + // - controllerDirectives - otherwise we'll create duplicates controllers + // - newIsolateScopeDirective or templateDirective - combining templates with + // element transclusion doesn't make sense. + // + // We need only nonTlbTranscludeDirective so that we prevent putting transclusion + // on the same element more than once. + nonTlbTranscludeDirective: nonTlbTranscludeDirective + }); + } else { + $template = jqLite(jqLiteClone(compileNode)).contents(); + $compileNode.empty(); // clear contents + childTranscludeFn = compile($template, transcludeFn); + } + } + + if (directive.template) { + hasTemplate = true; + assertNoDuplicate('template', templateDirective, directive, $compileNode); + templateDirective = directive; + + directiveValue = (isFunction(directive.template)) + ? directive.template($compileNode, templateAttrs) + : directive.template; + + directiveValue = denormalizeTemplate(directiveValue); + + if (directive.replace) { + replaceDirective = directive; + if (jqLiteIsTextNode(directiveValue)) { + $template = []; + } else { + $template = jqLite(trim(directiveValue)); + } + compileNode = $template[0]; + + if ($template.length != 1 || compileNode.nodeType !== 1) { + throw $compileMinErr('tplrt', + "Template for directive '{0}' must have exactly one root element. {1}", + directiveName, ''); + } + + replaceWith(jqCollection, $compileNode, compileNode); + + var newTemplateAttrs = {$attr: {}}; + + // combine directives from the original node and from the template: + // - take the array of directives for this element + // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) + // - collect directives from the template and sort them by priority + // - combine directives as: processed + template + unprocessed + var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); + var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); + + if (newIsolateScopeDirective) { + markDirectivesAsIsolate(templateDirectives); + } + directives = directives.concat(templateDirectives).concat(unprocessedDirectives); + mergeTemplateAttributes(templateAttrs, newTemplateAttrs); + + ii = directives.length; + } else { + $compileNode.html(directiveValue); + } + } + + if (directive.templateUrl) { + hasTemplate = true; + assertNoDuplicate('template', templateDirective, directive, $compileNode); + templateDirective = directive; + + if (directive.replace) { + replaceDirective = directive; + } + + nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, + templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { + controllerDirectives: controllerDirectives, + newIsolateScopeDirective: newIsolateScopeDirective, + templateDirective: templateDirective, + nonTlbTranscludeDirective: nonTlbTranscludeDirective + }); + ii = directives.length; + } else if (directive.compile) { + try { + linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); + if (isFunction(linkFn)) { + addLinkFns(null, linkFn, attrStart, attrEnd); + } else if (linkFn) { + addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); + } + } catch (e) { + $exceptionHandler(e, startingTag($compileNode)); + } + } + + if (directive.terminal) { + nodeLinkFn.terminal = true; + terminalPriority = Math.max(terminalPriority, directive.priority); + } + + } + + nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; + nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; + nodeLinkFn.templateOnThisElement = hasTemplate; + nodeLinkFn.transclude = childTranscludeFn; + + previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; + + // might be normal or delayed nodeLinkFn depending on if templateUrl is present + return nodeLinkFn; + + //////////////////// + + function addLinkFns(pre, post, attrStart, attrEnd) { + if (pre) { + if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); + pre.require = directive.require; + pre.directiveName = directiveName; + if (newIsolateScopeDirective === directive || directive.$$isolateScope) { + pre = cloneAndAnnotateFn(pre, {isolateScope: true}); + } + preLinkFns.push(pre); + } + if (post) { + if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); + post.require = directive.require; + post.directiveName = directiveName; + if (newIsolateScopeDirective === directive || directive.$$isolateScope) { + post = cloneAndAnnotateFn(post, {isolateScope: true}); + } + postLinkFns.push(post); + } + } + + + function getControllers(directiveName, require, $element, elementControllers) { + var value, retrievalMethod = 'data', optional = false; + if (isString(require)) { + while((value = require.charAt(0)) == '^' || value == '?') { + require = require.substr(1); + if (value == '^') { + retrievalMethod = 'inheritedData'; + } + optional = optional || value == '?'; + } + value = null; + + if (elementControllers && retrievalMethod === 'data') { + value = elementControllers[require]; + } + value = value || $element[retrievalMethod]('$' + require + 'Controller'); + + if (!value && !optional) { + throw $compileMinErr('ctreq', + "Controller '{0}', required by directive '{1}', can't be found!", + require, directiveName); + } + return value; + } else if (isArray(require)) { + value = []; + forEach(require, function(require) { + value.push(getControllers(directiveName, require, $element, elementControllers)); + }); + } + return value; + } + + + function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { + var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn; + + attrs = (compileNode === linkNode) + ? templateAttrs + : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); + $element = attrs.$$element; + + if (newIsolateScopeDirective) { + var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; + + isolateScope = scope.$new(true); + + if (templateDirective && (templateDirective === newIsolateScopeDirective || + templateDirective === newIsolateScopeDirective.$$originalDirective)) { + $element.data('$isolateScope', isolateScope); + } else { + $element.data('$isolateScopeNoTemplate', isolateScope); + } + + + + safeAddClass($element, 'ng-isolate-scope'); + + forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { + var match = definition.match(LOCAL_REGEXP) || [], + attrName = match[3] || scopeName, + optional = (match[2] == '?'), + mode = match[1], // @, =, or & + lastValue, + parentGet, parentSet, compare; + + isolateScope.$$isolateBindings[scopeName] = mode + attrName; + + switch (mode) { + + case '@': + attrs.$observe(attrName, function(value) { + isolateScope[scopeName] = value; + }); + attrs.$$observers[attrName].$$scope = scope; + if( attrs[attrName] ) { + // If the attribute has been provided then we trigger an interpolation to ensure + // the value is there for use in the link fn + isolateScope[scopeName] = $interpolate(attrs[attrName])(scope); + } + break; + + case '=': + if (optional && !attrs[attrName]) { + return; + } + parentGet = $parse(attrs[attrName]); + if (parentGet.literal) { + compare = equals; + } else { + compare = function(a,b) { return a === b || (a !== a && b !== b); }; + } + parentSet = parentGet.assign || function() { + // reset the change, or we will throw this exception on every $digest + lastValue = isolateScope[scopeName] = parentGet(scope); + throw $compileMinErr('nonassign', + "Expression '{0}' used with directive '{1}' is non-assignable!", + attrs[attrName], newIsolateScopeDirective.name); + }; + lastValue = isolateScope[scopeName] = parentGet(scope); + isolateScope.$watch(function parentValueWatch() { + var parentValue = parentGet(scope); + if (!compare(parentValue, isolateScope[scopeName])) { + // we are out of sync and need to copy + if (!compare(parentValue, lastValue)) { + // parent changed and it has precedence + isolateScope[scopeName] = parentValue; + } else { + // if the parent can be assigned then do so + parentSet(scope, parentValue = isolateScope[scopeName]); + } + } + return lastValue = parentValue; + }, null, parentGet.literal); + break; + + case '&': + parentGet = $parse(attrs[attrName]); + isolateScope[scopeName] = function(locals) { + return parentGet(scope, locals); + }; + break; + + default: + throw $compileMinErr('iscp', + "Invalid isolate scope definition for directive '{0}'." + + " Definition: {... {1}: '{2}' ...}", + newIsolateScopeDirective.name, scopeName, definition); + } + }); + } + transcludeFn = boundTranscludeFn && controllersBoundTransclude; + if (controllerDirectives) { + forEach(controllerDirectives, function(directive) { + var locals = { + $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, + $element: $element, + $attrs: attrs, + $transclude: transcludeFn + }, controllerInstance; + + controller = directive.controller; + if (controller == '@') { + controller = attrs[directive.name]; + } + + controllerInstance = $controller(controller, locals); + // For directives with element transclusion the element is a comment, + // but jQuery .data doesn't support attaching data to comment nodes as it's hard to + // clean up (http://bugs.jquery.com/ticket/8335). + // Instead, we save the controllers for the element in a local hash and attach to .data + // later, once we have the actual element. + elementControllers[directive.name] = controllerInstance; + if (!hasElementTranscludeDirective) { + $element.data('$' + directive.name + 'Controller', controllerInstance); + } + + if (directive.controllerAs) { + locals.$scope[directive.controllerAs] = controllerInstance; + } + }); + } + + // PRELINKING + for(i = 0, ii = preLinkFns.length; i < ii; i++) { + try { + linkFn = preLinkFns[i]; + linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn); + } catch (e) { + $exceptionHandler(e, startingTag($element)); + } + } + + // RECURSION + // We only pass the isolate scope, if the isolate directive has a template, + // otherwise the child elements do not belong to the isolate directive. + var scopeToChild = scope; + if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { + scopeToChild = isolateScope; + } + childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); + + // POSTLINKING + for(i = postLinkFns.length - 1; i >= 0; i--) { + try { + linkFn = postLinkFns[i]; + linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn); + } catch (e) { + $exceptionHandler(e, startingTag($element)); + } + } + + // This is the function that is injected as `$transclude`. + function controllersBoundTransclude(scope, cloneAttachFn) { + var transcludeControllers; + + // no scope passed + if (arguments.length < 2) { + cloneAttachFn = scope; + scope = undefined; + } + + if (hasElementTranscludeDirective) { + transcludeControllers = elementControllers; + } + + return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers); + } + } + } + + function markDirectivesAsIsolate(directives) { + // mark all directives as needing isolate scope. + for (var j = 0, jj = directives.length; j < jj; j++) { + directives[j] = inherit(directives[j], {$$isolateScope: true}); + } + } + + /** + * looks up the directive and decorates it with exception handling and proper parameters. We + * call this the boundDirective. + * + * @param {string} name name of the directive to look up. + * @param {string} location The directive must be found in specific format. + * String containing any of theses characters: + * + * * `E`: element name + * * `A': attribute + * * `C`: class + * * `M`: comment + * @returns {boolean} true if directive was added. + */ + function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, + endAttrName) { + if (name === ignoreDirective) return null; + var match = null; + if (hasDirectives.hasOwnProperty(name)) { + for(var directive, directives = $injector.get(name + Suffix), + i = 0, ii = directives.length; i directive.priority) && + directive.restrict.indexOf(location) != -1) { + if (startAttrName) { + directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + } + tDirectives.push(directive); + match = directive; + } + } catch(e) { $exceptionHandler(e); } + } + } + return match; + } + + + /** + * When the element is replaced with HTML template then the new attributes + * on the template need to be merged with the existing attributes in the DOM. + * The desired effect is to have both of the attributes present. + * + * @param {object} dst destination attributes (original DOM) + * @param {object} src source attributes (from the directive template) + */ + function mergeTemplateAttributes(dst, src) { + var srcAttr = src.$attr, + dstAttr = dst.$attr, + $element = dst.$$element; + + // reapply the old attributes to the new element + forEach(dst, function(value, key) { + if (key.charAt(0) != '$') { + if (src[key] && src[key] !== value) { + value += (key === 'style' ? ';' : ' ') + src[key]; + } + dst.$set(key, value, true, srcAttr[key]); + } + }); + + // copy the new attributes on the old attrs object + forEach(src, function(value, key) { + if (key == 'class') { + safeAddClass($element, value); + dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; + } else if (key == 'style') { + $element.attr('style', $element.attr('style') + ';' + value); + dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; + // `dst` will never contain hasOwnProperty as DOM parser won't let it. + // You will get an "InvalidCharacterError: DOM Exception 5" error if you + // have an attribute like "has-own-property" or "data-has-own-property", etc. + } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { + dst[key] = value; + dstAttr[key] = srcAttr[key]; + } + }); + } + + + function compileTemplateUrl(directives, $compileNode, tAttrs, + $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { + var linkQueue = [], + afterTemplateNodeLinkFn, + afterTemplateChildLinkFn, + beforeTemplateCompileNode = $compileNode[0], + origAsyncDirective = directives.shift(), + // The fact that we have to copy and patch the directive seems wrong! + derivedSyncDirective = extend({}, origAsyncDirective, { + templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective + }), + templateUrl = (isFunction(origAsyncDirective.templateUrl)) + ? origAsyncDirective.templateUrl($compileNode, tAttrs) + : origAsyncDirective.templateUrl; + + $compileNode.empty(); + + $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). + success(function(content) { + var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; + + content = denormalizeTemplate(content); + + if (origAsyncDirective.replace) { + if (jqLiteIsTextNode(content)) { + $template = []; + } else { + $template = jqLite(trim(content)); + } + compileNode = $template[0]; + + if ($template.length != 1 || compileNode.nodeType !== 1) { + throw $compileMinErr('tplrt', + "Template for directive '{0}' must have exactly one root element. {1}", + origAsyncDirective.name, templateUrl); + } + + tempTemplateAttrs = {$attr: {}}; + replaceWith($rootElement, $compileNode, compileNode); + var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); + + if (isObject(origAsyncDirective.scope)) { + markDirectivesAsIsolate(templateDirectives); + } + directives = templateDirectives.concat(directives); + mergeTemplateAttributes(tAttrs, tempTemplateAttrs); + } else { + compileNode = beforeTemplateCompileNode; + $compileNode.html(content); + } + + directives.unshift(derivedSyncDirective); + + afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, + childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, + previousCompileContext); + forEach($rootElement, function(node, i) { + if (node == compileNode) { + $rootElement[i] = $compileNode[0]; + } + }); + afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); + + while(linkQueue.length) { + var scope = linkQueue.shift(), + beforeTemplateLinkNode = linkQueue.shift(), + linkRootElement = linkQueue.shift(), + boundTranscludeFn = linkQueue.shift(), + linkNode = $compileNode[0]; + + if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { + var oldClasses = beforeTemplateLinkNode.className; + + if (!(previousCompileContext.hasElementTranscludeDirective && + origAsyncDirective.replace)) { + // it was cloned therefore we have to clone as well. + linkNode = jqLiteClone(compileNode); + } + + replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); + + // Copy in CSS classes from original node + safeAddClass(jqLite(linkNode), oldClasses); + } + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } else { + childBoundTranscludeFn = boundTranscludeFn; + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, + childBoundTranscludeFn); + } + linkQueue = null; + }). + error(function(response, code, headers, config) { + throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); + }); + + return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { + var childBoundTranscludeFn = boundTranscludeFn; + if (linkQueue) { + linkQueue.push(scope); + linkQueue.push(node); + linkQueue.push(rootElement); + linkQueue.push(childBoundTranscludeFn); + } else { + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); + } + }; + } + + + /** + * Sorting function for bound directives. + */ + function byPriority(a, b) { + var diff = b.priority - a.priority; + if (diff !== 0) return diff; + if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; + return a.index - b.index; + } + + + function assertNoDuplicate(what, previousDirective, directive, element) { + if (previousDirective) { + throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', + previousDirective.name, directive.name, what, startingTag(element)); + } + } + + + function addTextInterpolateDirective(directives, text) { + var interpolateFn = $interpolate(text, true); + if (interpolateFn) { + directives.push({ + priority: 0, + compile: function textInterpolateCompileFn(templateNode) { + // when transcluding a template that has bindings in the root + // then we don't have a parent and should do this in the linkFn + var parent = templateNode.parent(), hasCompileParent = parent.length; + if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding'); + + return function textInterpolateLinkFn(scope, node) { + var parent = node.parent(), + bindings = parent.data('$binding') || []; + bindings.push(interpolateFn); + parent.data('$binding', bindings); + if (!hasCompileParent) safeAddClass(parent, 'ng-binding'); + scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { + node[0].nodeValue = value; + }); + }; + } + }); + } + } + + + function getTrustedContext(node, attrNormalizedName) { + if (attrNormalizedName == "srcdoc") { + return $sce.HTML; + } + var tag = nodeName_(node); + // maction[xlink:href] can source SVG. It's not limited to . + if (attrNormalizedName == "xlinkHref" || + (tag == "FORM" && attrNormalizedName == "action") || + (tag != "IMG" && (attrNormalizedName == "src" || + attrNormalizedName == "ngSrc"))) { + return $sce.RESOURCE_URL; + } + } + + + function addAttrInterpolateDirective(node, directives, value, name) { + var interpolateFn = $interpolate(value, true); + + // no interpolation found -> ignore + if (!interpolateFn) return; + + + if (name === "multiple" && nodeName_(node) === "SELECT") { + throw $compileMinErr("selmulti", + "Binding to the 'multiple' attribute is not supported. Element: {0}", + startingTag(node)); + } + + directives.push({ + priority: 100, + compile: function() { + return { + pre: function attrInterpolatePreLinkFn(scope, element, attr) { + var $$observers = (attr.$$observers || (attr.$$observers = {})); + + if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { + throw $compileMinErr('nodomevents', + "Interpolations for HTML DOM event attributes are disallowed. Please use the " + + "ng- versions (such as ng-click instead of onclick) instead."); + } + + // we need to interpolate again, in case the attribute value has been updated + // (e.g. by another directive's compile function) + interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name)); + + // if attribute was updated so that there is no interpolation going on we don't want to + // register any observers + if (!interpolateFn) return; + + // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the + // actual attr value + attr[name] = interpolateFn(scope); + ($$observers[name] || ($$observers[name] = [])).$$inter = true; + (attr.$$observers && attr.$$observers[name].$$scope || scope). + $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { + //special case for class attribute addition + removal + //so that class changes can tap into the animation + //hooks provided by the $animate service. Be sure to + //skip animations when the first digest occurs (when + //both the new and the old values are the same) since + //the CSS classes are the non-interpolated values + if(name === 'class' && newValue != oldValue) { + attr.$updateClass(newValue, oldValue); + } else { + attr.$set(name, newValue); + } + }); + } + }; + } + }); + } + + + /** + * This is a special jqLite.replaceWith, which can replace items which + * have no parents, provided that the containing jqLite collection is provided. + * + * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes + * in the root of the tree. + * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep + * the shell, but replace its DOM node reference. + * @param {Node} newNode The new DOM node. + */ + function replaceWith($rootElement, elementsToRemove, newNode) { + var firstElementToRemove = elementsToRemove[0], + removeCount = elementsToRemove.length, + parent = firstElementToRemove.parentNode, + i, ii; + + if ($rootElement) { + for(i = 0, ii = $rootElement.length; i < ii; i++) { + if ($rootElement[i] == firstElementToRemove) { + $rootElement[i++] = newNode; + for (var j = i, j2 = j + removeCount - 1, + jj = $rootElement.length; + j < jj; j++, j2++) { + if (j2 < jj) { + $rootElement[j] = $rootElement[j2]; + } else { + delete $rootElement[j]; + } + } + $rootElement.length -= removeCount - 1; + break; + } + } + } + + if (parent) { + parent.replaceChild(newNode, firstElementToRemove); + } + var fragment = document.createDocumentFragment(); + fragment.appendChild(firstElementToRemove); + newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; + for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { + var element = elementsToRemove[k]; + jqLite(element).remove(); // must do this way to clean up expando + fragment.appendChild(element); + delete elementsToRemove[k]; + } + + elementsToRemove[0] = newNode; + elementsToRemove.length = 1; + } + + + function cloneAndAnnotateFn(fn, annotation) { + return extend(function() { return fn.apply(null, arguments); }, fn, annotation); + } + }]; +} + +var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; +/** + * Converts all accepted directives format into proper directive name. + * @param name Name to normalize + */ +function directiveNormalize(name) { + return camelCase(name.replace(PREFIX_REGEXP, '')); +} + +/** + * @ngdoc type + * @name $compile.directive.Attributes + * + * @description + * A shared object between directive compile / linking functions which contains normalized DOM + * element attributes. The values reflect current binding state `{{ }}`. The normalization is + * needed since all of these are treated as equivalent in Angular: + * + * ``` + * + * ``` + */ + +/** + * @ngdoc property + * @name $compile.directive.Attributes#$attr + * + * @description + * A map of DOM element attribute names to the normalized name. This is + * needed to do reverse lookup from normalized name back to actual name. + */ + + +/** + * @ngdoc method + * @name $compile.directive.Attributes#$set + * @kind function + * + * @description + * Set DOM element attribute value. + * + * + * @param {string} name Normalized element attribute name of the property to modify. The name is + * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} + * property to the original name. + * @param {string} value Value to set the attribute to. The value can be an interpolated string. + */ + + + +/** + * Closure compiler type information + */ + +function nodesetLinkingFn( + /* angular.Scope */ scope, + /* NodeList */ nodeList, + /* Element */ rootElement, + /* function(Function) */ boundTranscludeFn +){} + +function directiveLinkingFn( + /* nodesetLinkingFn */ nodesetLinkingFn, + /* angular.Scope */ scope, + /* Node */ node, + /* Element */ rootElement, + /* function(Function) */ boundTranscludeFn +){} + +function tokenDifference(str1, str2) { + var values = '', + tokens1 = str1.split(/\s+/), + tokens2 = str2.split(/\s+/); + + outer: + for(var i = 0; i < tokens1.length; i++) { + var token = tokens1[i]; + for(var j = 0; j < tokens2.length; j++) { + if(token == tokens2[j]) continue outer; + } + values += (values.length > 0 ? ' ' : '') + token; + } + return values; +} + +/** + * @ngdoc provider + * @name $controllerProvider + * @description + * The {@link ng.$controller $controller service} is used by Angular to create new + * controllers. + * + * This provider allows controller registration via the + * {@link ng.$controllerProvider#register register} method. + */ +function $ControllerProvider() { + var controllers = {}, + CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; + + + /** + * @ngdoc method + * @name $controllerProvider#register + * @param {string|Object} name Controller name, or an object map of controllers where the keys are + * the names and the values are the constructors. + * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI + * annotations in the array notation). + */ + this.register = function(name, constructor) { + assertNotHasOwnProperty(name, 'controller'); + if (isObject(name)) { + extend(controllers, name); + } else { + controllers[name] = constructor; + } + }; + + + this.$get = ['$injector', '$window', function($injector, $window) { + + /** + * @ngdoc service + * @name $controller + * @requires $injector + * + * @param {Function|string} constructor If called with a function then it's considered to be the + * controller constructor function. Otherwise it's considered to be a string which is used + * to retrieve the controller constructor using the following steps: + * + * * check if a controller with given name is registered via `$controllerProvider` + * * check if evaluating the string on the current scope returns a constructor + * * check `window[constructor]` on the global `window` object + * + * @param {Object} locals Injection locals for Controller. + * @return {Object} Instance of given controller. + * + * @description + * `$controller` service is responsible for instantiating controllers. + * + * It's just a simple call to {@link auto.$injector $injector}, but extracted into + * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). + */ + return function(expression, locals) { + var instance, match, constructor, identifier; + + if(isString(expression)) { + match = expression.match(CNTRL_REG), + constructor = match[1], + identifier = match[3]; + expression = controllers.hasOwnProperty(constructor) + ? controllers[constructor] + : getter(locals.$scope, constructor, true) || getter($window, constructor, true); + + assertArgFn(expression, constructor, true); + } + + instance = $injector.instantiate(expression, locals); + + if (identifier) { + if (!(locals && typeof locals.$scope === 'object')) { + throw minErr('$controller')('noscp', + "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", + constructor || expression.name, identifier); + } + + locals.$scope[identifier] = instance; + } + + return instance; + }; + }]; +} + +/** + * @ngdoc service + * @name $document + * @requires $window + * + * @description + * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. + * + * @example + + +
+

$document title:

+

window.document title:

+
+
+ + angular.module('documentExample', []) + .controller('ExampleController', ['$scope', '$document', function($scope, $document) { + $scope.title = $document[0].title; + $scope.windowTitle = angular.element(window.document)[0].title; + }]); + +
+ */ +function $DocumentProvider(){ + this.$get = ['$window', function(window){ + return jqLite(window.document); + }]; +} + +/** + * @ngdoc service + * @name $exceptionHandler + * @requires ng.$log + * + * @description + * Any uncaught exception in angular expressions is delegated to this service. + * The default implementation simply delegates to `$log.error` which logs it into + * the browser console. + * + * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by + * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. + * + * ## Example: + * + * ```js + * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { + * return function (exception, cause) { + * exception.message += ' (caused by "' + cause + '")'; + * throw exception; + * }; + * }); + * ``` + * + * This example will override the normal action of `$exceptionHandler`, to make angular + * exceptions fail hard when they happen, instead of just logging to the console. + * + * @param {Error} exception Exception associated with the error. + * @param {string=} cause optional information about the context in which + * the error was thrown. + * + */ +function $ExceptionHandlerProvider() { + this.$get = ['$log', function($log) { + return function(exception, cause) { + $log.error.apply($log, arguments); + }; + }]; +} + +/** + * Parse headers into key value object + * + * @param {string} headers Raw headers as a string + * @returns {Object} Parsed headers as key value object + */ +function parseHeaders(headers) { + var parsed = {}, key, val, i; + + if (!headers) return parsed; + + forEach(headers.split('\n'), function(line) { + i = line.indexOf(':'); + key = lowercase(trim(line.substr(0, i))); + val = trim(line.substr(i + 1)); + + if (key) { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + }); + + return parsed; +} + + +/** + * Returns a function that provides access to parsed headers. + * + * Headers are lazy parsed when first requested. + * @see parseHeaders + * + * @param {(string|Object)} headers Headers to provide access to. + * @returns {function(string=)} Returns a getter function which if called with: + * + * - if called with single an argument returns a single header value or null + * - if called with no arguments returns an object containing all headers. + */ +function headersGetter(headers) { + var headersObj = isObject(headers) ? headers : undefined; + + return function(name) { + if (!headersObj) headersObj = parseHeaders(headers); + + if (name) { + return headersObj[lowercase(name)] || null; + } + + return headersObj; + }; +} + + +/** + * Chain all given functions + * + * This function is used for both request and response transforming + * + * @param {*} data Data to transform. + * @param {function(string=)} headers Http headers getter fn. + * @param {(Function|Array.)} fns Function or an array of functions. + * @returns {*} Transformed data. + */ +function transformData(data, headers, fns) { + if (isFunction(fns)) + return fns(data, headers); + + forEach(fns, function(fn) { + data = fn(data, headers); + }); + + return data; +} + + +function isSuccess(status) { + return 200 <= status && status < 300; +} + + +/** + * @ngdoc provider + * @name $httpProvider + * @description + * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. + * */ +function $HttpProvider() { + var JSON_START = /^\s*(\[|\{[^\{])/, + JSON_END = /[\}\]]\s*$/, + PROTECTION_PREFIX = /^\)\]\}',?\n/, + CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; + + /** + * @ngdoc property + * @name $httpProvider#defaults + * @description + * + * Object containing default values for all {@link ng.$http $http} requests. + * + * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. + * Defaults value is `'XSRF-TOKEN'`. + * + * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the + * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. + * + * - **`defaults.headers`** - {Object} - Default headers for all $http requests. + * Refer to {@link ng.$http#setting-http-headers $http} for documentation on + * setting default headers. + * - **`defaults.headers.common`** + * - **`defaults.headers.post`** + * - **`defaults.headers.put`** + * - **`defaults.headers.patch`** + **/ + var defaults = this.defaults = { + // transform incoming response data + transformResponse: [function(data) { + if (isString(data)) { + // strip json vulnerability protection prefix + data = data.replace(PROTECTION_PREFIX, ''); + if (JSON_START.test(data) && JSON_END.test(data)) + data = fromJson(data); + } + return data; + }], + + // transform outgoing request data + transformRequest: [function(d) { + return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; + }], + + // default headers + headers: { + common: { + 'Accept': 'application/json, text/plain, */*' + }, + post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) + }, + + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN' + }; + + /** + * @ngdoc property + * @name $httpProvider#interceptors + * @description + * + * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} + * pre-processing of request or postprocessing of responses. + * + * These service factories are ordered by request, i.e. they are applied in the same order as the + * array, on request, but reverse order, on response. + * + * {@link ng.$http#interceptors Interceptors detailed info} + **/ + var interceptorFactories = this.interceptors = []; + + /** + * For historical reasons, response interceptors are ordered by the order in which + * they are applied to the response. (This is the opposite of interceptorFactories) + */ + var responseInterceptorFactories = this.responseInterceptors = []; + + this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', + function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { + + var defaultCache = $cacheFactory('$http'); + + /** + * Interceptors stored in reverse order. Inner interceptors before outer interceptors. + * The reversal is needed so that we can build up the interception chain around the + * server request. + */ + var reversedInterceptors = []; + + forEach(interceptorFactories, function(interceptorFactory) { + reversedInterceptors.unshift(isString(interceptorFactory) + ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); + }); + + forEach(responseInterceptorFactories, function(interceptorFactory, index) { + var responseFn = isString(interceptorFactory) + ? $injector.get(interceptorFactory) + : $injector.invoke(interceptorFactory); + + /** + * Response interceptors go before "around" interceptors (no real reason, just + * had to pick one.) But they are already reversed, so we can't use unshift, hence + * the splice. + */ + reversedInterceptors.splice(index, 0, { + response: function(response) { + return responseFn($q.when(response)); + }, + responseError: function(response) { + return responseFn($q.reject(response)); + } + }); + }); + + + /** + * @ngdoc service + * @kind function + * @name $http + * @requires ng.$httpBackend + * @requires $cacheFactory + * @requires $rootScope + * @requires $q + * @requires $injector + * + * @description + * The `$http` service is a core Angular service that facilitates communication with the remote + * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) + * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). + * + * For unit testing applications that use `$http` service, see + * {@link ngMock.$httpBackend $httpBackend mock}. + * + * For a higher level of abstraction, please check out the {@link ngResource.$resource + * $resource} service. + * + * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by + * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage + * it is important to familiarize yourself with these APIs and the guarantees they provide. + * + * + * # General usage + * The `$http` service is a function which takes a single argument — a configuration object — + * that is used to generate an HTTP request and returns a {@link ng.$q promise} + * with two $http specific methods: `success` and `error`. + * + * ```js + * $http({method: 'GET', url: '/someUrl'}). + * success(function(data, status, headers, config) { + * // this callback will be called asynchronously + * // when the response is available + * }). + * error(function(data, status, headers, config) { + * // called asynchronously if an error occurs + * // or server returns response with an error status. + * }); + * ``` + * + * Since the returned value of calling the $http function is a `promise`, you can also use + * the `then` method to register callbacks, and these callbacks will receive a single argument – + * an object representing the response. See the API signature and type info below for more + * details. + * + * A response status code between 200 and 299 is considered a success status and + * will result in the success callback being called. Note that if the response is a redirect, + * XMLHttpRequest will transparently follow it, meaning that the error callback will not be + * called for such responses. + * + * # Writing Unit Tests that use $http + * When unit testing (using {@link ngMock ngMock}), it is necessary to call + * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending + * request using trained responses. + * + * ``` + * $httpBackend.expectGET(...); + * $http.get(...); + * $httpBackend.flush(); + * ``` + * + * # Shortcut methods + * + * Shortcut methods are also available. All shortcut methods require passing in the URL, and + * request data must be passed in for POST/PUT requests. + * + * ```js + * $http.get('/someUrl').success(successCallback); + * $http.post('/someUrl', data).success(successCallback); + * ``` + * + * Complete list of shortcut methods: + * + * - {@link ng.$http#get $http.get} + * - {@link ng.$http#head $http.head} + * - {@link ng.$http#post $http.post} + * - {@link ng.$http#put $http.put} + * - {@link ng.$http#delete $http.delete} + * - {@link ng.$http#jsonp $http.jsonp} + * - {@link ng.$http#patch $http.patch} + * + * + * # Setting HTTP Headers + * + * The $http service will automatically add certain HTTP headers to all requests. These defaults + * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration + * object, which currently contains this default configuration: + * + * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): + * - `Accept: application/json, text/plain, * / *` + * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) + * - `Content-Type: application/json` + * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) + * - `Content-Type: application/json` + * + * To add or overwrite these defaults, simply add or remove a property from these configuration + * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object + * with the lowercased HTTP method name as the key, e.g. + * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. + * + * The defaults can also be set at runtime via the `$http.defaults` object in the same + * fashion. For example: + * + * ``` + * module.run(function($http) { + * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' + * }); + * ``` + * + * In addition, you can supply a `headers` property in the config object passed when + * calling `$http(config)`, which overrides the defaults without changing them globally. + * + * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, + * Use the `headers` property, setting the desired header to `undefined`. For example: + * + * ```js + * var req = { + * method: 'POST', + * url: 'http://example.com/', + * headers: { + * 'Content-Type': undefined + * }, + * data: { test: 'test' }, + * } + * + * $http(req).success(function(){...}).error(function(){...}); + * ``` + * + * # Transforming Requests and Responses + * + * Both requests and responses can be transformed using transform functions. By default, Angular + * applies these transformations: + * + * Request transformations: + * + * - If the `data` property of the request configuration object contains an object, serialize it + * into JSON format. + * + * Response transformations: + * + * - If XSRF prefix is detected, strip it (see Security Considerations section below). + * - If JSON response is detected, deserialize it using a JSON parser. + * + * To globally augment or override the default transforms, modify the + * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse` + * properties. These properties are by default an array of transform functions, which allows you + * to `push` or `unshift` a new transformation function into the transformation chain. You can + * also decide to completely override any default transformations by assigning your + * transformation functions to these properties directly without the array wrapper. These defaults + * are again available on the $http factory at run-time, which may be useful if you have run-time + * services you wish to be involved in your transformations. + * + * Similarly, to locally override the request/response transforms, augment the + * `transformRequest` and/or `transformResponse` properties of the configuration object passed + * into `$http`. + * + * + * # Caching + * + * To enable caching, set the request configuration `cache` property to `true` (to use default + * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). + * When the cache is enabled, `$http` stores the response from the server in the specified + * cache. The next time the same request is made, the response is served from the cache without + * sending a request to the server. + * + * Note that even if the response is served from cache, delivery of the data is asynchronous in + * the same way that real requests are. + * + * If there are multiple GET requests for the same URL that should be cached using the same + * cache, but the cache is not populated yet, only one request to the server will be made and + * the remaining requests will be fulfilled using the response from the first request. + * + * You can change the default cache to a new object (built with + * {@link ng.$cacheFactory `$cacheFactory`}) by updating the + * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set + * their `cache` property to `true` will now use this cache object. + * + * If you set the default cache to `false` then only requests that specify their own custom + * cache object will be cached. + * + * # Interceptors + * + * Before you start creating interceptors, be sure to understand the + * {@link ng.$q $q and deferred/promise APIs}. + * + * For purposes of global error handling, authentication, or any kind of synchronous or + * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be + * able to intercept requests before they are handed to the server and + * responses before they are handed over to the application code that + * initiated these requests. The interceptors leverage the {@link ng.$q + * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. + * + * The interceptors are service factories that are registered with the `$httpProvider` by + * adding them to the `$httpProvider.interceptors` array. The factory is called and + * injected with dependencies (if specified) and returns the interceptor. + * + * There are two kinds of interceptors (and two kinds of rejection interceptors): + * + * * `request`: interceptors get called with a http `config` object. The function is free to + * modify the `config` object or create a new one. The function needs to return the `config` + * object directly, or a promise containing the `config` or a new `config` object. + * * `requestError`: interceptor gets called when a previous interceptor threw an error or + * resolved with a rejection. + * * `response`: interceptors get called with http `response` object. The function is free to + * modify the `response` object or create a new one. The function needs to return the `response` + * object directly, or as a promise containing the `response` or a new `response` object. + * * `responseError`: interceptor gets called when a previous interceptor threw an error or + * resolved with a rejection. + * + * + * ```js + * // register the interceptor as a service + * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { + * return { + * // optional method + * 'request': function(config) { + * // do something on success + * return config; + * }, + * + * // optional method + * 'requestError': function(rejection) { + * // do something on error + * if (canRecover(rejection)) { + * return responseOrNewPromise + * } + * return $q.reject(rejection); + * }, + * + * + * + * // optional method + * 'response': function(response) { + * // do something on success + * return response; + * }, + * + * // optional method + * 'responseError': function(rejection) { + * // do something on error + * if (canRecover(rejection)) { + * return responseOrNewPromise + * } + * return $q.reject(rejection); + * } + * }; + * }); + * + * $httpProvider.interceptors.push('myHttpInterceptor'); + * + * + * // alternatively, register the interceptor via an anonymous factory + * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { + * return { + * 'request': function(config) { + * // same as above + * }, + * + * 'response': function(response) { + * // same as above + * } + * }; + * }); + * ``` + * + * # Response interceptors (DEPRECATED) + * + * Before you start creating interceptors, be sure to understand the + * {@link ng.$q $q and deferred/promise APIs}. + * + * For purposes of global error handling, authentication or any kind of synchronous or + * asynchronous preprocessing of received responses, it is desirable to be able to intercept + * responses for http requests before they are handed over to the application code that + * initiated these requests. The response interceptors leverage the {@link ng.$q + * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. + * + * The interceptors are service factories that are registered with the $httpProvider by + * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and + * injected with dependencies (if specified) and returns the interceptor — a function that + * takes a {@link ng.$q promise} and returns the original or a new promise. + * + * ```js + * // register the interceptor as a service + * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { + * return function(promise) { + * return promise.then(function(response) { + * // do something on success + * return response; + * }, function(response) { + * // do something on error + * if (canRecover(response)) { + * return responseOrNewPromise + * } + * return $q.reject(response); + * }); + * } + * }); + * + * $httpProvider.responseInterceptors.push('myHttpInterceptor'); + * + * + * // register the interceptor via an anonymous factory + * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { + * return function(promise) { + * // same as above + * } + * }); + * ``` + * + * + * # Security Considerations + * + * When designing web applications, consider security threats from: + * + * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) + * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) + * + * Both server and the client must cooperate in order to eliminate these threats. Angular comes + * pre-configured with strategies that address these issues, but for this to work backend server + * cooperation is required. + * + * ## JSON Vulnerability Protection + * + * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) + * allows third party website to turn your JSON resource URL into + * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To + * counter this your server can prefix all JSON requests with following string `")]}',\n"`. + * Angular will automatically strip the prefix before processing it as JSON. + * + * For example if your server needs to return: + * ```js + * ['one','two'] + * ``` + * + * which is vulnerable to attack, your server can return: + * ```js + * )]}', + * ['one','two'] + * ``` + * + * Angular will strip the prefix, before processing the JSON. + * + * + * ## Cross Site Request Forgery (XSRF) Protection + * + * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which + * an unauthorized site can gain your user's private data. Angular provides a mechanism + * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie + * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only + * JavaScript that runs on your domain could read the cookie, your server can be assured that + * the XHR came from JavaScript running on your domain. The header will not be set for + * cross-domain requests. + * + * To take advantage of this, your server needs to set a token in a JavaScript readable session + * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the + * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure + * that only JavaScript running on your domain could have sent the request. The token must be + * unique for each user and must be verifiable by the server (to prevent the JavaScript from + * making up its own tokens). We recommend that the token is a digest of your site's + * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) + * for added security. + * + * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName + * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, + * or the per-request config object. + * + * + * @param {object} config Object describing the request to be made and how it should be + * processed. The object has following properties: + * + * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) + * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. + * - **params** – `{Object.}` – Map of strings or objects which will be turned + * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be + * JSONified. + * - **data** – `{string|Object}` – Data to be sent as the request message data. + * - **headers** – `{Object}` – Map of strings or functions which return strings representing + * HTTP headers to send to the server. If the return value of a function is null, the + * header will not be sent. + * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. + * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. + * - **transformRequest** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * request body and headers and returns its transformed (typically serialized) version. + * - **transformResponse** – + * `{function(data, headersGetter)|Array.}` – + * transform function or an array of such functions. The transform function takes the http + * response body and headers and returns its transformed (typically deserialized) version. + * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the + * GET request, otherwise if a cache instance built with + * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for + * caching. + * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} + * that should abort the request when resolved. + * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the + * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) + * for more information. + * - **responseType** - `{string}` - see + * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). + * + * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the + * standard `then` method and two http specific methods: `success` and `error`. The `then` + * method takes two arguments a success and an error callback which will be called with a + * response object. The `success` and `error` methods take a single argument - a function that + * will be called when the request succeeds or fails respectively. The arguments passed into + * these functions are destructured representation of the response object passed into the + * `then` method. The response object has these properties: + * + * - **data** – `{string|Object}` – The response body transformed with the transform + * functions. + * - **status** – `{number}` – HTTP status code of the response. + * - **headers** – `{function([headerName])}` – Header getter function. + * - **config** – `{Object}` – The configuration object that was used to generate the request. + * - **statusText** – `{string}` – HTTP status text of the response. + * + * @property {Array.} pendingRequests Array of config objects for currently pending + * requests. This is primarily meant to be used for debugging purposes. + * + * + * @example + + +
+ + +
+ + + +
http status code: {{status}}
+
http response data: {{data}}
+
+
+ + angular.module('httpExample', []) + .controller('FetchController', ['$scope', '$http', '$templateCache', + function($scope, $http, $templateCache) { + $scope.method = 'GET'; + $scope.url = 'http-hello.html'; + + $scope.fetch = function() { + $scope.code = null; + $scope.response = null; + + $http({method: $scope.method, url: $scope.url, cache: $templateCache}). + success(function(data, status) { + $scope.status = status; + $scope.data = data; + }). + error(function(data, status) { + $scope.data = data || "Request failed"; + $scope.status = status; + }); + }; + + $scope.updateModel = function(method, url) { + $scope.method = method; + $scope.url = url; + }; + }]); + + + Hello, $http! + + + var status = element(by.binding('status')); + var data = element(by.binding('data')); + var fetchBtn = element(by.id('fetchbtn')); + var sampleGetBtn = element(by.id('samplegetbtn')); + var sampleJsonpBtn = element(by.id('samplejsonpbtn')); + var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); + + it('should make an xhr GET request', function() { + sampleGetBtn.click(); + fetchBtn.click(); + expect(status.getText()).toMatch('200'); + expect(data.getText()).toMatch(/Hello, \$http!/); + }); + +// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 +// it('should make a JSONP request to angularjs.org', function() { +// sampleJsonpBtn.click(); +// fetchBtn.click(); +// expect(status.getText()).toMatch('200'); +// expect(data.getText()).toMatch(/Super Hero!/); +// }); + + it('should make JSONP request to invalid URL and invoke the error handler', + function() { + invalidJsonpBtn.click(); + fetchBtn.click(); + expect(status.getText()).toMatch('0'); + expect(data.getText()).toMatch('Request failed'); + }); + +
+ */ + function $http(requestConfig) { + var config = { + method: 'get', + transformRequest: defaults.transformRequest, + transformResponse: defaults.transformResponse + }; + var headers = mergeHeaders(requestConfig); + + extend(config, requestConfig); + config.headers = headers; + config.method = uppercase(config.method); + + var serverRequest = function(config) { + headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); + + // strip content-type if data is undefined + if (isUndefined(reqData)) { + forEach(headers, function(value, header) { + if (lowercase(header) === 'content-type') { + delete headers[header]; + } + }); + } + + if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { + config.withCredentials = defaults.withCredentials; + } + + // send request + return sendReq(config, reqData, headers).then(transformResponse, transformResponse); + }; + + var chain = [serverRequest, undefined]; + var promise = $q.when(config); + + // apply interceptors + forEach(reversedInterceptors, function(interceptor) { + if (interceptor.request || interceptor.requestError) { + chain.unshift(interceptor.request, interceptor.requestError); + } + if (interceptor.response || interceptor.responseError) { + chain.push(interceptor.response, interceptor.responseError); + } + }); + + while(chain.length) { + var thenFn = chain.shift(); + var rejectFn = chain.shift(); + + promise = promise.then(thenFn, rejectFn); + } + + promise.success = function(fn) { + promise.then(function(response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + promise.error = function(fn) { + promise.then(null, function(response) { + fn(response.data, response.status, response.headers, config); + }); + return promise; + }; + + return promise; + + function transformResponse(response) { + // make a copy since the response must be cacheable + var resp = extend({}, response, { + data: transformData(response.data, response.headers, config.transformResponse) + }); + return (isSuccess(response.status)) + ? resp + : $q.reject(resp); + } + + function mergeHeaders(config) { + var defHeaders = defaults.headers, + reqHeaders = extend({}, config.headers), + defHeaderName, lowercaseDefHeaderName, reqHeaderName; + + defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); + + // using for-in instead of forEach to avoid unecessary iteration after header has been found + defaultHeadersIteration: + for (defHeaderName in defHeaders) { + lowercaseDefHeaderName = lowercase(defHeaderName); + + for (reqHeaderName in reqHeaders) { + if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { + continue defaultHeadersIteration; + } + } + + reqHeaders[defHeaderName] = defHeaders[defHeaderName]; + } + + // execute if header value is a function for merged headers + execHeaders(reqHeaders); + return reqHeaders; + + function execHeaders(headers) { + var headerContent; + + forEach(headers, function(headerFn, header) { + if (isFunction(headerFn)) { + headerContent = headerFn(); + if (headerContent != null) { + headers[header] = headerContent; + } else { + delete headers[header]; + } + } + }); + } + } + } + + $http.pendingRequests = []; + + /** + * @ngdoc method + * @name $http#get + * + * @description + * Shortcut method to perform `GET` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#delete + * + * @description + * Shortcut method to perform `DELETE` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#head + * + * @description + * Shortcut method to perform `HEAD` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#jsonp + * + * @description + * Shortcut method to perform `JSONP` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request. + * The name of the callback should be the string `JSON_CALLBACK`. + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethods('get', 'delete', 'head', 'jsonp'); + + /** + * @ngdoc method + * @name $http#post + * + * @description + * Shortcut method to perform `POST` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#put + * + * @description + * Shortcut method to perform `PUT` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + + /** + * @ngdoc method + * @name $http#patch + * + * @description + * Shortcut method to perform `PATCH` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object + * @returns {HttpPromise} Future object + */ + createShortMethodsWithData('post', 'put', 'patch'); + + /** + * @ngdoc property + * @name $http#defaults + * + * @description + * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of + * default headers, withCredentials as well as request and response transformations. + * + * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. + */ + $http.defaults = defaults; + + + return $http; + + + function createShortMethods(names) { + forEach(arguments, function(name) { + $http[name] = function(url, config) { + return $http(extend(config || {}, { + method: name, + url: url + })); + }; + }); + } + + + function createShortMethodsWithData(name) { + forEach(arguments, function(name) { + $http[name] = function(url, data, config) { + return $http(extend(config || {}, { + method: name, + url: url, + data: data + })); + }; + }); + } + + + /** + * Makes the request. + * + * !!! ACCESSES CLOSURE VARS: + * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests + */ + function sendReq(config, reqData, reqHeaders) { + var deferred = $q.defer(), + promise = deferred.promise, + cache, + cachedResp, + url = buildUrl(config.url, config.params); + + $http.pendingRequests.push(config); + promise.then(removePendingReq, removePendingReq); + + + if ((config.cache || defaults.cache) && config.cache !== false && + (config.method === 'GET' || config.method === 'JSONP')) { + cache = isObject(config.cache) ? config.cache + : isObject(defaults.cache) ? defaults.cache + : defaultCache; + } + + if (cache) { + cachedResp = cache.get(url); + if (isDefined(cachedResp)) { + if (isPromiseLike(cachedResp)) { + // cached request has already been sent, but there is no response yet + cachedResp.then(removePendingReq, removePendingReq); + return cachedResp; + } else { + // serving from cache + if (isArray(cachedResp)) { + resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]); + } else { + resolvePromise(cachedResp, 200, {}, 'OK'); + } + } + } else { + // put the promise for the non-transformed response into cache as a placeholder + cache.put(url, promise); + } + } + + + // if we won't have the response in cache, set the xsrf headers and + // send the request to the backend + if (isUndefined(cachedResp)) { + var xsrfValue = urlIsSameOrigin(config.url) + ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + } + + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, + config.withCredentials, config.responseType); + } + + return promise; + + + /** + * Callback registered to $httpBackend(): + * - caches the response if desired + * - resolves the raw $http promise + * - calls $apply + */ + function done(status, response, headersString, statusText) { + if (cache) { + if (isSuccess(status)) { + cache.put(url, [status, response, parseHeaders(headersString), statusText]); + } else { + // remove promise from the cache + cache.remove(url); + } + } + + resolvePromise(response, status, headersString, statusText); + if (!$rootScope.$$phase) $rootScope.$apply(); + } + + + /** + * Resolves the raw $http promise. + */ + function resolvePromise(response, status, headers, statusText) { + // normalize internal statuses to 0 + status = Math.max(status, 0); + + (isSuccess(status) ? deferred.resolve : deferred.reject)({ + data: response, + status: status, + headers: headersGetter(headers), + config: config, + statusText : statusText + }); + } + + + function removePendingReq() { + var idx = indexOf($http.pendingRequests, config); + if (idx !== -1) $http.pendingRequests.splice(idx, 1); + } + } + + + function buildUrl(url, params) { + if (!params) return url; + var parts = []; + forEachSorted(params, function(value, key) { + if (value === null || isUndefined(value)) return; + if (!isArray(value)) value = [value]; + + forEach(value, function(v) { + if (isObject(v)) { + if (isDate(v)){ + v = v.toISOString(); + } else { + v = toJson(v); + } + } + parts.push(encodeUriQuery(key) + '=' + + encodeUriQuery(v)); + }); + }); + if(parts.length > 0) { + url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + } + return url; + } + }]; +} + +function createXhr(method) { + //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest + //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest + //if it is available + if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) || + !window.XMLHttpRequest)) { + return new window.ActiveXObject("Microsoft.XMLHTTP"); + } else if (window.XMLHttpRequest) { + return new window.XMLHttpRequest(); + } + + throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); +} + +/** + * @ngdoc service + * @name $httpBackend + * @requires $window + * @requires $document + * + * @description + * HTTP backend used by the {@link ng.$http service} that delegates to + * XMLHttpRequest object or JSONP and deals with browser incompatibilities. + * + * You should never need to use this service directly, instead use the higher-level abstractions: + * {@link ng.$http $http} or {@link ngResource.$resource $resource}. + * + * During testing this implementation is swapped with {@link ngMock.$httpBackend mock + * $httpBackend} which can be trained with responses. + */ +function $HttpBackendProvider() { + this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { + return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); + }]; +} + +function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { + var ABORTED = -1; + + // TODO(vojta): fix the signature + return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { + var status; + $browser.$$incOutstandingRequestCount(); + url = url || $browser.url(); + + if (lowercase(method) == 'jsonp') { + var callbackId = '_' + (callbacks.counter++).toString(36); + callbacks[callbackId] = function(data) { + callbacks[callbackId].data = data; + callbacks[callbackId].called = true; + }; + + var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), + callbackId, function(status, text) { + completeRequest(callback, status, callbacks[callbackId].data, "", text); + callbacks[callbackId] = noop; + }); + } else { + + var xhr = createXhr(method); + + xhr.open(method, url, true); + forEach(headers, function(value, key) { + if (isDefined(value)) { + xhr.setRequestHeader(key, value); + } + }); + + // In IE6 and 7, this might be called synchronously when xhr.send below is called and the + // response is in the cache. the promise api will ensure that to the app code the api is + // always async + xhr.onreadystatechange = function() { + // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by + // xhrs that are resolved while the app is in the background (see #5426). + // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before + // continuing + // + // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and + // Safari respectively. + if (xhr && xhr.readyState == 4) { + var responseHeaders = null, + response = null, + statusText = ''; + + if(status !== ABORTED) { + responseHeaders = xhr.getAllResponseHeaders(); + + // responseText is the old-school way of retrieving response (supported by IE8 & 9) + // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) + response = ('response' in xhr) ? xhr.response : xhr.responseText; + } + + // Accessing statusText on an aborted xhr object will + // throw an 'c00c023f error' in IE9 and lower, don't touch it. + if (!(status === ABORTED && msie < 10)) { + statusText = xhr.statusText; + } + + completeRequest(callback, + status || xhr.status, + response, + responseHeaders, + statusText); + } + }; + + if (withCredentials) { + xhr.withCredentials = true; + } + + if (responseType) { + try { + xhr.responseType = responseType; + } catch (e) { + // WebKit added support for the json responseType value on 09/03/2013 + // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are + // known to throw when setting the value "json" as the response type. Other older + // browsers implementing the responseType + // + // The json response type can be ignored if not supported, because JSON payloads are + // parsed on the client-side regardless. + if (responseType !== 'json') { + throw e; + } + } + } + + xhr.send(post || null); + } + + if (timeout > 0) { + var timeoutId = $browserDefer(timeoutRequest, timeout); + } else if (isPromiseLike(timeout)) { + timeout.then(timeoutRequest); + } + + + function timeoutRequest() { + status = ABORTED; + jsonpDone && jsonpDone(); + xhr && xhr.abort(); + } + + function completeRequest(callback, status, response, headersString, statusText) { + // cancel timeout and subsequent timeout promise resolution + timeoutId && $browserDefer.cancel(timeoutId); + jsonpDone = xhr = null; + + // fix status code when it is 0 (0 status is undocumented). + // Occurs when accessing file resources or on Android 4.1 stock browser + // while retrieving files from application cache. + if (status === 0) { + status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; + } + + // normalize IE bug (http://bugs.jquery.com/ticket/1450) + status = status === 1223 ? 204 : status; + statusText = statusText || ''; + + callback(status, response, headersString, statusText); + $browser.$$completeOutstandingRequest(noop); + } + }; + + function jsonpReq(url, callbackId, done) { + // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: + // - fetches local scripts via XHR and evals them + // - adds and immediately removes script elements from the document + var script = rawDocument.createElement('script'), callback = null; + script.type = "text/javascript"; + script.src = url; + script.async = true; + + callback = function(event) { + removeEventListenerFn(script, "load", callback); + removeEventListenerFn(script, "error", callback); + rawDocument.body.removeChild(script); + script = null; + var status = -1; + var text = "unknown"; + + if (event) { + if (event.type === "load" && !callbacks[callbackId].called) { + event = { type: "error" }; + } + text = event.type; + status = event.type === "error" ? 404 : 200; + } + + if (done) { + done(status, text); + } + }; + + addEventListenerFn(script, "load", callback); + addEventListenerFn(script, "error", callback); + + if (msie <= 8) { + script.onreadystatechange = function() { + if (isString(script.readyState) && /loaded|complete/.test(script.readyState)) { + script.onreadystatechange = null; + callback({ + type: 'load' + }); + } + }; + } + + rawDocument.body.appendChild(script); + return callback; + } +} + +var $interpolateMinErr = minErr('$interpolate'); + +/** + * @ngdoc provider + * @name $interpolateProvider + * @kind function + * + * @description + * + * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. + * + * @example + + + +
+ //demo.label// +
+
+ + it('should interpolate binding with custom symbols', function() { + expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); + }); + +
+ */ +function $InterpolateProvider() { + var startSymbol = '{{'; + var endSymbol = '}}'; + + /** + * @ngdoc method + * @name $interpolateProvider#startSymbol + * @description + * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. + * + * @param {string=} value new value to set the starting symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.startSymbol = function(value){ + if (value) { + startSymbol = value; + return this; + } else { + return startSymbol; + } + }; + + /** + * @ngdoc method + * @name $interpolateProvider#endSymbol + * @description + * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. + * + * @param {string=} value new value to set the ending symbol to. + * @returns {string|self} Returns the symbol when used as getter and self if used as setter. + */ + this.endSymbol = function(value){ + if (value) { + endSymbol = value; + return this; + } else { + return endSymbol; + } + }; + + + this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { + var startSymbolLength = startSymbol.length, + endSymbolLength = endSymbol.length; + + /** + * @ngdoc service + * @name $interpolate + * @kind function + * + * @requires $parse + * @requires $sce + * + * @description + * + * Compiles a string with markup into an interpolation function. This service is used by the + * HTML {@link ng.$compile $compile} service for data binding. See + * {@link ng.$interpolateProvider $interpolateProvider} for configuring the + * interpolation markup. + * + * + * ```js + * var $interpolate = ...; // injected + * var exp = $interpolate('Hello {{name | uppercase}}!'); + * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); + * ``` + * + * + * @param {string} text The text with markup to interpolate. + * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have + * embedded expression in order to return an interpolation function. Strings with no + * embedded expression will return null for the interpolation function. + * @param {string=} trustedContext when provided, the returned function passes the interpolated + * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, + * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that + * provides Strict Contextual Escaping for details. + * @returns {function(context)} an interpolation function which is used to compute the + * interpolated string. The function has these parameters: + * + * * `context`: an object against which any expressions embedded in the strings are evaluated + * against. + * + */ + function $interpolate(text, mustHaveExpression, trustedContext) { + var startIndex, + endIndex, + index = 0, + parts = [], + length = text.length, + hasInterpolation = false, + fn, + exp, + concat = []; + + while(index < length) { + if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && + ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { + (index != startIndex) && parts.push(text.substring(index, startIndex)); + parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); + fn.exp = exp; + index = endIndex + endSymbolLength; + hasInterpolation = true; + } else { + // we did not find anything, so we have to add the remainder to the parts array + (index != length) && parts.push(text.substring(index)); + index = length; + } + } + + if (!(length = parts.length)) { + // we added, nothing, must have been an empty string. + parts.push(''); + length = 1; + } + + // Concatenating expressions makes it hard to reason about whether some combination of + // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a + // single expression be used for iframe[src], object[src], etc., we ensure that the value + // that's used is assigned or constructed by some JS code somewhere that is more testable or + // make it obvious that you bound the value to some user controlled value. This helps reduce + // the load when auditing for XSS issues. + if (trustedContext && parts.length > 1) { + throw $interpolateMinErr('noconcat', + "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + + "interpolations that concatenate multiple expressions when a trusted value is " + + "required. See http://docs.angularjs.org/api/ng.$sce", text); + } + + if (!mustHaveExpression || hasInterpolation) { + concat.length = length; + fn = function(context) { + try { + for(var i = 0, ii = length, part; i + * **Note**: Intervals created by this service must be explicitly destroyed when you are finished + * with them. In particular they are not automatically destroyed when a controller's scope or a + * directive's element are destroyed. + * You should take this into consideration and make sure to always cancel the interval at the + * appropriate moment. See the example below for more details on how and when to do this. + * + * + * @param {function()} fn A function that should be called repeatedly. + * @param {number} delay Number of milliseconds between each function call. + * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat + * indefinitely. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @returns {promise} A promise which will be notified on each iteration. + * + * @example + * + * + * + * + *
+ *
+ * Date format:
+ * Current time is: + *
+ * Blood 1 : {{blood_1}} + * Blood 2 : {{blood_2}} + * + * + * + *
+ *
+ * + *
+ *
+ */ + function interval(fn, delay, count, invokeApply) { + var setInterval = $window.setInterval, + clearInterval = $window.clearInterval, + deferred = $q.defer(), + promise = deferred.promise, + iteration = 0, + skipApply = (isDefined(invokeApply) && !invokeApply); + + count = isDefined(count) ? count : 0; + + promise.then(null, null, fn); + + promise.$$intervalId = setInterval(function tick() { + deferred.notify(iteration++); + + if (count > 0 && iteration >= count) { + deferred.resolve(iteration); + clearInterval(promise.$$intervalId); + delete intervals[promise.$$intervalId]; + } + + if (!skipApply) $rootScope.$apply(); + + }, delay); + + intervals[promise.$$intervalId] = deferred; + + return promise; + } + + + /** + * @ngdoc method + * @name $interval#cancel + * + * @description + * Cancels a task associated with the `promise`. + * + * @param {promise} promise returned by the `$interval` function. + * @returns {boolean} Returns `true` if the task was successfully canceled. + */ + interval.cancel = function(promise) { + if (promise && promise.$$intervalId in intervals) { + intervals[promise.$$intervalId].reject('canceled'); + $window.clearInterval(promise.$$intervalId); + delete intervals[promise.$$intervalId]; + return true; + } + return false; + }; + + return interval; + }]; +} + +/** + * @ngdoc service + * @name $locale + * + * @description + * $locale service provides localization rules for various Angular components. As of right now the + * only public api is: + * + * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + */ +function $LocaleProvider(){ + this.$get = function() { + return { + id: 'en-us', + + NUMBER_FORMATS: { + DECIMAL_SEP: '.', + GROUP_SEP: ',', + PATTERNS: [ + { // Decimal Pattern + minInt: 1, + minFrac: 0, + maxFrac: 3, + posPre: '', + posSuf: '', + negPre: '-', + negSuf: '', + gSize: 3, + lgSize: 3 + },{ //Currency Pattern + minInt: 1, + minFrac: 2, + maxFrac: 2, + posPre: '\u00A4', + posSuf: '', + negPre: '(\u00A4', + negSuf: ')', + gSize: 3, + lgSize: 3 + } + ], + CURRENCY_SYM: '$' + }, + + DATETIME_FORMATS: { + MONTH: + 'January,February,March,April,May,June,July,August,September,October,November,December' + .split(','), + SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), + DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), + SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), + AMPMS: ['AM','PM'], + medium: 'MMM d, y h:mm:ss a', + short: 'M/d/yy h:mm a', + fullDate: 'EEEE, MMMM d, y', + longDate: 'MMMM d, y', + mediumDate: 'MMM d, y', + shortDate: 'M/d/yy', + mediumTime: 'h:mm:ss a', + shortTime: 'h:mm a' + }, + + pluralCat: function(num) { + if (num === 1) { + return 'one'; + } + return 'other'; + } + }; + }; +} + +var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, + DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; +var $locationMinErr = minErr('$location'); + + +/** + * Encode path using encodeUriSegment, ignoring forward slashes + * + * @param {string} path Path to encode + * @returns {string} + */ +function encodePath(path) { + var segments = path.split('/'), + i = segments.length; + + while (i--) { + segments[i] = encodeUriSegment(segments[i]); + } + + return segments.join('/'); +} + +function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { + var parsedUrl = urlResolve(absoluteUrl, appBase); + + locationObj.$$protocol = parsedUrl.protocol; + locationObj.$$host = parsedUrl.hostname; + locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; +} + + +function parseAppUrl(relativeUrl, locationObj, appBase) { + var prefixed = (relativeUrl.charAt(0) !== '/'); + if (prefixed) { + relativeUrl = '/' + relativeUrl; + } + var match = urlResolve(relativeUrl, appBase); + locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? + match.pathname.substring(1) : match.pathname); + locationObj.$$search = parseKeyValue(match.search); + locationObj.$$hash = decodeURIComponent(match.hash); + + // make sure path starts with '/'; + if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { + locationObj.$$path = '/' + locationObj.$$path; + } +} + + +/** + * + * @param {string} begin + * @param {string} whole + * @returns {string} returns text from whole after begin or undefined if it does not begin with + * expected string. + */ +function beginsWith(begin, whole) { + if (whole.indexOf(begin) === 0) { + return whole.substr(begin.length); + } +} + + +function stripHash(url) { + var index = url.indexOf('#'); + return index == -1 ? url : url.substr(0, index); +} + + +function stripFile(url) { + return url.substr(0, stripHash(url).lastIndexOf('/') + 1); +} + +/* return the server only (scheme://host:port) */ +function serverBase(url) { + return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); +} + + +/** + * LocationHtml5Url represents an url + * This object is exposed as $location service when HTML5 mode is enabled and supported + * + * @constructor + * @param {string} appBase application base URL + * @param {string} basePrefix url path prefix + */ +function LocationHtml5Url(appBase, basePrefix) { + this.$$html5 = true; + basePrefix = basePrefix || ''; + var appBaseNoFile = stripFile(appBase); + parseAbsoluteUrl(appBase, this, appBase); + + + /** + * Parse given html5 (regular) url string into properties + * @param {string} newAbsoluteUrl HTML5 url + * @private + */ + this.$$parse = function(url) { + var pathUrl = beginsWith(appBaseNoFile, url); + if (!isString(pathUrl)) { + throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, + appBaseNoFile); + } + + parseAppUrl(pathUrl, this, appBase); + + if (!this.$$path) { + this.$$path = '/'; + } + + this.$$compose(); + }; + + /** + * Compose url and update `absUrl` property + * @private + */ + this.$$compose = function() { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; + + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' + }; + + this.$$parseLinkUrl = function(url, relHref) { + var appUrl, prevAppUrl; + var rewrittenUrl; + + if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { + prevAppUrl = appUrl; + if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { + rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl); + } else { + rewrittenUrl = appBase + prevAppUrl; + } + } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { + rewrittenUrl = appBaseNoFile + appUrl; + } else if (appBaseNoFile == url + '/') { + rewrittenUrl = appBaseNoFile; + } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); + } + return !!rewrittenUrl; + }; +} + + +/** + * LocationHashbangUrl represents url + * This object is exposed as $location service when developer doesn't opt into html5 mode. + * It also serves as the base class for html5 mode fallback on legacy browsers. + * + * @constructor + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix + */ +function LocationHashbangUrl(appBase, hashPrefix) { + var appBaseNoFile = stripFile(appBase); + + parseAbsoluteUrl(appBase, this, appBase); + + + /** + * Parse given hashbang url into properties + * @param {string} url Hashbang url + * @private + */ + this.$$parse = function(url) { + var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); + var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' + ? beginsWith(hashPrefix, withoutBaseUrl) + : (this.$$html5) + ? withoutBaseUrl + : ''; + + if (!isString(withoutHashUrl)) { + throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, + hashPrefix); + } + parseAppUrl(withoutHashUrl, this, appBase); + + this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); + + this.$$compose(); + + /* + * In Windows, on an anchor node on documents loaded from + * the filesystem, the browser will return a pathname + * prefixed with the drive name ('/C:/path') when a + * pathname without a drive is set: + * * a.setAttribute('href', '/foo') + * * a.pathname === '/C:/foo' //true + * + * Inside of Angular, we're always using pathnames that + * do not include drive names for routing. + */ + function removeWindowsDriveName (path, url, base) { + /* + Matches paths for file protocol on windows, + such as /C:/foo/bar, and captures only /foo/bar. + */ + var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; + + var firstPathSegmentMatch; + + //Get the relative path from the input URL. + if (url.indexOf(base) === 0) { + url = url.replace(base, ''); + } + + // The input URL intentionally contains a first path segment that ends with a colon. + if (windowsFilePathExp.exec(url)) { + return path; + } + + firstPathSegmentMatch = windowsFilePathExp.exec(path); + return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; + } + }; + + /** + * Compose hashbang url and update `absUrl` property + * @private + */ + this.$$compose = function() { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; + + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); + }; + + this.$$parseLinkUrl = function(url, relHref) { + if(stripHash(appBase) == stripHash(url)) { + this.$$parse(url); + return true; + } + return false; + }; +} + + +/** + * LocationHashbangUrl represents url + * This object is exposed as $location service when html5 history api is enabled but the browser + * does not support it. + * + * @constructor + * @param {string} appBase application base URL + * @param {string} hashPrefix hashbang prefix + */ +function LocationHashbangInHtml5Url(appBase, hashPrefix) { + this.$$html5 = true; + LocationHashbangUrl.apply(this, arguments); + + var appBaseNoFile = stripFile(appBase); + + this.$$parseLinkUrl = function(url, relHref) { + var rewrittenUrl; + var appUrl; + + if ( appBase == stripHash(url) ) { + rewrittenUrl = url; + } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { + rewrittenUrl = appBase + hashPrefix + appUrl; + } else if ( appBaseNoFile === url + '/') { + rewrittenUrl = appBaseNoFile; + } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); + } + return !!rewrittenUrl; + }; + + this.$$compose = function() { + var search = toKeyValue(this.$$search), + hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; + + this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; + // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' + this.$$absUrl = appBase + hashPrefix + this.$$url; + }; + +} + + +LocationHashbangInHtml5Url.prototype = + LocationHashbangUrl.prototype = + LocationHtml5Url.prototype = { + + /** + * Are we in html5 mode? + * @private + */ + $$html5: false, + + /** + * Has any change been replacing ? + * @private + */ + $$replace: false, + + /** + * @ngdoc method + * @name $location#absUrl + * + * @description + * This method is getter only. + * + * Return full url representation with all segments encoded according to rules specified in + * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). + * + * @return {string} full url + */ + absUrl: locationGetter('$$absUrl'), + + /** + * @ngdoc method + * @name $location#url + * + * @description + * This method is getter / setter. + * + * Return url (e.g. `/path?a=b#hash`) when called without any parameter. + * + * Change path, search and hash, when called with parameter and return `$location`. + * + * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) + * @return {string} url + */ + url: function(url) { + if (isUndefined(url)) + return this.$$url; + + var match = PATH_MATCH.exec(url); + if (match[1]) this.path(decodeURIComponent(match[1])); + if (match[2] || match[1]) this.search(match[3] || ''); + this.hash(match[5] || ''); + + return this; + }, + + /** + * @ngdoc method + * @name $location#protocol + * + * @description + * This method is getter only. + * + * Return protocol of current url. + * + * @return {string} protocol of current url + */ + protocol: locationGetter('$$protocol'), + + /** + * @ngdoc method + * @name $location#host + * + * @description + * This method is getter only. + * + * Return host of current url. + * + * @return {string} host of current url. + */ + host: locationGetter('$$host'), + + /** + * @ngdoc method + * @name $location#port + * + * @description + * This method is getter only. + * + * Return port of current url. + * + * @return {Number} port + */ + port: locationGetter('$$port'), + + /** + * @ngdoc method + * @name $location#path + * + * @description + * This method is getter / setter. + * + * Return path of current url when called without any parameter. + * + * Change path when called with parameter and return `$location`. + * + * Note: Path should always begin with forward slash (/), this method will add the forward slash + * if it is missing. + * + * @param {(string|number)=} path New path + * @return {string} path + */ + path: locationGetterSetter('$$path', function(path) { + path = path !== null ? path.toString() : ''; + return path.charAt(0) == '/' ? path : '/' + path; + }), + + /** + * @ngdoc method + * @name $location#search + * + * @description + * This method is getter / setter. + * + * Return search part (as object) of current url when called without any parameter. + * + * Change search part when called with parameter and return `$location`. + * + * + * ```js + * // given url http://example.com/#/some/path?foo=bar&baz=xoxo + * var searchObject = $location.search(); + * // => {foo: 'bar', baz: 'xoxo'} + * + * + * // set foo to 'yipee' + * $location.search('foo', 'yipee'); + * // => $location + * ``` + * + * @param {string|Object.|Object.>} search New search params - string or + * hash object. + * + * When called with a single argument the method acts as a setter, setting the `search` component + * of `$location` to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded + * as duplicate search parameters in the url. + * + * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue` + * will override only a single search property. + * + * If `paramValue` is an array, it will override the property of the `search` component of + * `$location` specified via the first argument. + * + * If `paramValue` is `null`, the property specified via the first argument will be deleted. + * + * If `paramValue` is `true`, the property specified via the first argument will be added with no + * value nor trailing equal sign. + * + * @return {Object} If called with no arguments returns the parsed `search` object. If called with + * one or more arguments returns `$location` object itself. + */ + search: function(search, paramValue) { + switch (arguments.length) { + case 0: + return this.$$search; + case 1: + if (isString(search) || isNumber(search)) { + search = search.toString(); + this.$$search = parseKeyValue(search); + } else if (isObject(search)) { + // remove object undefined or null properties + forEach(search, function(value, key) { + if (value == null) delete search[key]; + }); + + this.$$search = search; + } else { + throw $locationMinErr('isrcharg', + 'The first argument of the `$location#search()` call must be a string or an object.'); + } + break; + default: + if (isUndefined(paramValue) || paramValue === null) { + delete this.$$search[search]; + } else { + this.$$search[search] = paramValue; + } + } + + this.$$compose(); + return this; + }, + + /** + * @ngdoc method + * @name $location#hash + * + * @description + * This method is getter / setter. + * + * Return hash fragment when called without any parameter. + * + * Change hash fragment when called with parameter and return `$location`. + * + * @param {(string|number)=} hash New hash fragment + * @return {string} hash + */ + hash: locationGetterSetter('$$hash', function(hash) { + return hash !== null ? hash.toString() : ''; + }), + + /** + * @ngdoc method + * @name $location#replace + * + * @description + * If called, all changes to $location during current `$digest` will be replacing current history + * record, instead of adding new one. + */ + replace: function() { + this.$$replace = true; + return this; + } +}; + +function locationGetter(property) { + return function() { + return this[property]; + }; +} + + +function locationGetterSetter(property, preprocess) { + return function(value) { + if (isUndefined(value)) + return this[property]; + + this[property] = preprocess(value); + this.$$compose(); + + return this; + }; +} + + +/** + * @ngdoc service + * @name $location + * + * @requires $rootElement + * + * @description + * The $location service parses the URL in the browser address bar (based on the + * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL + * available to your application. Changes to the URL in the address bar are reflected into + * $location service and changes to $location are reflected into the browser address bar. + * + * **The $location service:** + * + * - Exposes the current URL in the browser address bar, so you can + * - Watch and observe the URL. + * - Change the URL. + * - Synchronizes the URL with the browser when the user + * - Changes the address bar. + * - Clicks the back or forward button (or clicks a History link). + * - Clicks on a link. + * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). + * + * For more information see {@link guide/$location Developer Guide: Using $location} + */ + +/** + * @ngdoc provider + * @name $locationProvider + * @description + * Use the `$locationProvider` to configure how the application deep linking paths are stored. + */ +function $LocationProvider(){ + var hashPrefix = '', + html5Mode = false; + + /** + * @ngdoc method + * @name $locationProvider#hashPrefix + * @description + * @param {string=} prefix Prefix for hash part (containing path and search) + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.hashPrefix = function(prefix) { + if (isDefined(prefix)) { + hashPrefix = prefix; + return this; + } else { + return hashPrefix; + } + }; + + /** + * @ngdoc method + * @name $locationProvider#html5Mode + * @description + * @param {boolean=} mode Use HTML5 strategy if available. + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.html5Mode = function(mode) { + if (isDefined(mode)) { + html5Mode = mode; + return this; + } else { + return html5Mode; + } + }; + + /** + * @ngdoc event + * @name $location#$locationChangeStart + * @eventType broadcast on root scope + * @description + * Broadcasted before a URL will change. This change can be prevented by calling + * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more + * details about event object. Upon successful change + * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired. + * + * @param {Object} angularEvent Synthetic event object. + * @param {string} newUrl New URL + * @param {string=} oldUrl URL that was before it was changed. + */ + + /** + * @ngdoc event + * @name $location#$locationChangeSuccess + * @eventType broadcast on root scope + * @description + * Broadcasted after a URL was changed. + * + * @param {Object} angularEvent Synthetic event object. + * @param {string} newUrl New URL + * @param {string=} oldUrl URL that was before it was changed. + */ + + this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', + function( $rootScope, $browser, $sniffer, $rootElement) { + var $location, + LocationMode, + baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' + initialUrl = $browser.url(), + appBase; + + if (html5Mode) { + appBase = serverBase(initialUrl) + (baseHref || '/'); + LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; + } else { + appBase = stripHash(initialUrl); + LocationMode = LocationHashbangUrl; + } + $location = new LocationMode(appBase, '#' + hashPrefix); + $location.$$parseLinkUrl(initialUrl, initialUrl); + + var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; + + $rootElement.on('click', function(event) { + // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) + // currently we open nice url link and redirect then + + if (event.ctrlKey || event.metaKey || event.which == 2) return; + + var elm = jqLite(event.target); + + // traverse the DOM up to find first A tag + while (lowercase(elm[0].nodeName) !== 'a') { + // ignore rewriting if no A tag (reached root element, or no parent - removed from document) + if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; + } + + var absHref = elm.prop('href'); + // get the actual href attribute - see + // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx + var relHref = elm.attr('href') || elm.attr('xlink:href'); + + if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { + // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during + // an animation. + absHref = urlResolve(absHref.animVal).href; + } + + // Ignore when url is started with javascript: or mailto: + if (IGNORE_URI_REGEXP.test(absHref)) return; + + if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { + if ($location.$$parseLinkUrl(absHref, relHref)) { + // We do a preventDefault for all urls that are part of the angular application, + // in html5mode and also without, so that we are able to abort navigation without + // getting double entries in the location history. + event.preventDefault(); + // update location manually + if ($location.absUrl() != $browser.url()) { + $rootScope.$apply(); + // hack to work around FF6 bug 684208 when scenario runner clicks on links + window.angular['ff-684208-preventDefault'] = true; + } + } + } + }); + + + // rewrite hashbang url <> html5 url + if ($location.absUrl() != initialUrl) { + $browser.url(https://github.com/$location.absUrl(), true); + } + + // update $location when $browser url changes + $browser.onUrlChange(function(newUrl) { + if ($location.absUrl() != newUrl) { + $rootScope.$evalAsync(function() { + var oldUrl = $location.absUrl(); + + $location.$$parse(newUrl); + if ($rootScope.$broadcast('$locationChangeStart', newUrl, + oldUrl).defaultPrevented) { + $location.$$parse(oldUrl); + $browser.url(https://github.com/oldUrl); + } else { + afterLocationChange(oldUrl); + } + }); + if (!$rootScope.$$phase) $rootScope.$digest(); + } + }); + + // update browser + var changeCounter = 0; + $rootScope.$watch(function $locationWatch() { + var oldUrl = $browser.url(); + var currentReplace = $location.$$replace; + + if (!changeCounter || oldUrl != $location.absUrl()) { + changeCounter++; + $rootScope.$evalAsync(function() { + if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). + defaultPrevented) { + $location.$$parse(oldUrl); + } else { + $browser.url(https://github.com/$location.absUrl(), currentReplace); + afterLocationChange(oldUrl); + } + }); + } + $location.$$replace = false; + + return changeCounter; + }); + + return $location; + + function afterLocationChange(oldUrl) { + $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); + } +}]; +} + +/** + * @ngdoc service + * @name $log + * @requires $window + * + * @description + * Simple service for logging. Default implementation safely writes the message + * into the browser's console (if present). + * + * The main purpose of this service is to simplify debugging and troubleshooting. + * + * The default is to log `debug` messages. You can use + * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. + * + * @example + + + angular.module('logExample', []) + .controller('LogController', ['$scope', '$log', function($scope, $log) { + $scope.$log = $log; + $scope.message = 'Hello World!'; + }]); + + +
+

Reload this page with open console, enter text and hit the log button...

+ Message: + + + + + +
+
+
+ */ + +/** + * @ngdoc provider + * @name $logProvider + * @description + * Use the `$logProvider` to configure how the application logs messages + */ +function $LogProvider(){ + var debug = true, + self = this; + + /** + * @ngdoc method + * @name $logProvider#debugEnabled + * @description + * @param {boolean=} flag enable or disable debug level messages + * @returns {*} current value if used as getter or itself (chaining) if used as setter + */ + this.debugEnabled = function(flag) { + if (isDefined(flag)) { + debug = flag; + return this; + } else { + return debug; + } + }; + + this.$get = ['$window', function($window){ + return { + /** + * @ngdoc method + * @name $log#log + * + * @description + * Write a log message + */ + log: consoleLog('log'), + + /** + * @ngdoc method + * @name $log#info + * + * @description + * Write an information message + */ + info: consoleLog('info'), + + /** + * @ngdoc method + * @name $log#warn + * + * @description + * Write a warning message + */ + warn: consoleLog('warn'), + + /** + * @ngdoc method + * @name $log#error + * + * @description + * Write an error message + */ + error: consoleLog('error'), + + /** + * @ngdoc method + * @name $log#debug + * + * @description + * Write a debug message + */ + debug: (function () { + var fn = consoleLog('debug'); + + return function() { + if (debug) { + fn.apply(self, arguments); + } + }; + }()) + }; + + function formatError(arg) { + if (arg instanceof Error) { + if (arg.stack) { + arg = (arg.message && arg.stack.indexOf(arg.message) === -1) + ? 'Error: ' + arg.message + '\n' + arg.stack + : arg.stack; + } else if (arg.sourceURL) { + arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; + } + } + return arg; + } + + function consoleLog(type) { + var console = $window.console || {}, + logFn = console[type] || console.log || noop, + hasApply = false; + + // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. + // The reason behind this is that console.log has type "object" in IE8... + try { + hasApply = !!logFn.apply; + } catch (e) {} + + if (hasApply) { + return function() { + var args = []; + forEach(arguments, function(arg) { + args.push(formatError(arg)); + }); + return logFn.apply(console, args); + }; + } + + // we are IE which either doesn't have window.console => this is noop and we do nothing, + // or we are IE where console.log doesn't have apply so we log at least first 2 args + return function(arg1, arg2) { + logFn(arg1, arg2 == null ? '' : arg2); + }; + } + }]; +} + +var $parseMinErr = minErr('$parse'); +var promiseWarningCache = {}; +var promiseWarning; + +// Sandboxing Angular Expressions +// ------------------------------ +// Angular expressions are generally considered safe because these expressions only have direct +// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by +// obtaining a reference to native JS functions such as the Function constructor. +// +// As an example, consider the following Angular expression: +// +// {}.toString.constructor('alert("evil JS code")') +// +// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits +// against the expression language, but not to prevent exploits that were enabled by exposing +// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good +// practice and therefore we are not even trying to protect against interaction with an object +// explicitly exposed in this way. +// +// In general, it is not possible to access a Window object from an angular expression unless a +// window or some DOM object that has a reference to window is published onto a Scope. +// Similarly we prevent invocations of function known to be dangerous, as well as assignments to +// native objects. +// +// See https://docs.angularjs.org/guide/security + + +function ensureSafeMemberName(name, fullExpression) { + if (name === "__defineGetter__" || name === "__defineSetter__" + || name === "__lookupGetter__" || name === "__lookupSetter__" + || name === "__proto__") { + throw $parseMinErr('isecfld', + 'Attempting to access a disallowed field in Angular expressions! ' + +'Expression: {0}', fullExpression); + } + return name; +} + +function ensureSafeObject(obj, fullExpression) { + // nifty check if obj is Function that is fast and works across iframes and other contexts + if (obj) { + if (obj.constructor === obj) { + throw $parseMinErr('isecfn', + 'Referencing Function in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// isWindow(obj) + obj.document && obj.location && obj.alert && obj.setInterval) { + throw $parseMinErr('isecwindow', + 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// isElement(obj) + obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { + throw $parseMinErr('isecdom', + 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (// block Object so that we can't get hold of dangerous Object.* methods + obj === Object) { + throw $parseMinErr('isecobj', + 'Referencing Object in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } + } + return obj; +} + +var CALL = Function.prototype.call; +var APPLY = Function.prototype.apply; +var BIND = Function.prototype.bind; + +function ensureSafeFunction(obj, fullExpression) { + if (obj) { + if (obj.constructor === obj) { + throw $parseMinErr('isecfn', + 'Referencing Function in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) { + throw $parseMinErr('isecff', + 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}', + fullExpression); + } + } +} + +var OPERATORS = { + /* jshint bitwise : false */ + 'null':function(){return null;}, + 'true':function(){return true;}, + 'false':function(){return false;}, + undefined:noop, + '+':function(self, locals, a,b){ + a=a(self, locals); b=b(self, locals); + if (isDefined(a)) { + if (isDefined(b)) { + return a + b; + } + return a; + } + return isDefined(b)?b:undefined;}, + '-':function(self, locals, a,b){ + a=a(self, locals); b=b(self, locals); + return (isDefined(a)?a:0)-(isDefined(b)?b:0); + }, + '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, + '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, + '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, + '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, + '=':noop, + '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, + '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, + '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, + '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, + '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, + '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, + '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, + '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, + '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, + '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, +// '|':function(self, locals, a,b){return a|b;}, + '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, + '!':function(self, locals, a){return !a(self, locals);} +}; +/* jshint bitwise: true */ +var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; + + +///////////////////////////////////////// + + +/** + * @constructor + */ +var Lexer = function (options) { + this.options = options; +}; + +Lexer.prototype = { + constructor: Lexer, + + lex: function (text) { + this.text = text; + + this.index = 0; + this.ch = undefined; + this.lastCh = ':'; // can start regexp + + this.tokens = []; + + while (this.index < this.text.length) { + this.ch = this.text.charAt(this.index); + if (this.is('"\'')) { + this.readString(this.ch); + } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) { + this.readNumber(); + } else if (this.isIdent(this.ch)) { + this.readIdent(); + } else if (this.is('(){}[].,;:?')) { + this.tokens.push({ + index: this.index, + text: this.ch + }); + this.index++; + } else if (this.isWhitespace(this.ch)) { + this.index++; + continue; + } else { + var ch2 = this.ch + this.peek(); + var ch3 = ch2 + this.peek(2); + var fn = OPERATORS[this.ch]; + var fn2 = OPERATORS[ch2]; + var fn3 = OPERATORS[ch3]; + if (fn3) { + this.tokens.push({index: this.index, text: ch3, fn: fn3}); + this.index += 3; + } else if (fn2) { + this.tokens.push({index: this.index, text: ch2, fn: fn2}); + this.index += 2; + } else if (fn) { + this.tokens.push({ + index: this.index, + text: this.ch, + fn: fn + }); + this.index += 1; + } else { + this.throwError('Unexpected next character ', this.index, this.index + 1); + } + } + this.lastCh = this.ch; + } + return this.tokens; + }, + + is: function(chars) { + return chars.indexOf(this.ch) !== -1; + }, + + was: function(chars) { + return chars.indexOf(this.lastCh) !== -1; + }, + + peek: function(i) { + var num = i || 1; + return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; + }, + + isNumber: function(ch) { + return ('0' <= ch && ch <= '9'); + }, + + isWhitespace: function(ch) { + // IE treats non-breaking space as \u00A0 + return (ch === ' ' || ch === '\r' || ch === '\t' || + ch === '\n' || ch === '\v' || ch === '\u00A0'); + }, + + isIdent: function(ch) { + return ('a' <= ch && ch <= 'z' || + 'A' <= ch && ch <= 'Z' || + '_' === ch || ch === '$'); + }, + + isExpOperator: function(ch) { + return (ch === '-' || ch === '+' || this.isNumber(ch)); + }, + + throwError: function(error, start, end) { + end = end || this.index; + var colStr = (isDefined(start) + ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' + : ' ' + end); + throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', + error, colStr, this.text); + }, + + readNumber: function() { + var number = ''; + var start = this.index; + while (this.index < this.text.length) { + var ch = lowercase(this.text.charAt(this.index)); + if (ch == '.' || this.isNumber(ch)) { + number += ch; + } else { + var peekCh = this.peek(); + if (ch == 'e' && this.isExpOperator(peekCh)) { + number += ch; + } else if (this.isExpOperator(ch) && + peekCh && this.isNumber(peekCh) && + number.charAt(number.length - 1) == 'e') { + number += ch; + } else if (this.isExpOperator(ch) && + (!peekCh || !this.isNumber(peekCh)) && + number.charAt(number.length - 1) == 'e') { + this.throwError('Invalid exponent'); + } else { + break; + } + } + this.index++; + } + number = 1 * number; + this.tokens.push({ + index: start, + text: number, + literal: true, + constant: true, + fn: function() { return number; } + }); + }, + + readIdent: function() { + var parser = this; + + var ident = ''; + var start = this.index; + + var lastDot, peekIndex, methodName, ch; + + while (this.index < this.text.length) { + ch = this.text.charAt(this.index); + if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) { + if (ch === '.') lastDot = this.index; + ident += ch; + } else { + break; + } + this.index++; + } + + //check if this is not a method invocation and if it is back out to last dot + if (lastDot) { + peekIndex = this.index; + while (peekIndex < this.text.length) { + ch = this.text.charAt(peekIndex); + if (ch === '(') { + methodName = ident.substr(lastDot - start + 1); + ident = ident.substr(0, lastDot - start); + this.index = peekIndex; + break; + } + if (this.isWhitespace(ch)) { + peekIndex++; + } else { + break; + } + } + } + + + var token = { + index: start, + text: ident + }; + + // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn + if (OPERATORS.hasOwnProperty(ident)) { + token.fn = OPERATORS[ident]; + token.literal = true; + token.constant = true; + } else { + var getter = getterFn(ident, this.options, this.text); + token.fn = extend(function(self, locals) { + return (getter(self, locals)); + }, { + assign: function(self, value) { + return setter(self, ident, value, parser.text, parser.options); + } + }); + } + + this.tokens.push(token); + + if (methodName) { + this.tokens.push({ + index:lastDot, + text: '.' + }); + this.tokens.push({ + index: lastDot + 1, + text: methodName + }); + } + }, + + readString: function(quote) { + var start = this.index; + this.index++; + var string = ''; + var rawString = quote; + var escape = false; + while (this.index < this.text.length) { + var ch = this.text.charAt(this.index); + rawString += ch; + if (escape) { + if (ch === 'u') { + var hex = this.text.substring(this.index + 1, this.index + 5); + if (!hex.match(/[\da-f]{4}/i)) + this.throwError('Invalid unicode escape [\\u' + hex + ']'); + this.index += 4; + string += String.fromCharCode(parseInt(hex, 16)); + } else { + var rep = ESCAPE[ch]; + string = string + (rep || ch); + } + escape = false; + } else if (ch === '\\') { + escape = true; + } else if (ch === quote) { + this.index++; + this.tokens.push({ + index: start, + text: rawString, + string: string, + literal: true, + constant: true, + fn: function() { return string; } + }); + return; + } else { + string += ch; + } + this.index++; + } + this.throwError('Unterminated quote', start); + } +}; + + +/** + * @constructor + */ +var Parser = function (lexer, $filter, options) { + this.lexer = lexer; + this.$filter = $filter; + this.options = options; +}; + +Parser.ZERO = extend(function () { + return 0; +}, { + constant: true +}); + +Parser.prototype = { + constructor: Parser, + + parse: function (text) { + this.text = text; + + this.tokens = this.lexer.lex(text); + + var value = this.statements(); + + if (this.tokens.length !== 0) { + this.throwError('is an unexpected token', this.tokens[0]); + } + + value.literal = !!value.literal; + value.constant = !!value.constant; + + return value; + }, + + primary: function () { + var primary; + if (this.expect('(')) { + primary = this.filterChain(); + this.consume(')'); + } else if (this.expect('[')) { + primary = this.arrayDeclaration(); + } else if (this.expect('{')) { + primary = this.object(); + } else { + var token = this.expect(); + primary = token.fn; + if (!primary) { + this.throwError('not a primary expression', token); + } + primary.literal = !!token.literal; + primary.constant = !!token.constant; + } + + var next, context; + while ((next = this.expect('(', '[', '.'))) { + if (next.text === '(') { + primary = this.functionCall(primary, context); + context = null; + } else if (next.text === '[') { + context = primary; + primary = this.objectIndex(primary); + } else if (next.text === '.') { + context = primary; + primary = this.fieldAccess(primary); + } else { + this.throwError('IMPOSSIBLE'); + } + } + return primary; + }, + + throwError: function(msg, token) { + throw $parseMinErr('syntax', + 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', + token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); + }, + + peekToken: function() { + if (this.tokens.length === 0) + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); + return this.tokens[0]; + }, + + peek: function(e1, e2, e3, e4) { + if (this.tokens.length > 0) { + var token = this.tokens[0]; + var t = token.text; + if (t === e1 || t === e2 || t === e3 || t === e4 || + (!e1 && !e2 && !e3 && !e4)) { + return token; + } + } + return false; + }, + + expect: function(e1, e2, e3, e4){ + var token = this.peek(e1, e2, e3, e4); + if (token) { + this.tokens.shift(); + return token; + } + return false; + }, + + consume: function(e1){ + if (!this.expect(e1)) { + this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); + } + }, + + unaryFn: function(fn, right) { + return extend(function(self, locals) { + return fn(self, locals, right); + }, { + constant:right.constant + }); + }, + + ternaryFn: function(left, middle, right){ + return extend(function(self, locals){ + return left(self, locals) ? middle(self, locals) : right(self, locals); + }, { + constant: left.constant && middle.constant && right.constant + }); + }, + + binaryFn: function(left, fn, right) { + return extend(function(self, locals) { + return fn(self, locals, left, right); + }, { + constant:left.constant && right.constant + }); + }, + + statements: function() { + var statements = []; + while (true) { + if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) + statements.push(this.filterChain()); + if (!this.expect(';')) { + // optimize for the common case where there is only one statement. + // TODO(size): maybe we should not support multiple statements? + return (statements.length === 1) + ? statements[0] + : function(self, locals) { + var value; + for (var i = 0; i < statements.length; i++) { + var statement = statements[i]; + if (statement) { + value = statement(self, locals); + } + } + return value; + }; + } + } + }, + + filterChain: function() { + var left = this.expression(); + var token; + while (true) { + if ((token = this.expect('|'))) { + left = this.binaryFn(left, token.fn, this.filter()); + } else { + return left; + } + } + }, + + filter: function() { + var token = this.expect(); + var fn = this.$filter(token.text); + var argsFn = []; + while (true) { + if ((token = this.expect(':'))) { + argsFn.push(this.expression()); + } else { + var fnInvoke = function(self, locals, input) { + var args = [input]; + for (var i = 0; i < argsFn.length; i++) { + args.push(argsFn[i](self, locals)); + } + return fn.apply(self, args); + }; + return function() { + return fnInvoke; + }; + } + } + }, + + expression: function() { + return this.assignment(); + }, + + assignment: function() { + var left = this.ternary(); + var right; + var token; + if ((token = this.expect('='))) { + if (!left.assign) { + this.throwError('implies assignment but [' + + this.text.substring(0, token.index) + '] can not be assigned to', token); + } + right = this.ternary(); + return function(scope, locals) { + return left.assign(scope, right(scope, locals), locals); + }; + } + return left; + }, + + ternary: function() { + var left = this.logicalOR(); + var middle; + var token; + if ((token = this.expect('?'))) { + middle = this.assignment(); + if ((token = this.expect(':'))) { + return this.ternaryFn(left, middle, this.assignment()); + } else { + this.throwError('expected :', token); + } + } else { + return left; + } + }, + + logicalOR: function() { + var left = this.logicalAND(); + var token; + while (true) { + if ((token = this.expect('||'))) { + left = this.binaryFn(left, token.fn, this.logicalAND()); + } else { + return left; + } + } + }, + + logicalAND: function() { + var left = this.equality(); + var token; + if ((token = this.expect('&&'))) { + left = this.binaryFn(left, token.fn, this.logicalAND()); + } + return left; + }, + + equality: function() { + var left = this.relational(); + var token; + if ((token = this.expect('==','!=','===','!=='))) { + left = this.binaryFn(left, token.fn, this.equality()); + } + return left; + }, + + relational: function() { + var left = this.additive(); + var token; + if ((token = this.expect('<', '>', '<=', '>='))) { + left = this.binaryFn(left, token.fn, this.relational()); + } + return left; + }, + + additive: function() { + var left = this.multiplicative(); + var token; + while ((token = this.expect('+','-'))) { + left = this.binaryFn(left, token.fn, this.multiplicative()); + } + return left; + }, + + multiplicative: function() { + var left = this.unary(); + var token; + while ((token = this.expect('*','/','%'))) { + left = this.binaryFn(left, token.fn, this.unary()); + } + return left; + }, + + unary: function() { + var token; + if (this.expect('+')) { + return this.primary(); + } else if ((token = this.expect('-'))) { + return this.binaryFn(Parser.ZERO, token.fn, this.unary()); + } else if ((token = this.expect('!'))) { + return this.unaryFn(token.fn, this.unary()); + } else { + return this.primary(); + } + }, + + fieldAccess: function(object) { + var parser = this; + var field = this.expect().text; + var getter = getterFn(field, this.options, this.text); + + return extend(function(scope, locals, self) { + return getter(self || object(scope, locals)); + }, { + assign: function(scope, value, locals) { + var o = object(scope, locals); + if (!o) object.assign(scope, o = {}); + return setter(o, field, value, parser.text, parser.options); + } + }); + }, + + objectIndex: function(obj) { + var parser = this; + + var indexFn = this.expression(); + this.consume(']'); + + return extend(function(self, locals) { + var o = obj(self, locals), + i = indexFn(self, locals), + v, p; + + ensureSafeMemberName(i, parser.text); + if (!o) return undefined; + v = ensureSafeObject(o[i], parser.text); + if (v && v.then && parser.options.unwrapPromises) { + p = v; + if (!('$$v' in v)) { + p.$$v = undefined; + p.then(function(val) { p.$$v = val; }); + } + v = v.$$v; + } + return v; + }, { + assign: function(self, value, locals) { + var key = ensureSafeMemberName(indexFn(self, locals), parser.text); + // prevent overwriting of Function.constructor which would break ensureSafeObject check + var o = ensureSafeObject(obj(self, locals), parser.text); + if (!o) obj.assign(self, o = {}); + return o[key] = value; + } + }); + }, + + functionCall: function(fn, contextGetter) { + var argsFn = []; + if (this.peekToken().text !== ')') { + do { + argsFn.push(this.expression()); + } while (this.expect(',')); + } + this.consume(')'); + + var parser = this; + + return function(scope, locals) { + var args = []; + var context = contextGetter ? contextGetter(scope, locals) : scope; + + for (var i = 0; i < argsFn.length; i++) { + args.push(ensureSafeObject(argsFn[i](scope, locals), parser.text)); + } + var fnPtr = fn(scope, locals, context) || noop; + + ensureSafeObject(context, parser.text); + ensureSafeFunction(fnPtr, parser.text); + + // IE doesn't have apply for some native functions + var v = fnPtr.apply + ? fnPtr.apply(context, args) + : fnPtr(args[0], args[1], args[2], args[3], args[4]); + + return ensureSafeObject(v, parser.text); + }; + }, + + // This is used with json array declaration + arrayDeclaration: function () { + var elementFns = []; + var allConstant = true; + if (this.peekToken().text !== ']') { + do { + if (this.peek(']')) { + // Support trailing commas per ES5.1. + break; + } + var elementFn = this.expression(); + elementFns.push(elementFn); + if (!elementFn.constant) { + allConstant = false; + } + } while (this.expect(',')); + } + this.consume(']'); + + return extend(function(self, locals) { + var array = []; + for (var i = 0; i < elementFns.length; i++) { + array.push(elementFns[i](self, locals)); + } + return array; + }, { + literal: true, + constant: allConstant + }); + }, + + object: function () { + var keyValues = []; + var allConstant = true; + if (this.peekToken().text !== '}') { + do { + if (this.peek('}')) { + // Support trailing commas per ES5.1. + break; + } + var token = this.expect(), + key = token.string || token.text; + this.consume(':'); + var value = this.expression(); + keyValues.push({key: key, value: value}); + if (!value.constant) { + allConstant = false; + } + } while (this.expect(',')); + } + this.consume('}'); + + return extend(function(self, locals) { + var object = {}; + for (var i = 0; i < keyValues.length; i++) { + var keyValue = keyValues[i]; + object[keyValue.key] = keyValue.value(self, locals); + } + return object; + }, { + literal: true, + constant: allConstant + }); + } +}; + + +////////////////////////////////////////////////// +// Parser helper functions +////////////////////////////////////////////////// + +function setter(obj, path, setValue, fullExp, options) { + ensureSafeObject(obj, fullExp); + + //needed? + options = options || {}; + + var element = path.split('.'), key; + for (var i = 0; element.length > 1; i++) { + key = ensureSafeMemberName(element.shift(), fullExp); + var propertyObj = ensureSafeObject(obj[key], fullExp); + if (!propertyObj) { + propertyObj = {}; + obj[key] = propertyObj; + } + obj = propertyObj; + if (obj.then && options.unwrapPromises) { + promiseWarning(fullExp); + if (!("$$v" in obj)) { + (function(promise) { + promise.then(function(val) { promise.$$v = val; }); } + )(obj); + } + if (obj.$$v === undefined) { + obj.$$v = {}; + } + obj = obj.$$v; + } + } + key = ensureSafeMemberName(element.shift(), fullExp); + ensureSafeObject(obj[key], fullExp); + obj[key] = setValue; + return setValue; +} + +var getterFnCacheDefault = {}; +var getterFnCacheExpensive = {}; + +function isPossiblyDangerousMemberName(name) { + return name == 'constructor'; +} + +/** + * Implementation of the "Black Hole" variant from: + * - http://jsperf.com/angularjs-parse-getter/4 + * - http://jsperf.com/path-evaluation-simplified/7 + */ +function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) { + ensureSafeMemberName(key0, fullExp); + ensureSafeMemberName(key1, fullExp); + ensureSafeMemberName(key2, fullExp); + ensureSafeMemberName(key3, fullExp); + ensureSafeMemberName(key4, fullExp); + var eso = function(o) { + return ensureSafeObject(o, fullExp); + }; + var expensiveChecks = options.expensiveChecks; + var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity; + var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity; + var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity; + var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity; + var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity; + + return !options.unwrapPromises + ? function cspSafeGetter(scope, locals) { + var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; + + if (pathVal == null) return pathVal; + pathVal = eso0(pathVal[key0]); + + if (!key1) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso1(pathVal[key1]); + + if (!key2) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso2(pathVal[key2]); + + if (!key3) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso3(pathVal[key3]); + + if (!key4) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso4(pathVal[key4]); + + return pathVal; + } + : function cspSafePromiseEnabledGetter(scope, locals) { + var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, + promise; + + if (pathVal == null) return pathVal; + + pathVal = eso0(pathVal[key0]); + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = eso0(val); }); + } + pathVal = eso0(pathVal.$$v); + } + + if (!key1) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso1(pathVal[key1]); + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = eso1(val); }); + } + pathVal = eso1(pathVal.$$v); + } + + if (!key2) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso2(pathVal[key2]); + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = eso2(val); }); + } + pathVal = eso2(pathVal.$$v); + } + + if (!key3) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso3(pathVal[key3]); + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = eso3(val); }); + } + pathVal = eso3(pathVal.$$v); + } + + if (!key4) return pathVal; + if (pathVal == null) return undefined; + pathVal = eso4(pathVal[key4]); + if (pathVal && pathVal.then) { + promiseWarning(fullExp); + if (!("$$v" in pathVal)) { + promise = pathVal; + promise.$$v = undefined; + promise.then(function(val) { promise.$$v = eso4(val); }); + } + pathVal = eso4(pathVal.$$v); + } + return pathVal; + }; +} + +function getterFnWithExtraArgs(fn, fullExpression) { + return function(s, l) { + return fn(s, l, promiseWarning, ensureSafeObject, fullExpression); + }; +} + +function getterFn(path, options, fullExp) { + var expensiveChecks = options.expensiveChecks; + var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault); + // Check whether the cache has this getter already. + // We can use hasOwnProperty directly on the cache because we ensure, + // see below, that the cache never stores a path called 'hasOwnProperty' + if (getterFnCache.hasOwnProperty(path)) { + return getterFnCache[path]; + } + + var pathKeys = path.split('.'), + pathKeysLength = pathKeys.length, + fn; + + // http://jsperf.com/angularjs-parse-getter/6 + if (options.csp) { + if (pathKeysLength < 6) { + fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, + options); + } else { + fn = function(scope, locals) { + var i = 0, val; + do { + val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], + pathKeys[i++], fullExp, options)(scope, locals); + + locals = undefined; // clear after first iteration + scope = val; + } while (i < pathKeysLength); + return val; + }; + } + } else { + var code = 'var p;\n'; + if (expensiveChecks) { + code += 's = eso(s, fe);\nl = eso(l, fe);\n'; + } + var needsEnsureSafeObject = expensiveChecks; + forEach(pathKeys, function(key, index) { + ensureSafeMemberName(key, fullExp); + var lookupJs = (index + // we simply dereference 's' on any .dot notation + ? 's' + // but if we are first then we check locals first, and if so read it first + : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '["' + key + '"]'; + var wrapWithEso = expensiveChecks || isPossiblyDangerousMemberName(key); + if (wrapWithEso) { + lookupJs = 'eso(' + lookupJs + ', fe)'; + needsEnsureSafeObject = true; + } + code += 'if(s == null) return undefined;\n' + + 's=' + lookupJs + ';\n'; + if (options.unwrapPromises) { + code += 'if (s && s.then) {\n' + + ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' + + ' if (!("$$v" in s)) {\n' + + ' p=s;\n' + + ' p.$$v = undefined;\n' + + ' p.then(function(v) {p.$$v=' + (wrapWithEso ? 'eso(v)' : 'v') + ';});\n' + + '}\n' + + ' s=' + (wrapWithEso ? 'eso(s.$$v)' : 's.$$v') + '\n' + + '}\n'; + + } + }); + code += 'return s;'; + + /* jshint -W054 */ + // s=scope, l=locals, pw=promiseWarning, eso=ensureSafeObject, fe=fullExpression + var evaledFnGetter = new Function('s', 'l', 'pw', 'eso', 'fe', code); + /* jshint +W054 */ + evaledFnGetter.toString = valueFn(code); + if (needsEnsureSafeObject || options.unwrapPromises) { + evaledFnGetter = getterFnWithExtraArgs(evaledFnGetter, fullExp); + } + fn = evaledFnGetter; + } + + // Only cache the value if it's not going to mess up the cache object + // This is more performant that using Object.prototype.hasOwnProperty.call + if (path !== 'hasOwnProperty') { + getterFnCache[path] = fn; + } + return fn; +} + +/////////////////////////////////// + +/** + * @ngdoc service + * @name $parse + * @kind function + * + * @description + * + * Converts Angular {@link guide/expression expression} into a function. + * + * ```js + * var getter = $parse('user.name'); + * var setter = getter.assign; + * var context = {user:{name:'angular'}}; + * var locals = {user:{name:'local'}}; + * + * expect(getter(context)).toEqual('angular'); + * setter(context, 'newValue'); + * expect(context.user.name).toEqual('newValue'); + * expect(getter(context, locals)).toEqual('local'); + * ``` + * + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + * + * The returned function also has the following properties: + * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript + * literal. + * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript + * constant literals. + * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be + * set to a function to change its value on the given context. + * + */ + + +/** + * @ngdoc provider + * @name $parseProvider + * @kind function + * + * @description + * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} + * service. + */ +function $ParseProvider() { + var cacheDefault = {}; + var cacheExpensive = {}; + + var $parseOptions = { + csp: false, + unwrapPromises: false, + logPromiseWarnings: true, + expensiveChecks: false + }; + + + /** + * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. + * + * @ngdoc method + * @name $parseProvider#unwrapPromises + * @description + * + * **This feature is deprecated, see deprecation notes below for more info** + * + * If set to true (default is false), $parse will unwrap promises automatically when a promise is + * found at any part of the expression. In other words, if set to true, the expression will always + * result in a non-promise value. + * + * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled, + * the fulfillment value is used in place of the promise while evaluating the expression. + * + * **Deprecation notice** + * + * This is a feature that didn't prove to be wildly useful or popular, primarily because of the + * dichotomy between data access in templates (accessed as raw values) and controller code + * (accessed as promises). + * + * In most code we ended up resolving promises manually in controllers anyway and thus unifying + * the model access there. + * + * Other downsides of automatic promise unwrapping: + * + * - when building components it's often desirable to receive the raw promises + * - adds complexity and slows down expression evaluation + * - makes expression code pre-generation unattractive due to the amount of code that needs to be + * generated + * - makes IDE auto-completion and tool support hard + * + * **Warning Logs** + * + * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a + * promise (to reduce the noise, each expression is logged only once). To disable this logging use + * `$parseProvider.logPromiseWarnings(false)` api. + * + * + * @param {boolean=} value New value. + * @returns {boolean|self} Returns the current setting when used as getter and self if used as + * setter. + */ + this.unwrapPromises = function(value) { + if (isDefined(value)) { + $parseOptions.unwrapPromises = !!value; + return this; + } else { + return $parseOptions.unwrapPromises; + } + }; + + + /** + * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. + * + * @ngdoc method + * @name $parseProvider#logPromiseWarnings + * @description + * + * Controls whether Angular should log a warning on any encounter of a promise in an expression. + * + * The default is set to `true`. + * + * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well. + * + * @param {boolean=} value New value. + * @returns {boolean|self} Returns the current setting when used as getter and self if used as + * setter. + */ + this.logPromiseWarnings = function(value) { + if (isDefined(value)) { + $parseOptions.logPromiseWarnings = value; + return this; + } else { + return $parseOptions.logPromiseWarnings; + } + }; + + + this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) { + $parseOptions.csp = $sniffer.csp; + var $parseOptionsExpensive = { + csp: $parseOptions.csp, + unwrapPromises: $parseOptions.unwrapPromises, + logPromiseWarnings: $parseOptions.logPromiseWarnings, + expensiveChecks: true + }; + + promiseWarning = function promiseWarningFn(fullExp) { + if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return; + promiseWarningCache[fullExp] = true; + $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' + + 'Automatic unwrapping of promises in Angular expressions is deprecated.'); + }; + + return function(exp, expensiveChecks) { + var parsedExpression; + + switch (typeof exp) { + case 'string': + + var cache = (expensiveChecks ? cacheExpensive : cacheDefault); + if (cache.hasOwnProperty(exp)) { + return cache[exp]; + } + + var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions; + var lexer = new Lexer(parseOptions); + var parser = new Parser(lexer, $filter, parseOptions); + parsedExpression = parser.parse(exp); + + if (exp !== 'hasOwnProperty') { + // Only cache the value if it's not going to mess up the cache object + // This is more performant that using Object.prototype.hasOwnProperty.call + cache[exp] = parsedExpression; + } + + return parsedExpression; + + case 'function': + return exp; + + default: + return noop; + } + }; + }]; +} + +/** + * @ngdoc service + * @name $q + * @requires $rootScope + * + * @description + * A service that helps you run functions asynchronously, and use their return values (or exceptions) + * when they are done processing. + * + * This is an implementation of promises/deferred objects inspired by + * [Kris Kowal's Q](https://github.com/kriskowal/q). + * + * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an + * interface for interacting with an object that represents the result of an action that is + * performed asynchronously, and may or may not be finished at any given point in time. + * + * From the perspective of dealing with error handling, deferred and promise APIs are to + * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. + * + * ```js + * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet` + * // are available in the current lexical scope (they could have been injected or passed in). + * + * function asyncGreet(name) { + * var deferred = $q.defer(); + * + * setTimeout(function() { + * deferred.notify('About to greet ' + name + '.'); + * + * if (okToGreet(name)) { + * deferred.resolve('Hello, ' + name + '!'); + * } else { + * deferred.reject('Greeting ' + name + ' is not allowed.'); + * } + * }, 1000); + * + * return deferred.promise; + * } + * + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { + * alert('Success: ' + greeting); + * }, function(reason) { + * alert('Failed: ' + reason); + * }, function(update) { + * alert('Got notification: ' + update); + * }); + * ``` + * + * At first it might not be obvious why this extra complexity is worth the trouble. The payoff + * comes in the way of guarantees that promise and deferred APIs make, see + * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. + * + * Additionally the promise api allows for composition that is very hard to do with the + * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. + * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the + * section on serial or parallel joining of promises. + * + * + * # The Deferred API + * + * A new instance of deferred is constructed by calling `$q.defer()`. + * + * The purpose of the deferred object is to expose the associated Promise instance as well as APIs + * that can be used for signaling the successful or unsuccessful completion, as well as the status + * of the task. + * + * **Methods** + * + * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection + * constructed via `$q.reject`, the promise will be rejected instead. + * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to + * resolving it with a rejection constructed via `$q.reject`. + * - `notify(value)` - provides updates on the status of the promise's execution. This may be called + * multiple times before the promise is either resolved or rejected. + * + * **Properties** + * + * - promise – `{Promise}` – promise object associated with this deferred. + * + * + * # The Promise API + * + * A new promise instance is created when a deferred instance is created and can be retrieved by + * calling `deferred.promise`. + * + * The purpose of the promise object is to allow for interested parties to get access to the result + * of the deferred task when it completes. + * + * **Methods** + * + * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or + * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously + * as soon as the result is available. The callbacks are called with a single argument: the result + * or rejection reason. Additionally, the notify callback may be called zero or more times to + * provide a progress indication, before the promise is resolved or rejected. + * + * This method *returns a new promise* which is resolved or rejected via the return value of the + * `successCallback`, `errorCallback`. It also notifies via the return value of the + * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback + * method. + * + * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` + * + * Because `catch` is a reserved word in JavaScript and reserved keywords are not supported as + * property names by ES3, you'll need to invoke the method like `promise['catch'](callback)` or + * `promise.then(null, errorCallback)` to make your code IE8 and Android 2.x compatible. + * + * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, + * but to do so without modifying the final value. This is useful to release resources or do some + * clean-up that needs to be done whether the promise was rejected or resolved. See the [full + * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for + * more information. + * + * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as + * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to + * make your code IE8 and Android 2.x compatible. + * + * # Chaining promises + * + * Because calling the `then` method of a promise returns a new derived promise, it is easily + * possible to create a chain of promises: + * + * ```js + * promiseB = promiseA.then(function(result) { + * return result + 1; + * }); + * + * // promiseB will be resolved immediately after promiseA is resolved and its value + * // will be the result of promiseA incremented by 1 + * ``` + * + * It is possible to create chains of any length and since a promise can be resolved with another + * promise (which will defer its resolution further), it is possible to pause/defer resolution of + * the promises at any point in the chain. This makes it possible to implement powerful APIs like + * $http's response interceptors. + * + * + * # Differences between Kris Kowal's Q and $q + * + * There are two main differences: + * + * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation + * mechanism in angular, which means faster propagation of resolution or rejection into your + * models and avoiding unnecessary browser repaints, which would result in flickering UI. + * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains + * all the important functionality needed for common async tasks. + * + * # Testing + * + * ```js + * it('should simulate promise', inject(function($q, $rootScope) { + * var deferred = $q.defer(); + * var promise = deferred.promise; + * var resolvedValue; + * + * promise.then(function(value) { resolvedValue = value; }); + * expect(resolvedValue).toBeUndefined(); + * + * // Simulate resolving of promise + * deferred.resolve(123); + * // Note that the 'then' function does not get called synchronously. + * // This is because we want the promise API to always be async, whether or not + * // it got called synchronously or asynchronously. + * expect(resolvedValue).toBeUndefined(); + * + * // Propagate promise resolution to 'then' functions using $apply(). + * $rootScope.$apply(); + * expect(resolvedValue).toEqual(123); + * })); + * ``` + */ +function $QProvider() { + + this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { + return qFactory(function(callback) { + $rootScope.$evalAsync(callback); + }, $exceptionHandler); + }]; +} + + +/** + * Constructs a promise manager. + * + * @param {function(Function)} nextTick Function for executing functions in the next turn. + * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for + * debugging purposes. + * @returns {object} Promise manager. + */ +function qFactory(nextTick, exceptionHandler) { + + /** + * @ngdoc method + * @name $q#defer + * @kind function + * + * @description + * Creates a `Deferred` object which represents a task which will finish in the future. + * + * @returns {Deferred} Returns a new instance of deferred. + */ + var defer = function() { + var pending = [], + value, deferred; + + deferred = { + + resolve: function(val) { + if (pending) { + var callbacks = pending; + pending = undefined; + value = ref(val); + + if (callbacks.length) { + nextTick(function() { + var callback; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + callback = callbacks[i]; + value.then(callback[0], callback[1], callback[2]); + } + }); + } + } + }, + + + reject: function(reason) { + deferred.resolve(createInternalRejectedPromise(reason)); + }, + + + notify: function(progress) { + if (pending) { + var callbacks = pending; + + if (pending.length) { + nextTick(function() { + var callback; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + callback = callbacks[i]; + callback[2](progress); + } + }); + } + } + }, + + + promise: { + then: function(callback, errback, progressback) { + var result = defer(); + + var wrappedCallback = function(value) { + try { + result.resolve((isFunction(callback) ? callback : defaultCallback)(value)); + } catch(e) { + result.reject(e); + exceptionHandler(e); + } + }; + + var wrappedErrback = function(reason) { + try { + result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); + } catch(e) { + result.reject(e); + exceptionHandler(e); + } + }; + + var wrappedProgressback = function(progress) { + try { + result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress)); + } catch(e) { + exceptionHandler(e); + } + }; + + if (pending) { + pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); + } else { + value.then(wrappedCallback, wrappedErrback, wrappedProgressback); + } + + return result.promise; + }, + + "catch": function(callback) { + return this.then(null, callback); + }, + + "finally": function(callback) { + + function makePromise(value, resolved) { + var result = defer(); + if (resolved) { + result.resolve(value); + } else { + result.reject(value); + } + return result.promise; + } + + function handleCallback(value, isResolved) { + var callbackOutput = null; + try { + callbackOutput = (callback ||defaultCallback)(); + } catch(e) { + return makePromise(e, false); + } + if (isPromiseLike(callbackOutput)) { + return callbackOutput.then(function() { + return makePromise(value, isResolved); + }, function(error) { + return makePromise(error, false); + }); + } else { + return makePromise(value, isResolved); + } + } + + return this.then(function(value) { + return handleCallback(value, true); + }, function(error) { + return handleCallback(error, false); + }); + } + } + }; + + return deferred; + }; + + + var ref = function(value) { + if (isPromiseLike(value)) return value; + return { + then: function(callback) { + var result = defer(); + nextTick(function() { + result.resolve(callback(value)); + }); + return result.promise; + } + }; + }; + + + /** + * @ngdoc method + * @name $q#reject + * @kind function + * + * @description + * Creates a promise that is resolved as rejected with the specified `reason`. This api should be + * used to forward rejection in a chain of promises. If you are dealing with the last promise in + * a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of + * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via + * a promise error callback and you want to forward the error to the promise derived from the + * current promise, you have to "rethrow" the error by returning a rejection constructed via + * `reject`. + * + * ```js + * promiseB = promiseA.then(function(result) { + * // success: do something and resolve promiseB + * // with the old or a new result + * return result; + * }, function(reason) { + * // error: handle the error if possible and + * // resolve promiseB with newPromiseOrValue, + * // otherwise forward the rejection to promiseB + * if (canHandle(reason)) { + * // handle the error and recover + * return newPromiseOrValue; + * } + * return $q.reject(reason); + * }); + * ``` + * + * @param {*} reason Constant, message, exception or an object representing the rejection reason. + * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. + */ + var reject = function(reason) { + var result = defer(); + result.reject(reason); + return result.promise; + }; + + var createInternalRejectedPromise = function(reason) { + return { + then: function(callback, errback) { + var result = defer(); + nextTick(function() { + try { + result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); + } catch(e) { + result.reject(e); + exceptionHandler(e); + } + }); + return result.promise; + } + }; + }; + + + /** + * @ngdoc method + * @name $q#when + * @kind function + * + * @description + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. + * This is useful when you are dealing with an object that might or might not be a promise, or if + * the promise comes from a source that can't be trusted. + * + * @param {*} value Value or a promise + * @returns {Promise} Returns a promise of the passed value or promise + */ + var when = function(value, callback, errback, progressback) { + var result = defer(), + done; + + var wrappedCallback = function(value) { + try { + return (isFunction(callback) ? callback : defaultCallback)(value); + } catch (e) { + exceptionHandler(e); + return reject(e); + } + }; + + var wrappedErrback = function(reason) { + try { + return (isFunction(errback) ? errback : defaultErrback)(reason); + } catch (e) { + exceptionHandler(e); + return reject(e); + } + }; + + var wrappedProgressback = function(progress) { + try { + return (isFunction(progressback) ? progressback : defaultCallback)(progress); + } catch (e) { + exceptionHandler(e); + } + }; + + nextTick(function() { + ref(value).then(function(value) { + if (done) return; + done = true; + result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); + }, function(reason) { + if (done) return; + done = true; + result.resolve(wrappedErrback(reason)); + }, function(progress) { + if (done) return; + result.notify(wrappedProgressback(progress)); + }); + }); + + return result.promise; + }; + + + function defaultCallback(value) { + return value; + } + + + function defaultErrback(reason) { + return reject(reason); + } + + + /** + * @ngdoc method + * @name $q#all + * @kind function + * + * @description + * Combines multiple promises into a single promise that is resolved when all of the input + * promises are resolved. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, + * each value corresponding to the promise at the same index/key in the `promises` array/hash. + * If any of the promises is resolved with a rejection, this resulting promise will be rejected + * with the same rejection value. + */ + function all(promises) { + var deferred = defer(), + counter = 0, + results = isArray(promises) ? [] : {}; + + forEach(promises, function(promise, key) { + counter++; + ref(promise).then(function(value) { + if (results.hasOwnProperty(key)) return; + results[key] = value; + if (!(--counter)) deferred.resolve(results); + }, function(reason) { + if (results.hasOwnProperty(key)) return; + deferred.reject(reason); + }); + }); + + if (counter === 0) { + deferred.resolve(results); + } + + return deferred.promise; + } + + return { + defer: defer, + reject: reject, + when: when, + all: all + }; +} + +function $$RAFProvider(){ //rAF + this.$get = ['$window', '$timeout', function($window, $timeout) { + var requestAnimationFrame = $window.requestAnimationFrame || + $window.webkitRequestAnimationFrame || + $window.mozRequestAnimationFrame; + + var cancelAnimationFrame = $window.cancelAnimationFrame || + $window.webkitCancelAnimationFrame || + $window.mozCancelAnimationFrame || + $window.webkitCancelRequestAnimationFrame; + + var rafSupported = !!requestAnimationFrame; + var raf = rafSupported + ? function(fn) { + var id = requestAnimationFrame(fn); + return function() { + cancelAnimationFrame(id); + }; + } + : function(fn) { + var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 + return function() { + $timeout.cancel(timer); + }; + }; + + raf.supported = rafSupported; + + return raf; + }]; +} + +/** + * DESIGN NOTES + * + * The design decisions behind the scope are heavily favored for speed and memory consumption. + * + * The typical use of scope is to watch the expressions, which most of the time return the same + * value as last time so we optimize the operation. + * + * Closures construction is expensive in terms of speed as well as memory: + * - No closures, instead use prototypical inheritance for API + * - Internal state needs to be stored on scope directly, which means that private state is + * exposed as $$____ properties + * + * Loop operations are optimized by using while(count--) { ... } + * - this means that in order to keep the same order of execution as addition we have to add + * items to the array at the beginning (unshift) instead of at the end (push) + * + * Child scopes are created and removed often + * - Using an array would be slow since inserts in middle are expensive so we use linked list + * + * There are few watches then a lot of observers. This is why you don't want the observer to be + * implemented in the same way as watch. Watch requires return of initialization function which + * are expensive to construct. + */ + + +/** + * @ngdoc provider + * @name $rootScopeProvider + * @description + * + * Provider for the $rootScope service. + */ + +/** + * @ngdoc method + * @name $rootScopeProvider#digestTtl + * @description + * + * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and + * assuming that the model is unstable. + * + * The current default is 10 iterations. + * + * In complex applications it's possible that the dependencies between `$watch`s will result in + * several digest iterations. However if an application needs more than the default 10 digest + * iterations for its model to stabilize then you should investigate what is causing the model to + * continuously change during the digest. + * + * Increasing the TTL could have performance implications, so you should not change it without + * proper justification. + * + * @param {number} limit The number of digest iterations. + */ + + +/** + * @ngdoc service + * @name $rootScope + * @description + * + * Every application has a single root {@link ng.$rootScope.Scope scope}. + * All other scopes are descendant scopes of the root scope. Scopes provide separation + * between the model and the view, via a mechanism for watching the model for changes. + * They also provide an event emission/broadcast and subscription facility. See the + * {@link guide/scope developer guide on scopes}. + */ +function $RootScopeProvider(){ + var TTL = 10; + var $rootScopeMinErr = minErr('$rootScope'); + var lastDirtyWatch = null; + + this.digestTtl = function(value) { + if (arguments.length) { + TTL = value; + } + return TTL; + }; + + this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', + function( $injector, $exceptionHandler, $parse, $browser) { + + /** + * @ngdoc type + * @name $rootScope.Scope + * + * @description + * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the + * {@link auto.$injector $injector}. Child scopes are created using the + * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when + * compiled HTML template is executed.) + * + * Here is a simple scope snippet to show how you can interact with the scope. + * ```html + * + * ``` + * + * # Inheritance + * A scope can inherit from a parent scope, as in this example: + * ```js + var parent = $rootScope; + var child = parent.$new(); + + parent.salutation = "Hello"; + child.name = "World"; + expect(child.salutation).toEqual('Hello'); + + child.salutation = "Welcome"; + expect(child.salutation).toEqual('Welcome'); + expect(parent.salutation).toEqual('Hello'); + * ``` + * + * + * @param {Object.=} providers Map of service factory which need to be + * provided for the current scope. Defaults to {@link ng}. + * @param {Object.=} instanceCache Provides pre-instantiated services which should + * append/override services provided by `providers`. This is handy + * when unit-testing and having the need to override a default + * service. + * @returns {Object} Newly created scope. + * + */ + function Scope() { + this.$id = nextUid(); + this.$$phase = this.$parent = this.$$watchers = + this.$$nextSibling = this.$$prevSibling = + this.$$childHead = this.$$childTail = null; + this['this'] = this.$root = this; + this.$$destroyed = false; + this.$$asyncQueue = []; + this.$$postDigestQueue = []; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$$isolateBindings = {}; + } + + /** + * @ngdoc property + * @name $rootScope.Scope#$id + * + * @description + * Unique scope ID (monotonically increasing) useful for debugging. + */ + + /** + * @ngdoc property + * @name $rootScope.Scope#$parent + * + * @description + * Reference to the parent scope. + */ + + /** + * @ngdoc property + * @name $rootScope.Scope#$root + * + * @description + * Reference to the root scope. + */ + + Scope.prototype = { + constructor: Scope, + /** + * @ngdoc method + * @name $rootScope.Scope#$new + * @kind function + * + * @description + * Creates a new child {@link ng.$rootScope.Scope scope}. + * + * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. + * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. + * + * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is + * desired for the scope and its child scopes to be permanently detached from the parent and + * thus stop participating in model change detection and listener notification by invoking. + * + * @param {boolean} isolate If true, then the scope does not prototypically inherit from the + * parent scope. The scope is isolated, as it can not see parent scope properties. + * When creating widgets, it is useful for the widget to not accidentally read parent + * state. + * + * @returns {Object} The newly created child scope. + * + */ + $new: function(isolate) { + var ChildScope, + child; + + if (isolate) { + child = new Scope(); + child.$root = this.$root; + // ensure that there is just one async queue per $rootScope and its children + child.$$asyncQueue = this.$$asyncQueue; + child.$$postDigestQueue = this.$$postDigestQueue; + } else { + // Only create a child scope class if somebody asks for one, + // but cache it to allow the VM to optimize lookups. + if (!this.$$childScopeClass) { + this.$$childScopeClass = function() { + this.$$watchers = this.$$nextSibling = + this.$$childHead = this.$$childTail = null; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$id = nextUid(); + this.$$childScopeClass = null; + }; + this.$$childScopeClass.prototype = this; + } + child = new this.$$childScopeClass(); + } + child['this'] = child; + child.$parent = this; + child.$$prevSibling = this.$$childTail; + if (this.$$childHead) { + this.$$childTail.$$nextSibling = child; + this.$$childTail = child; + } else { + this.$$childHead = this.$$childTail = child; + } + return child; + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$watch + * @kind function + * + * @description + * Registers a `listener` callback to be executed whenever the `watchExpression` changes. + * + * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest + * $digest()} and should return the value that will be watched. (Since + * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the + * `watchExpression` can execute multiple times per + * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) + * - The `listener` is called only when the value from the current `watchExpression` and the + * previous call to `watchExpression` are not equal (with the exception of the initial run, + * see below). Inequality is determined according to reference inequality, + * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) + * via the `!==` Javascript operator, unless `objectEquality == true` + * (see next point) + * - When `objectEquality == true`, inequality of the `watchExpression` is determined + * according to the {@link angular.equals} function. To save the value of the object for + * later comparison, the {@link angular.copy} function is used. This therefore means that + * watching complex objects will have adverse memory and performance implications. + * - The watch `listener` may change the model, which may trigger other `listener`s to fire. + * This is achieved by rerunning the watchers until no changes are detected. The rerun + * iteration limit is 10 to prevent an infinite loop deadlock. + * + * + * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, + * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` + * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a + * change is detected, be prepared for multiple calls to your listener.) + * + * After a watcher is registered with the scope, the `listener` fn is called asynchronously + * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the + * watcher. In rare cases, this is undesirable because the listener is called when the result + * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you + * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the + * listener was called due to initialization. + * + * The example below contains an illustration of using a function as your $watch listener + * + * + * # Example + * ```js + // let's assume that scope was dependency injected as the $rootScope + var scope = $rootScope; + scope.name = 'misko'; + scope.counter = 0; + + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { + scope.counter = scope.counter + 1; + }); + expect(scope.counter).toEqual(0); + + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); + + scope.$digest(); + // but now it will not be called unless the value changes + expect(scope.counter).toEqual(1); + + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + + + + // Using a listener function + var food; + scope.foodCounter = 0; + expect(scope.foodCounter).toEqual(0); + scope.$watch( + // This is the listener function + function() { return food; }, + // This is the change handler + function(newValue, oldValue) { + if ( newValue !== oldValue ) { + // Only increment the counter if the value changed + scope.foodCounter = scope.foodCounter + 1; + } + } + ); + // No digest has been run so the counter will be zero + expect(scope.foodCounter).toEqual(0); + + // Run the digest but since food has not changed count will still be zero + scope.$digest(); + expect(scope.foodCounter).toEqual(0); + + // Update food and run digest. Now the counter will increment + food = 'cheeseburger'; + scope.$digest(); + expect(scope.foodCounter).toEqual(1); + + * ``` + * + * + * + * @param {(function()|string)} watchExpression Expression that is evaluated on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers + * a call to the `listener`. + * + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(scope)`: called with current `scope` as a parameter. + * @param {(function()|string)=} listener Callback called whenever the return value of + * the `watchExpression` changes. + * + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(newValue, oldValue, scope)`: called with current and previous values as + * parameters. + * + * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of + * comparing for reference equality. + * @returns {function()} Returns a deregistration function for this listener. + */ + $watch: function(watchExp, listener, objectEquality) { + var scope = this, + get = compileToFn(watchExp, 'watch'), + array = scope.$$watchers, + watcher = { + fn: listener, + last: initWatchVal, + get: get, + exp: watchExp, + eq: !!objectEquality + }; + + lastDirtyWatch = null; + + // in the case user pass string, we need to compile it, do we really need this ? + if (!isFunction(listener)) { + var listenFn = compileToFn(listener || noop, 'listener'); + watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; + } + + if (typeof watchExp == 'string' && get.constant) { + var originalFn = watcher.fn; + watcher.fn = function(newVal, oldVal, scope) { + originalFn.call(this, newVal, oldVal, scope); + arrayRemove(array, watcher); + }; + } + + if (!array) { + array = scope.$$watchers = []; + } + // we use unshift since we use a while loop in $digest for speed. + // the while loop reads in reverse order. + array.unshift(watcher); + + return function deregisterWatch() { + arrayRemove(array, watcher); + lastDirtyWatch = null; + }; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$watchCollection + * @kind function + * + * @description + * Shallow watches the properties of an object and fires whenever any of the properties change + * (for arrays, this implies watching the array items; for object maps, this implies watching + * the properties). If a change is detected, the `listener` callback is fired. + * + * - The `obj` collection is observed via standard $watch operation and is examined on every + * call to $digest() to see if any items have been added, removed, or moved. + * - The `listener` is called whenever anything within the `obj` has changed. Examples include + * adding, removing, and moving items belonging to an object or array. + * + * + * # Example + * ```js + $scope.names = ['igor', 'matias', 'misko', 'james']; + $scope.dataCount = 4; + + $scope.$watchCollection('names', function(newNames, oldNames) { + $scope.dataCount = newNames.length; + }); + + expect($scope.dataCount).toEqual(4); + $scope.$digest(); + + //still at 4 ... no changes + expect($scope.dataCount).toEqual(4); + + $scope.names.pop(); + $scope.$digest(); + + //now there's been a change + expect($scope.dataCount).toEqual(3); + * ``` + * + * + * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The + * expression value should evaluate to an object or an array which is observed on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the + * collection will trigger a call to the `listener`. + * + * @param {function(newCollection, oldCollection, scope)} listener a callback function called + * when a change is detected. + * - The `newCollection` object is the newly modified data obtained from the `obj` expression + * - The `oldCollection` object is a copy of the former collection data. + * Due to performance considerations, the`oldCollection` value is computed only if the + * `listener` function declares two or more arguments. + * - The `scope` argument refers to the current scope. + * + * @returns {function()} Returns a de-registration function for this listener. When the + * de-registration function is executed, the internal watch operation is terminated. + */ + $watchCollection: function(obj, listener) { + var self = this; + // the current value, updated on each dirty-check run + var newValue; + // a shallow copy of the newValue from the last dirty-check run, + // updated to match newValue during dirty-check run + var oldValue; + // a shallow copy of the newValue from when the last change happened + var veryOldValue; + // only track veryOldValue if the listener is asking for it + var trackVeryOldValue = (listener.length > 1); + var changeDetected = 0; + var objGetter = $parse(obj); + var internalArray = []; + var internalObject = {}; + var initRun = true; + var oldLength = 0; + + function $watchCollectionWatch() { + newValue = objGetter(self); + var newLength, key, bothNaN; + + if (!isObject(newValue)) { // if primitive + if (oldValue !== newValue) { + oldValue = newValue; + changeDetected++; + } + } else if (isArrayLike(newValue)) { + if (oldValue !== internalArray) { + // we are transitioning from something which was not an array into array. + oldValue = internalArray; + oldLength = oldValue.length = 0; + changeDetected++; + } + + newLength = newValue.length; + + if (oldLength !== newLength) { + // if lengths do not match we need to trigger change notification + changeDetected++; + oldValue.length = oldLength = newLength; + } + // copy the items to oldValue and look for changes. + for (var i = 0; i < newLength; i++) { + bothNaN = (oldValue[i] !== oldValue[i]) && + (newValue[i] !== newValue[i]); + if (!bothNaN && (oldValue[i] !== newValue[i])) { + changeDetected++; + oldValue[i] = newValue[i]; + } + } + } else { + if (oldValue !== internalObject) { + // we are transitioning from something which was not an object into object. + oldValue = internalObject = {}; + oldLength = 0; + changeDetected++; + } + // copy the items to oldValue and look for changes. + newLength = 0; + for (key in newValue) { + if (newValue.hasOwnProperty(key)) { + newLength++; + if (oldValue.hasOwnProperty(key)) { + bothNaN = (oldValue[key] !== oldValue[key]) && + (newValue[key] !== newValue[key]); + if (!bothNaN && (oldValue[key] !== newValue[key])) { + changeDetected++; + oldValue[key] = newValue[key]; + } + } else { + oldLength++; + oldValue[key] = newValue[key]; + changeDetected++; + } + } + } + if (oldLength > newLength) { + // we used to have more keys, need to find them and destroy them. + changeDetected++; + for(key in oldValue) { + if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { + oldLength--; + delete oldValue[key]; + } + } + } + } + return changeDetected; + } + + function $watchCollectionAction() { + if (initRun) { + initRun = false; + listener(newValue, newValue, self); + } else { + listener(newValue, veryOldValue, self); + } + + // make a copy for the next time a collection is changed + if (trackVeryOldValue) { + if (!isObject(newValue)) { + //primitive + veryOldValue = newValue; + } else if (isArrayLike(newValue)) { + veryOldValue = new Array(newValue.length); + for (var i = 0; i < newValue.length; i++) { + veryOldValue[i] = newValue[i]; + } + } else { // if object + veryOldValue = {}; + for (var key in newValue) { + if (hasOwnProperty.call(newValue, key)) { + veryOldValue[key] = newValue[key]; + } + } + } + } + } + + return this.$watch($watchCollectionWatch, $watchCollectionAction); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$digest + * @kind function + * + * @description + * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and + * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change + * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} + * until no more listeners are firing. This means that it is possible to get into an infinite + * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of + * iterations exceeds 10. + * + * Usually, you don't call `$digest()` directly in + * {@link ng.directive:ngController controllers} or in + * {@link ng.$compileProvider#directive directives}. + * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within + * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`. + * + * If you want to be notified whenever `$digest()` is called, + * you can register a `watchExpression` function with + * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. + * + * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. + * + * # Example + * ```js + var scope = ...; + scope.name = 'misko'; + scope.counter = 0; + + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { + scope.counter = scope.counter + 1; + }); + expect(scope.counter).toEqual(0); + + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); + + scope.$digest(); + // but now it will not be called unless the value changes + expect(scope.counter).toEqual(1); + + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + * ``` + * + */ + $digest: function() { + var watch, value, last, + watchers, + asyncQueue = this.$$asyncQueue, + postDigestQueue = this.$$postDigestQueue, + length, + dirty, ttl = TTL, + next, current, target = this, + watchLog = [], + logIdx, logMsg, asyncTask; + + beginPhase('$digest'); + // Check for changes to browser url that happened in sync before the call to $digest + $browser.$$checkUrlChange(); + + lastDirtyWatch = null; + + do { // "while dirty" loop + dirty = false; + current = target; + + while(asyncQueue.length) { + try { + asyncTask = asyncQueue.shift(); + asyncTask.scope.$eval(asyncTask.expression); + } catch (e) { + clearPhase(); + $exceptionHandler(e); + } + lastDirtyWatch = null; + } + + traverseScopesLoop: + do { // "traverse the scopes" loop + if ((watchers = current.$$watchers)) { + // process our watches + length = watchers.length; + while (length--) { + try { + watch = watchers[length]; + // Most common watches are on primitives, in which case we can short + // circuit it with === operator, only when === fails do we use .equals + if (watch) { + if ((value = watch.get(current)) !== (last = watch.last) && + !(watch.eq + ? equals(value, last) + : (typeof value === 'number' && typeof last === 'number' + && isNaN(value) && isNaN(last)))) { + dirty = true; + lastDirtyWatch = watch; + watch.last = watch.eq ? copy(value, null) : value; + watch.fn(value, ((last === initWatchVal) ? value : last), current); + if (ttl < 5) { + logIdx = 4 - ttl; + if (!watchLog[logIdx]) watchLog[logIdx] = []; + logMsg = (isFunction(watch.exp)) + ? 'fn: ' + (watch.exp.name || watch.exp.toString()) + : watch.exp; + logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); + watchLog[logIdx].push(logMsg); + } + } else if (watch === lastDirtyWatch) { + // If the most recently dirty watcher is now clean, short circuit since the remaining watchers + // have already been tested. + dirty = false; + break traverseScopesLoop; + } + } + } catch (e) { + clearPhase(); + $exceptionHandler(e); + } + } + } + + // Insanity Warning: scope depth-first traversal + // yes, this code is a bit crazy, but it works and we have tests to prove it! + // this piece should be kept in sync with the traversal in $broadcast + if (!(next = (current.$$childHead || + (current !== target && current.$$nextSibling)))) { + while(current !== target && !(next = current.$$nextSibling)) { + current = current.$parent; + } + } + } while ((current = next)); + + // `break traverseScopesLoop;` takes us to here + + if((dirty || asyncQueue.length) && !(ttl--)) { + clearPhase(); + throw $rootScopeMinErr('infdig', + '{0} $digest() iterations reached. Aborting!\n' + + 'Watchers fired in the last 5 iterations: {1}', + TTL, toJson(watchLog)); + } + + } while (dirty || asyncQueue.length); + + clearPhase(); + + while(postDigestQueue.length) { + try { + postDigestQueue.shift()(); + } catch (e) { + $exceptionHandler(e); + } + } + }, + + + /** + * @ngdoc event + * @name $rootScope.Scope#$destroy + * @eventType broadcast on scope being destroyed + * + * @description + * Broadcasted when a scope and its children are being destroyed. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + + /** + * @ngdoc method + * @name $rootScope.Scope#$destroy + * @kind function + * + * @description + * Removes the current scope (and all of its children) from the parent scope. Removal implies + * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer + * propagate to the current scope and its children. Removal also implies that the current + * scope is eligible for garbage collection. + * + * The `$destroy()` is usually used by directives such as + * {@link ng.directive:ngRepeat ngRepeat} for managing the + * unrolling of the loop. + * + * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. + * Application code can register a `$destroy` event handler that will give it a chance to + * perform any necessary cleanup. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + $destroy: function() { + // we can't destroy the root scope or a scope that has been already destroyed + if (this.$$destroyed) return; + var parent = this.$parent; + + this.$broadcast('$destroy'); + this.$$destroyed = true; + if (this === $rootScope) return; + + forEach(this.$$listenerCount, bind(null, decrementListenerCount, this)); + + // sever all the references to parent scopes (after this cleanup, the current scope should + // not be retained by any of our references and should be eligible for garbage collection) + if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; + if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; + if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; + if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; + + + // All of the code below is bogus code that works around V8's memory leak via optimized code + // and inline caches. + // + // see: + // - https://code.google.com/p/v8/issues/detail?id=2073#c26 + // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 + // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + + this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = + this.$$childTail = this.$root = null; + + // don't reset these to null in case some async task tries to register a listener/watch/task + this.$$listeners = {}; + this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = []; + + // prevent NPEs since these methods have references to properties we nulled out + this.$destroy = this.$digest = this.$apply = noop; + this.$on = this.$watch = function() { return noop; }; + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$eval + * @kind function + * + * @description + * Executes the `expression` on the current scope and returns the result. Any exceptions in + * the expression are propagated (uncaught). This is useful when evaluating Angular + * expressions. + * + * # Example + * ```js + var scope = ng.$rootScope.Scope(); + scope.a = 1; + scope.b = 2; + + expect(scope.$eval('a+b')).toEqual(3); + expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); + * ``` + * + * @param {(string|function())=} expression An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + * @param {(object)=} locals Local variables object, useful for overriding values in scope. + * @returns {*} The result of evaluating the expression. + */ + $eval: function(expr, locals) { + return $parse(expr)(this, locals); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$evalAsync + * @kind function + * + * @description + * Executes the expression on the current scope at a later point in time. + * + * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only + * that: + * + * - it will execute after the function that scheduled the evaluation (preferably before DOM + * rendering). + * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after + * `expression` execution. + * + * Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle + * will be scheduled. However, it is encouraged to always call code that changes the model + * from within an `$apply` call. That includes code evaluated via `$evalAsync`. + * + * @param {(string|function())=} expression An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with the current `scope` parameter. + * + */ + $evalAsync: function(expr) { + // if we are outside of an $digest loop and this is the first time we are scheduling async + // task also schedule async auto-flush + if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) { + $browser.defer(function() { + if ($rootScope.$$asyncQueue.length) { + $rootScope.$digest(); + } + }); + } + + this.$$asyncQueue.push({scope: this, expression: expr}); + }, + + $$postDigest : function(fn) { + this.$$postDigestQueue.push(fn); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$apply + * @kind function + * + * @description + * `$apply()` is used to execute an expression in angular from outside of the angular + * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). + * Because we are calling into the angular framework we need to perform proper scope life + * cycle of {@link ng.$exceptionHandler exception handling}, + * {@link ng.$rootScope.Scope#$digest executing watches}. + * + * ## Life cycle + * + * # Pseudo-Code of `$apply()` + * ```js + function $apply(expr) { + try { + return $eval(expr); + } catch (e) { + $exceptionHandler(e); + } finally { + $root.$digest(); + } + } + * ``` + * + * + * Scope's `$apply()` method transitions through the following stages: + * + * 1. The {@link guide/expression expression} is executed using the + * {@link ng.$rootScope.Scope#$eval $eval()} method. + * 2. Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the + * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. + * + * + * @param {(string|function())=} exp An angular expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with current `scope` parameter. + * + * @returns {*} The result of evaluating the expression. + */ + $apply: function(expr) { + try { + beginPhase('$apply'); + return this.$eval(expr); + } catch (e) { + $exceptionHandler(e); + } finally { + clearPhase(); + try { + $rootScope.$digest(); + } catch (e) { + $exceptionHandler(e); + throw e; + } + } + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$on + * @kind function + * + * @description + * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for + * discussion of event life cycle. + * + * The event listener function format is: `function(event, args...)`. The `event` object + * passed into the listener has the following attributes: + * + * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or + * `$broadcast`-ed. + * - `currentScope` - `{Scope}`: the current scope which is handling the event. + * - `name` - `{string}`: name of the event. + * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel + * further event propagation (available only for events that were `$emit`-ed). + * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag + * to true. + * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. + * + * @param {string} name Event name to listen on. + * @param {function(event, ...args)} listener Function to call when the event is emitted. + * @returns {function()} Returns a deregistration function for this listener. + */ + $on: function(name, listener) { + var namedListeners = this.$$listeners[name]; + if (!namedListeners) { + this.$$listeners[name] = namedListeners = []; + } + namedListeners.push(listener); + + var current = this; + do { + if (!current.$$listenerCount[name]) { + current.$$listenerCount[name] = 0; + } + current.$$listenerCount[name]++; + } while ((current = current.$parent)); + + var self = this; + return function() { + var indexOfListener = indexOf(namedListeners, listener); + if (indexOfListener !== -1) { + namedListeners[indexOfListener] = null; + decrementListenerCount(self, 1, name); + } + }; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$emit + * @kind function + * + * @description + * Dispatches an event `name` upwards through the scope hierarchy notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$emit` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event traverses upwards toward the root scope and calls all + * registered listeners along the way. The event will stop propagating if one of the listeners + * cancels it. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to emit. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). + */ + $emit: function(name, args) { + var empty = [], + namedListeners, + scope = this, + stopPropagation = false, + event = { + name: name, + targetScope: scope, + stopPropagation: function() {stopPropagation = true;}, + preventDefault: function() { + event.defaultPrevented = true; + }, + defaultPrevented: false + }, + listenerArgs = concat([event], arguments, 1), + i, length; + + do { + namedListeners = scope.$$listeners[name] || empty; + event.currentScope = scope; + for (i=0, length=namedListeners.length; i= 8 ) { + normalizedVal = urlResolve(uri).href; + if (normalizedVal !== '' && !normalizedVal.match(regex)) { + return 'unsafe:'+normalizedVal; + } + } + return uri; + }; + }; +} + +var $sceMinErr = minErr('$sce'); + +var SCE_CONTEXTS = { + HTML: 'html', + CSS: 'css', + URL: 'url', + // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a + // url. (e.g. ng-include, script src, templateUrl) + RESOURCE_URL: 'resourceUrl', + JS: 'js' +}; + +// Helper functions follow. + +// Copied from: +// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962 +// Prereq: s is a string. +function escapeForRegexp(s) { + return s.replace(/([-()\[\]{}+?*.$\^|,:# -1) { + throw $sceMinErr('iwcard', + 'Illegal sequence *** in string matcher. String: {0}', matcher); + } + matcher = escapeForRegexp(matcher). + replace('\\*\\*', '.*'). + replace('\\*', '[^:/.?&;]*'); + return new RegExp('^' + matcher + '$'); + } else if (isRegExp(matcher)) { + // The only other type of matcher allowed is a Regexp. + // Match entire URL / disallow partial matches. + // Flags are reset (i.e. no global, ignoreCase or multiline) + return new RegExp('^' + matcher.source + '$'); + } else { + throw $sceMinErr('imatcher', + 'Matchers may only be "self", string patterns or RegExp objects'); + } +} + + +function adjustMatchers(matchers) { + var adjustedMatchers = []; + if (isDefined(matchers)) { + forEach(matchers, function(matcher) { + adjustedMatchers.push(adjustMatcher(matcher)); + }); + } + return adjustedMatchers; +} + + +/** + * @ngdoc service + * @name $sceDelegate + * @kind function + * + * @description + * + * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict + * Contextual Escaping (SCE)} services to AngularJS. + * + * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of + * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is + * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to + * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things + * work because `$sce` delegates to `$sceDelegate` for these operations. + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. + * + * The default instance of `$sceDelegate` should work out of the box with little pain. While you + * can override it completely to change the behavior of `$sce`, the common case would + * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting + * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as + * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist + * $sceDelegateProvider.resourceUrlWhitelist} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + */ + +/** + * @ngdoc provider + * @name $sceDelegateProvider + * @description + * + * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate + * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure + * that the URLs used for sourcing Angular templates are safe. Refer {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and + * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + * + * For the general details about this service in Angular, read the main page for {@link ng.$sce + * Strict Contextual Escaping (SCE)}. + * + * **Example**: Consider the following case. + * + * - your app is hosted at url `http://myapp.example.com/` + * - but some of your templates are hosted on other domains you control such as + * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc. + * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. + * + * Here is what a secure configuration for this scenario might look like: + * + * ``` + * angular.module('myApp', []).config(function($sceDelegateProvider) { + * $sceDelegateProvider.resourceUrlWhitelist([ + * // Allow same origin resource loads. + * 'self', + * // Allow loading from our assets domain. Notice the difference between * and **. + * 'http://srv*.assets.example.com/**' + * ]); + * + * // The blacklist overrides the whitelist so the open redirect here is blocked. + * $sceDelegateProvider.resourceUrlBlacklist([ + * 'http://myapp.example.com/clickThru**' + * ]); + * }); + * ``` + */ + +function $SceDelegateProvider() { + this.SCE_CONTEXTS = SCE_CONTEXTS; + + // Resource URLs can also be trusted by policy. + var resourceUrlWhitelist = ['self'], + resourceUrlBlacklist = []; + + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlWhitelist + * @kind function + * + * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored. + * + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array. + * + * Note: **an empty whitelist array will block all URLs**! + * + * @return {Array} the currently set whitelist array. + * + * The **default value** when no whitelist has been explicitly set is `['self']` allowing only + * same origin resource requests. + * + * @description + * Sets/Gets the whitelist of trusted resource URLs. + */ + this.resourceUrlWhitelist = function (value) { + if (arguments.length) { + resourceUrlWhitelist = adjustMatchers(value); + } + return resourceUrlWhitelist; + }; + + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlBlacklist + * @kind function + * + * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value + * provided. This must be an array or null. A snapshot of this array is used so further + * changes to the array are ignored. + * + * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array. + * + * The typical usage for the blacklist is to **block + * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as + * these would otherwise be trusted but actually return content from the redirected domain. + * + * Finally, **the blacklist overrides the whitelist** and has the final say. + * + * @return {Array} the currently set blacklist array. + * + * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there + * is no blacklist.) + * + * @description + * Sets/Gets the blacklist of trusted resource URLs. + */ + + this.resourceUrlBlacklist = function (value) { + if (arguments.length) { + resourceUrlBlacklist = adjustMatchers(value); + } + return resourceUrlBlacklist; + }; + + this.$get = ['$injector', function($injector) { + + var htmlSanitizer = function htmlSanitizer(html) { + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + }; + + if ($injector.has('$sanitize')) { + htmlSanitizer = $injector.get('$sanitize'); + } + + + function matchUrl(matcher, parsedUrl) { + if (matcher === 'self') { + return urlIsSameOrigin(parsedUrl); + } else { + // definitely a regex. See adjustMatchers() + return !!matcher.exec(parsedUrl.href); + } + } + + function isResourceUrlAllowedByPolicy(url) { + var parsedUrl = urlResolve(url.toString()); + var i, n, allowed = false; + // Ensure that at least one item from the whitelist allows this url. + for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { + if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { + allowed = true; + break; + } + } + if (allowed) { + // Ensure that no item from the blacklist blocked this url. + for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { + if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { + allowed = false; + break; + } + } + } + return allowed; + } + + function generateHolderType(Base) { + var holderType = function TrustedValueHolderType(trustedValue) { + this.$$unwrapTrustedValue = function() { + return trustedValue; + }; + }; + if (Base) { + holderType.prototype = new Base(); + } + holderType.prototype.valueOf = function sceValueOf() { + return this.$$unwrapTrustedValue(); + }; + holderType.prototype.toString = function sceToString() { + return this.$$unwrapTrustedValue().toString(); + }; + return holderType; + } + + var trustedValueHolderBase = generateHolderType(), + byType = {}; + + byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); + + /** + * @ngdoc method + * @name $sceDelegate#trustAs + * + * @description + * Returns an object that is trusted by angular for use in specified strict + * contextual escaping contexts (such as ng-bind-html, ng-include, any src + * attribute interpolation, any dom event binding attribute interpolation + * such as for onclick, etc.) that uses the provided value. + * See {@link ng.$sce $sce} for enabling strict contextual escaping. + * + * @param {string} type The kind of context in which this value is safe for use. e.g. url, + * resourceUrl, html, js and css. + * @param {*} value The value that that should be considered trusted/safe. + * @returns {*} A value that can be used to stand in for the provided `value` in places + * where Angular expects a $sce.trustAs() return value. + */ + function trustAs(type, trustedValue) { + var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + if (!Constructor) { + throw $sceMinErr('icontext', + 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', + type, trustedValue); + } + if (trustedValue === null || trustedValue === undefined || trustedValue === '') { + return trustedValue; + } + // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting + // mutable objects, we ensure here that the value passed in is actually a string. + if (typeof trustedValue !== 'string') { + throw $sceMinErr('itype', + 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', + type); + } + return new Constructor(trustedValue); + } + + /** + * @ngdoc method + * @name $sceDelegate#valueOf + * + * @description + * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. + * + * If the passed parameter is not a value that had been returned by {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. + * + * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} + * call or anything else. + * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns + * `value` unchanged. + */ + function valueOf(maybeTrusted) { + if (maybeTrusted instanceof trustedValueHolderBase) { + return maybeTrusted.$$unwrapTrustedValue(); + } else { + return maybeTrusted; + } + } + + /** + * @ngdoc method + * @name $sceDelegate#getTrusted + * + * @description + * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and + * returns the originally supplied value if the queried context type is a supertype of the + * created type. If this condition isn't satisfied, throws an exception. + * + * @param {string} type The kind of context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} call. + * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. + */ + function getTrusted(type, maybeTrusted) { + if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { + return maybeTrusted; + } + var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + if (constructor && maybeTrusted instanceof constructor) { + return maybeTrusted.$$unwrapTrustedValue(); + } + // If we get here, then we may only take one of two actions. + // 1. sanitize the value for the requested type, or + // 2. throw an exception. + if (type === SCE_CONTEXTS.RESOURCE_URL) { + if (isResourceUrlAllowedByPolicy(maybeTrusted)) { + return maybeTrusted; + } else { + throw $sceMinErr('insecurl', + 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', + maybeTrusted.toString()); + } + } else if (type === SCE_CONTEXTS.HTML) { + return htmlSanitizer(maybeTrusted); + } + throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + } + + return { trustAs: trustAs, + getTrusted: getTrusted, + valueOf: valueOf }; + }]; +} + + +/** + * @ngdoc provider + * @name $sceProvider + * @description + * + * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. + * - enable/disable Strict Contextual Escaping (SCE) in a module + * - override the default implementation with a custom delegate + * + * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. + */ + +/* jshint maxlen: false*/ + +/** + * @ngdoc service + * @name $sce + * @kind function + * + * @description + * + * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. + * + * # Strict Contextual Escaping + * + * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain + * contexts to result in a value that is marked as safe to use for that context. One example of + * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer + * to these contexts as privileged or SCE contexts. + * + * As of version 1.2, Angular ships with SCE enabled by default. + * + * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows + * one to execute arbitrary javascript by the use of the expression() syntax. Refer + * to learn more about them. + * You can ensure your document is in standards mode and not quirks mode by adding `` + * to the top of your HTML document. + * + * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for + * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. + * + * Here's an example of a binding in a privileged context: + * + * ``` + * + *
+ * ``` + * + * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE + * disabled, this application allows the user to render arbitrary HTML into the DIV. + * In a more realistic example, one may be rendering user comments, blog articles, etc. via + * bindings. (HTML is just one example of a context where rendering user controlled input creates + * security vulnerabilities.) + * + * For the case of HTML, you might use a library, either on the client side, or on the server side, + * to sanitize unsafe HTML before binding to the value and rendering it in the document. + * + * How would you ensure that every place that used these types of bindings was bound to a value that + * was sanitized by your library (or returned as safe for rendering by your server?) How can you + * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some + * properties/fields and forgot to update the binding to the sanitized value? + * + * To be secure by default, you want to ensure that any such bindings are disallowed unless you can + * determine that something explicitly says it's safe to use a value for binding in that + * context. You can then audit your code (a simple grep would do) to ensure that this is only done + * for those values that you can easily tell are safe - because they were received from your server, + * sanitized by your library, etc. You can organize your codebase to help with this - perhaps + * allowing only the files in a specific directory to do this. Ensuring that the internal API + * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. + * + * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} + * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to + * obtain values that will be accepted by SCE / privileged contexts. + * + * + * ## How does it work? + * + * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted + * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link + * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the + * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. + * + * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link + * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly + * simplified): + * + * ``` + * var ngBindHtmlDirective = ['$sce', function($sce) { + * return function(scope, element, attr) { + * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { + * element.html(value || ''); + * }); + * }; + * }]; + * ``` + * + * ## Impact on loading templates + * + * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as + * `templateUrl`'s specified by {@link guide/directive directives}. + * + * By default, Angular only loads templates from the same domain and protocol as the application + * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or + * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist + * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. + * + * *Please note*: + * The browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy apply in addition to this and may further restrict whether the template is successfully + * loaded. This means that without the right CORS policy, loading templates from a different domain + * won't work on all browsers. Also, loading templates from `file://` URL does not work on some + * browsers. + * + * ## This feels like too much overhead for the developer? + * + * It's important to remember that SCE only applies to interpolation expressions. + * + * If your expressions are constant literals, they're automatically trusted and you don't need to + * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. + * `
`) just works. + * + * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them + * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. + * + * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load + * templates in `ng-include` from your application's domain without having to even know about SCE. + * It blocks loading templates from other domains or loading templates over http from an https + * served document. You can change these by setting your own custom {@link + * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link + * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. + * + * This significantly reduces the overhead. It is far easier to pay the small overhead and have an + * application that's secure and can be audited to verify that with much more ease than bolting + * security onto an application later. + * + * + * ## What trusted context types are supported? + * + * | Context | Notes | + * |---------------------|----------------| + * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | + * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | + * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | + * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | + * + * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
+ * + * Each element in these arrays must be one of the following: + * + * - **'self'** + * - The special **string**, `'self'`, can be used to match against all URLs of the **same + * domain** as the application document using the **same protocol**. + * - **String** (except the special value `'self'`) + * - The string is matched against the full *normalized / absolute URL* of the resource + * being tested (substring matches are not good enough.) + * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters + * match themselves. + * - `*`: matches zero or more occurrences of any character other than one of the following 6 + * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use + * in a whitelist. + * - `**`: matches zero or more occurrences of *any* character. As such, it's not + * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. + * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might + * not have been the intention.) Its usage at the very end of the path is ok. (e.g. + * http://foo.example.com/templates/**). + * - **RegExp** (*see caveat below*) + * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax + * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to + * accidentally introduce a bug when one updates a complex expression (imho, all regexes should + * have good test coverage.). For instance, the use of `.` in the regex is correct only in a + * small number of cases. A `.` character in the regex used when matching the scheme or a + * subdomain could be matched against a `:` or literal `.` that was likely not intended. It + * is highly recommended to use the string patterns and only fall back to regular expressions + * if they as a last resort. + * - The regular expression must be an instance of RegExp (i.e. not a string.) It is + * matched against the **entire** *normalized / absolute URL* of the resource being tested + * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags + * present on the RegExp (such as multiline, global, ignoreCase) are ignored. + * - If you are generating your JavaScript from some other templating engine (not + * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), + * remember to escape your regular expression (and be aware that you might need more than + * one level of escaping depending on your templating engine and the way you interpolated + * the value.) Do make use of your platform's escaping mechanism as it might be good + * enough before coding your own. e.g. Ruby has + * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) + * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). + * Javascript lacks a similar built in function for escaping. Take a look at Google + * Closure library's [goog.string.regExpEscape(s)]( + * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. + * + * ## Show me an example using SCE. + * + * + * + *
+ *

+ * User comments
+ * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when + * $sanitize is available. If $sanitize isn't available, this results in an error instead of an + * exploit. + *
+ *
+ * {{userComment.name}}: + * + *
+ *
+ *
+ *
+ *
+ * + * + * var mySceApp = angular.module('mySceApp', ['ngSanitize']); + * + * mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { + * var self = this; + * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { + * self.userComments = userComments; + * }); + * self.explicitlyTrustedHtml = $sce.trustAsHtml( + * 'Hover over this text.'); + * }); + * + * + * + * [ + * { "name": "Alice", + * "htmlComment": + * "Is anyone reading this?" + * }, + * { "name": "Bob", + * "htmlComment": "Yes! Am I the only other one?" + * } + * ] + * + * + * + * describe('SCE doc demo', function() { + * it('should sanitize untrusted values', function() { + * expect(element.all(by.css('.htmlComment')).first().getInnerHtml()) + * .toBe('Is anyone reading this?'); + * }); + * + * it('should NOT sanitize explicitly trusted values', function() { + * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( + * 'Hover over this text.'); + * }); + * }); + * + *
+ * + * + * + * ## Can I disable SCE completely? + * + * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits + * for little coding overhead. It will be much harder to take an SCE disabled application and + * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE + * for cases where you have a lot of existing code that was written before SCE was introduced and + * you're migrating them a module at a time. + * + * That said, here's how you can completely disable SCE: + * + * ``` + * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { + * // Completely disable SCE. For demonstration purposes only! + * // Do not use in new projects. + * $sceProvider.enabled(false); + * }); + * ``` + * + */ +/* jshint maxlen: 100 */ + +function $SceProvider() { + var enabled = true; + + /** + * @ngdoc method + * @name $sceProvider#enabled + * @kind function + * + * @param {boolean=} value If provided, then enables/disables SCE. + * @return {boolean} true if SCE is enabled, false otherwise. + * + * @description + * Enables/disables SCE and returns the current value. + */ + this.enabled = function (value) { + if (arguments.length) { + enabled = !!value; + } + return enabled; + }; + + + /* Design notes on the default implementation for SCE. + * + * The API contract for the SCE delegate + * ------------------------------------- + * The SCE delegate object must provide the following 3 methods: + * + * - trustAs(contextEnum, value) + * This method is used to tell the SCE service that the provided value is OK to use in the + * contexts specified by contextEnum. It must return an object that will be accepted by + * getTrusted() for a compatible contextEnum and return this value. + * + * - valueOf(value) + * For values that were not produced by trustAs(), return them as is. For values that were + * produced by trustAs(), return the corresponding input value to trustAs. Basically, if + * trustAs is wrapping the given values into some type, this operation unwraps it when given + * such a value. + * + * - getTrusted(contextEnum, value) + * This function should return the a value that is safe to use in the context specified by + * contextEnum or throw and exception otherwise. + * + * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be + * opaque or wrapped in some holder object. That happens to be an implementation detail. For + * instance, an implementation could maintain a registry of all trusted objects by context. In + * such a case, trustAs() would return the same object that was passed in. getTrusted() would + * return the same object passed in if it was found in the registry under a compatible context or + * throw an exception otherwise. An implementation might only wrap values some of the time based + * on some criteria. getTrusted() might return a value and not throw an exception for special + * constants or objects even if not wrapped. All such implementations fulfill this contract. + * + * + * A note on the inheritance model for SCE contexts + * ------------------------------------------------ + * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This + * is purely an implementation details. + * + * The contract is simply this: + * + * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) + * will also succeed. + * + * Inheritance happens to capture this in a natural way. In some future, we + * may not use inheritance anymore. That is OK because no code outside of + * sce.js and sceSpecs.js would need to be aware of this detail. + */ + + this.$get = ['$parse', '$sniffer', '$sceDelegate', function( + $parse, $sniffer, $sceDelegate) { + // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows + // the "expression(javascript expression)" syntax which is insecure. + if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) { + throw $sceMinErr('iequirks', + 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + + 'mode. You can fix this by adding the text to the top of your HTML ' + + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); + } + + var sce = shallowCopy(SCE_CONTEXTS); + + /** + * @ngdoc method + * @name $sce#isEnabled + * @kind function + * + * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you + * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. + * + * @description + * Returns a boolean indicating if SCE is enabled. + */ + sce.isEnabled = function () { + return enabled; + }; + sce.trustAs = $sceDelegate.trustAs; + sce.getTrusted = $sceDelegate.getTrusted; + sce.valueOf = $sceDelegate.valueOf; + + if (!enabled) { + sce.trustAs = sce.getTrusted = function(type, value) { return value; }; + sce.valueOf = identity; + } + + /** + * @ngdoc method + * @name $sce#parseAs + * + * @description + * Converts Angular {@link guide/expression expression} into a function. This is like {@link + * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it + * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, + * *result*)} + * + * @param {string} type The kind of SCE context in which this result will be used. + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + sce.parseAs = function sceParseAs(type, expr) { + var parsed = $parse(expr); + if (parsed.literal && parsed.constant) { + return parsed; + } else { + return function sceParseAsTrusted(self, locals) { + return sce.getTrusted(type, parsed(self, locals)); + }; + } + }; + + /** + * @ngdoc method + * @name $sce#trustAs + * + * @description + * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, + * returns an object that is trusted by angular for use in specified strict contextual + * escaping contexts (such as ng-bind-html, ng-include, any src attribute + * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) + * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual + * escaping. + * + * @param {string} type The kind of context in which this value is safe for use. e.g. url, + * resource_url, html, js and css. + * @param {*} value The value that that should be considered trusted/safe. + * @returns {*} A value that can be used to stand in for the provided `value` in places + * where Angular expects a $sce.trustAs() return value. + */ + + /** + * @ngdoc method + * @name $sce#trustAsHtml + * + * @description + * Shorthand method. `$sce.trustAsHtml(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml + * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#trustAsUrl + * + * @description + * Shorthand method. `$sce.trustAsUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl + * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#trustAsResourceUrl + * + * @description + * Shorthand method. `$sce.trustAsResourceUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the return + * value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#trustAsJs + * + * @description + * Shorthand method. `$sce.trustAsJs(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} + * + * @param {*} value The value to trustAs. + * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs + * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives + * only accept expressions that are either literal constants or are the + * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + */ + + /** + * @ngdoc method + * @name $sce#getTrusted + * + * @description + * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, + * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the + * originally supplied value if the queried context type is a supertype of the created type. + * If this condition isn't satisfied, throws an exception. + * + * @param {string} type The kind of context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} + * call. + * @returns {*} The value the was originally provided to + * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. + * Otherwise, throws an exception. + */ + + /** + * @ngdoc method + * @name $sce#getTrustedHtml + * + * @description + * Shorthand method. `$sce.getTrustedHtml(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedCss + * + * @description + * Shorthand method. `$sce.getTrustedCss(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedUrl + * + * @description + * Shorthand method. `$sce.getTrustedUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedResourceUrl + * + * @description + * Shorthand method. `$sce.getTrustedResourceUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to pass to `$sceDelegate.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` + */ + + /** + * @ngdoc method + * @name $sce#getTrustedJs + * + * @description + * Shorthand method. `$sce.getTrustedJs(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` + */ + + /** + * @ngdoc method + * @name $sce#parseAsHtml + * + * @description + * Shorthand method. `$sce.parseAsHtml(expression string)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsCss + * + * @description + * Shorthand method. `$sce.parseAsCss(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsUrl + * + * @description + * Shorthand method. `$sce.parseAsUrl(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsResourceUrl + * + * @description + * Shorthand method. `$sce.parseAsResourceUrl(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + /** + * @ngdoc method + * @name $sce#parseAsJs + * + * @description + * Shorthand method. `$sce.parseAsJs(value)` → + * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`} + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + */ + + // Shorthand delegations. + var parse = sce.parseAs, + getTrusted = sce.getTrusted, + trustAs = sce.trustAs; + + forEach(SCE_CONTEXTS, function (enumValue, name) { + var lName = lowercase(name); + sce[camelCase("parse_as_" + lName)] = function (expr) { + return parse(enumValue, expr); + }; + sce[camelCase("get_trusted_" + lName)] = function (value) { + return getTrusted(enumValue, value); + }; + sce[camelCase("trust_as_" + lName)] = function (value) { + return trustAs(enumValue, value); + }; + }); + + return sce; + }]; +} + +/** + * !!! This is an undocumented "private" service !!! + * + * @name $sniffer + * @requires $window + * @requires $document + * + * @property {boolean} history Does the browser support html5 history api ? + * @property {boolean} hashchange Does the browser support hashchange event ? + * @property {boolean} transitions Does the browser support CSS transition events ? + * @property {boolean} animations Does the browser support CSS animation events ? + * + * @description + * This is very simple implementation of testing browser's features. + */ +function $SnifferProvider() { + this.$get = ['$window', '$document', function($window, $document) { + var eventSupport = {}, + android = + int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), + boxee = /Boxee/i.test(($window.navigator || {}).userAgent), + document = $document[0] || {}, + documentMode = document.documentMode, + vendorPrefix, + vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, + bodyStyle = document.body && document.body.style, + transitions = false, + animations = false, + match; + + if (bodyStyle) { + for(var prop in bodyStyle) { + if(match = vendorRegex.exec(prop)) { + vendorPrefix = match[0]; + vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); + break; + } + } + + if(!vendorPrefix) { + vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; + } + + transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); + animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); + + if (android && (!transitions||!animations)) { + transitions = isString(document.body.style.webkitTransition); + animations = isString(document.body.style.webkitAnimation); + } + } + + + return { + // Android has history.pushState, but it does not update location correctly + // so let's not use the history API at all. + // http://code.google.com/p/android/issues/detail?id=17471 + // https://github.com/angular/angular.js/issues/904 + + // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has + // so let's not use the history API also + // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined + // jshint -W018 + history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), + // jshint +W018 + hashchange: 'onhashchange' in $window && + // IE8 compatible mode lies + (!documentMode || documentMode > 7), + hasEvent: function(event) { + // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have + // it. In particular the event is not fired when backspace or delete key are pressed or + // when cut operation is performed. + if (event == 'input' && msie == 9) return false; + + if (isUndefined(eventSupport[event])) { + var divElm = document.createElement('div'); + eventSupport[event] = 'on' + event in divElm; + } + + return eventSupport[event]; + }, + csp: csp(), + vendorPrefix: vendorPrefix, + transitions : transitions, + animations : animations, + android: android, + msie : msie, + msieDocumentMode: documentMode + }; + }]; +} + +function $TimeoutProvider() { + this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', + function($rootScope, $browser, $q, $exceptionHandler) { + var deferreds = {}; + + + /** + * @ngdoc service + * @name $timeout + * + * @description + * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch + * block and delegates any exceptions to + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * The return value of registering a timeout function is a promise, which will be resolved when + * the timeout is reached and the timeout function is executed. + * + * To cancel a timeout request, call `$timeout.cancel(promise)`. + * + * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to + * synchronously flush the queue of deferred functions. + * + * @param {function()} fn A function, whose execution should be delayed. + * @param {number=} [delay=0] Delay in milliseconds. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this + * promise will be resolved with is the return value of the `fn` function. + * + */ + function timeout(fn, delay, invokeApply) { + var deferred = $q.defer(), + promise = deferred.promise, + skipApply = (isDefined(invokeApply) && !invokeApply), + timeoutId; + + timeoutId = $browser.defer(function() { + try { + deferred.resolve(fn()); + } catch(e) { + deferred.reject(e); + $exceptionHandler(e); + } + finally { + delete deferreds[promise.$$timeoutId]; + } + + if (!skipApply) $rootScope.$apply(); + }, delay); + + promise.$$timeoutId = timeoutId; + deferreds[timeoutId] = deferred; + + return promise; + } + + + /** + * @ngdoc method + * @name $timeout#cancel + * + * @description + * Cancels a task associated with the `promise`. As a result of this, the promise will be + * resolved with a rejection. + * + * @param {Promise=} promise Promise returned by the `$timeout` function. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. + */ + timeout.cancel = function(promise) { + if (promise && promise.$$timeoutId in deferreds) { + deferreds[promise.$$timeoutId].reject('canceled'); + delete deferreds[promise.$$timeoutId]; + return $browser.defer.cancel(promise.$$timeoutId); + } + return false; + }; + + return timeout; + }]; +} + +// NOTE: The usage of window and document instead of $window and $document here is +// deliberate. This service depends on the specific behavior of anchor nodes created by the +// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and +// cause us to break tests. In addition, when the browser resolves a URL for XHR, it +// doesn't know about mocked locations and resolves URLs to the real document - which is +// exactly the behavior needed here. There is little value is mocking these out for this +// service. +var urlParsingNode = document.createElement("a"); +var originUrl = urlResolve(window.location.href, true); + + +/** + * + * Implementation Notes for non-IE browsers + * ---------------------------------------- + * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, + * results both in the normalizing and parsing of the URL. Normalizing means that a relative + * URL will be resolved into an absolute URL in the context of the application document. + * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related + * properties are all populated to reflect the normalized URL. This approach has wide + * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * + * Implementation Notes for IE + * --------------------------- + * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other + * browsers. However, the parsed components will not be set if the URL assigned did not specify + * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We + * work around that by performing the parsing in a 2nd step by taking a previously normalized + * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the + * properties such as protocol, hostname, port, etc. + * + * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one + * uses the inner HTML approach to assign the URL as part of an HTML snippet - + * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. + * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. + * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that + * method and IE < 8 is unsupported. + * + * References: + * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * http://url.spec.whatwg.org/#urlutils + * https://github.com/angular/angular.js/pull/2902 + * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * + * @kind function + * @param {string} url The URL to be parsed. + * @description Normalizes and parses a URL. + * @returns {object} Returns the normalized URL as a dictionary. + * + * | member name | Description | + * |---------------|----------------| + * | href | A normalized version of the provided URL if it was not an absolute URL | + * | protocol | The protocol including the trailing colon | + * | host | The host and port (if the port is non-default) of the normalizedUrl | + * | search | The search params, minus the question mark | + * | hash | The hash string, minus the hash symbol + * | hostname | The hostname + * | port | The port, without ":" + * | pathname | The pathname, beginning with "/" + * + */ +function urlResolve(url, base) { + var href = url; + + if (msie) { + // Normalize before parse. Refer Implementation Notes on why this is + // done in two steps on IE. + urlParsingNode.setAttribute("href", href); + href = urlParsingNode.href; + } + + urlParsingNode.setAttribute('href', href); + + // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + return { + href: urlParsingNode.href, + protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', + host: urlParsingNode.host, + search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', + hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', + hostname: urlParsingNode.hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') + ? urlParsingNode.pathname + : '/' + urlParsingNode.pathname + }; +} + +/** + * Parse a request URL and determine whether this is a same-origin request as the application document. + * + * @param {string|object} requestUrl The url of the request as a string that will be resolved + * or a parsed URL object. + * @returns {boolean} Whether the request is for the same origin as the application document. + */ +function urlIsSameOrigin(requestUrl) { + var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; + return (parsed.protocol === originUrl.protocol && + parsed.host === originUrl.host); +} + +/** + * @ngdoc service + * @name $window + * + * @description + * A reference to the browser's `window` object. While `window` + * is globally available in JavaScript, it causes testability problems, because + * it is a global variable. In angular we always refer to it through the + * `$window` service, so it may be overridden, removed or mocked for testing. + * + * Expressions, like the one defined for the `ngClick` directive in the example + * below, are evaluated with respect to the current scope. Therefore, there is + * no risk of inadvertently coding in a dependency on a global value in such an + * expression. + * + * @example + + + +
+ + +
+
+ + it('should display the greeting in the input box', function() { + element(by.model('greeting')).sendKeys('Hello, E2E Tests'); + // If we click the button it will block the test runner + // element(':button').click(); + }); + +
+ */ +function $WindowProvider(){ + this.$get = valueFn(window); +} + +/* global currencyFilter: true, + dateFilter: true, + filterFilter: true, + jsonFilter: true, + limitToFilter: true, + lowercaseFilter: true, + numberFilter: true, + orderByFilter: true, + uppercaseFilter: true, + */ + +/** + * @ngdoc provider + * @name $filterProvider + * @description + * + * Filters are just functions which transform input to an output. However filters need to be + * Dependency Injected. To achieve this a filter definition consists of a factory function which is + * annotated with dependencies and is responsible for creating a filter function. + * + * ```js + * // Filter registration + * function MyModule($provide, $filterProvider) { + * // create a service to demonstrate injection (not always needed) + * $provide.value('greet', function(name){ + * return 'Hello ' + name + '!'; + * }); + * + * // register a filter factory which uses the + * // greet service to demonstrate DI. + * $filterProvider.register('greet', function(greet){ + * // return the filter function which uses the greet service + * // to generate salutation + * return function(text) { + * // filters need to be forgiving so check input validity + * return text && greet(text) || text; + * }; + * }); + * } + * ``` + * + * The filter function is registered with the `$injector` under the filter name suffix with + * `Filter`. + * + * ```js + * it('should be the same instance', inject( + * function($filterProvider) { + * $filterProvider.register('reverse', function(){ + * return ...; + * }); + * }, + * function($filter, reverseFilter) { + * expect($filter('reverse')).toBe(reverseFilter); + * }); + * ``` + * + * + * For more information about how angular filters work, and how to create your own filters, see + * {@link guide/filter Filters} in the Angular Developer Guide. + */ + +/** + * @ngdoc service + * @name $filter + * @kind function + * @description + * Filters are used for formatting data displayed to the user. + * + * The general syntax in templates is as follows: + * + * {{ expression [| filter_name[:parameter_value] ... ] }} + * + * @param {String} name Name of the filter function to retrieve + * @return {Function} the filter function + * @example + + +
+

{{ originalText }}

+

{{ filteredText }}

+
+
+ + + angular.module('filterExample', []) + .controller('MainCtrl', function($scope, $filter) { + $scope.originalText = 'hello'; + $scope.filteredText = $filter('uppercase')($scope.originalText); + }); + +
+ */ +$FilterProvider.$inject = ['$provide']; +function $FilterProvider($provide) { + var suffix = 'Filter'; + + /** + * @ngdoc method + * @name $filterProvider#register + * @param {string|Object} name Name of the filter function, or an object map of filters where + * the keys are the filter names and the values are the filter factories. + * @returns {Object} Registered filter instance, or if a map of filters was provided then a map + * of the registered filter instances. + */ + function register(name, factory) { + if(isObject(name)) { + var filters = {}; + forEach(name, function(filter, key) { + filters[key] = register(key, filter); + }); + return filters; + } else { + return $provide.factory(name + suffix, factory); + } + } + this.register = register; + + this.$get = ['$injector', function($injector) { + return function(name) { + return $injector.get(name + suffix); + }; + }]; + + //////////////////////////////////////// + + /* global + currencyFilter: false, + dateFilter: false, + filterFilter: false, + jsonFilter: false, + limitToFilter: false, + lowercaseFilter: false, + numberFilter: false, + orderByFilter: false, + uppercaseFilter: false, + */ + + register('currency', currencyFilter); + register('date', dateFilter); + register('filter', filterFilter); + register('json', jsonFilter); + register('limitTo', limitToFilter); + register('lowercase', lowercaseFilter); + register('number', numberFilter); + register('orderBy', orderByFilter); + register('uppercase', uppercaseFilter); +} + +/** + * @ngdoc filter + * @name filter + * @kind function + * + * @description + * Selects a subset of items from `array` and returns it as a new array. + * + * @param {Array} array The source array. + * @param {string|Object|function()} expression The predicate to be used for selecting items from + * `array`. + * + * Can be one of: + * + * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against + * the contents of the `array`. All strings or objects with string properties in `array` that contain this string + * will be returned. The predicate can be negated by prefixing the string with `!`. + * + * - `Object`: A pattern object can be used to filter specific properties on objects contained + * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items + * which have property `name` containing "M" and property `phone` containing "1". A special + * property name `$` can be used (as in `{$:"text"}`) to accept a match against any + * property of the object. That's equivalent to the simple substring match with a `string` + * as described above. The predicate can be negated by prefixing the string with `!`. + * For Example `{name: "!M"}` predicate will return an array of items which have property `name` + * not containing "M". + * + * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is + * called for each element of `array`. The final result is an array of those elements that + * the predicate returned true for. + * + * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in + * determining if the expected value (from the filter expression) and actual value (from + * the object in the array) should be considered a match. + * + * Can be one of: + * + * - `function(actual, expected)`: + * The function will be given the object value and the predicate value to compare and + * should return true if the item should be included in filtered result. + * + * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. + * this is essentially strict comparison of expected and actual. + * + * - `false|undefined`: A short hand for a function which will look for a substring match in case + * insensitive way. + * + * @example + + +
+ + Search: + + + + + + +
NamePhone
{{friend.name}}{{friend.phone}}
+
+ Any:
+ Name only
+ Phone only
+ Equality
+ + + + + + +
NamePhone
{{friendObj.name}}{{friendObj.phone}}
+
+ + var expectFriendNames = function(expectedNames, key) { + element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { + arr.forEach(function(wd, i) { + expect(wd.getText()).toMatch(expectedNames[i]); + }); + }); + }; + + it('should search across all fields when filtering with a string', function() { + var searchText = element(by.model('searchText')); + searchText.clear(); + searchText.sendKeys('m'); + expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); + + searchText.clear(); + searchText.sendKeys('76'); + expectFriendNames(['John', 'Julie'], 'friend'); + }); + + it('should search in specific fields when filtering with a predicate object', function() { + var searchAny = element(by.model('search.$')); + searchAny.clear(); + searchAny.sendKeys('i'); + expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); + }); + it('should use a equal comparison when comparator is true', function() { + var searchName = element(by.model('search.name')); + var strict = element(by.model('strict')); + searchName.clear(); + searchName.sendKeys('Julie'); + strict.click(); + expectFriendNames(['Julie'], 'friendObj'); + }); + +
+ */ +function filterFilter() { + return function(array, expression, comparator) { + if (!isArray(array)) return array; + + var comparatorType = typeof(comparator), + predicates = []; + + predicates.check = function(value) { + for (var j = 0; j < predicates.length; j++) { + if(!predicates[j](value)) { + return false; + } + } + return true; + }; + + if (comparatorType !== 'function') { + if (comparatorType === 'boolean' && comparator) { + comparator = function(obj, text) { + return angular.equals(obj, text); + }; + } else { + comparator = function(obj, text) { + if (obj && text && typeof obj === 'object' && typeof text === 'object') { + for (var objKey in obj) { + if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && + comparator(obj[objKey], text[objKey])) { + return true; + } + } + return false; + } + text = (''+text).toLowerCase(); + return (''+obj).toLowerCase().indexOf(text) > -1; + }; + } + } + + var search = function(obj, text){ + if (typeof text === 'string' && text.charAt(0) === '!') { + return !search(obj, text.substr(1)); + } + switch (typeof obj) { + case 'boolean': + case 'number': + case 'string': + return comparator(obj, text); + case 'object': + switch (typeof text) { + case 'object': + return comparator(obj, text); + default: + for ( var objKey in obj) { + if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { + return true; + } + } + break; + } + return false; + case 'array': + for ( var i = 0; i < obj.length; i++) { + if (search(obj[i], text)) { + return true; + } + } + return false; + default: + return false; + } + }; + switch (typeof expression) { + case 'boolean': + case 'number': + case 'string': + // Set up expression object and fall through + expression = {$:expression}; + // jshint -W086 + case 'object': + // jshint +W086 + for (var key in expression) { + (function(path) { + if (typeof expression[path] === 'undefined') return; + predicates.push(function(value) { + return search(path == '$' ? value : (value && value[path]), expression[path]); + }); + })(key); + } + break; + case 'function': + predicates.push(expression); + break; + default: + return array; + } + var filtered = []; + for ( var j = 0; j < array.length; j++) { + var value = array[j]; + if (predicates.check(value)) { + filtered.push(value); + } + } + return filtered; + }; +} + +/** + * @ngdoc filter + * @name currency + * @kind function + * + * @description + * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default + * symbol for current locale is used. + * + * @param {number} amount Input to filter. + * @param {string=} symbol Currency symbol or identifier to be displayed. + * @returns {string} Formatted number. + * + * + * @example + + + +
+
+ default currency symbol ($): {{amount | currency}}
+ custom currency identifier (USD$): {{amount | currency:"USD$"}} +
+
+ + it('should init with 1234.56', function() { + expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); + expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56'); + }); + it('should update', function() { + if (browser.params.browser == 'safari') { + // Safari does not understand the minus key. See + // https://github.com/angular/protractor/issues/481 + return; + } + element(by.model('amount')).clear(); + element(by.model('amount')).sendKeys('-1234'); + expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); + expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)'); + }); + +
+ */ +currencyFilter.$inject = ['$locale']; +function currencyFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + return function(amount, currencySymbol){ + if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; + return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). + replace(/\u00A4/g, currencySymbol); + }; +} + +/** + * @ngdoc filter + * @name number + * @kind function + * + * @description + * Formats a number as text. + * + * If the input is not a number an empty string is returned. + * + * @param {number|string} number Number to format. + * @param {(number|string)=} fractionSize Number of decimal places to round the number to. + * If this is not provided then the fraction size is computed from the current locale's number + * formatting pattern. In the case of the default locale, it will be 3. + * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. + * + * @example + + + +
+ Enter number:
+ Default formatting: {{val | number}}
+ No fractions: {{val | number:0}}
+ Negative number: {{-val | number:4}} +
+
+ + it('should format numbers', function() { + expect(element(by.id('number-default')).getText()).toBe('1,234.568'); + expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); + }); + + it('should update', function() { + element(by.model('val')).clear(); + element(by.model('val')).sendKeys('3374.333'); + expect(element(by.id('number-default')).getText()).toBe('3,374.333'); + expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); + }); + +
+ */ + + +numberFilter.$inject = ['$locale']; +function numberFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + return function(number, fractionSize) { + return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, + fractionSize); + }; +} + +var DECIMAL_SEP = '.'; +function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { + if (number == null || !isFinite(number) || isObject(number)) return ''; + + var isNegative = number < 0; + number = Math.abs(number); + var numStr = number + '', + formatedText = '', + parts = []; + + var hasExponent = false; + if (numStr.indexOf('e') !== -1) { + var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); + if (match && match[2] == '-' && match[3] > fractionSize + 1) { + numStr = '0'; + number = 0; + } else { + formatedText = numStr; + hasExponent = true; + } + } + + if (!hasExponent) { + var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; + + // determine fractionSize if it is not specified + if (isUndefined(fractionSize)) { + fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); + } + + // safely round numbers in JS without hitting imprecisions of floating-point arithmetics + // inspired by: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round + number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize); + + if (number === 0) { + isNegative = false; + } + + var fraction = ('' + number).split(DECIMAL_SEP); + var whole = fraction[0]; + fraction = fraction[1] || ''; + + var i, pos = 0, + lgroup = pattern.lgSize, + group = pattern.gSize; + + if (whole.length >= (lgroup + group)) { + pos = whole.length - lgroup; + for (i = 0; i < pos; i++) { + if ((pos - i)%group === 0 && i !== 0) { + formatedText += groupSep; + } + formatedText += whole.charAt(i); + } + } + + for (i = pos; i < whole.length; i++) { + if ((whole.length - i)%lgroup === 0 && i !== 0) { + formatedText += groupSep; + } + formatedText += whole.charAt(i); + } + + // format fraction part. + while(fraction.length < fractionSize) { + fraction += '0'; + } + + if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); + } else { + + if (fractionSize > 0 && number > -1 && number < 1) { + formatedText = number.toFixed(fractionSize); + } + } + + parts.push(isNegative ? pattern.negPre : pattern.posPre); + parts.push(formatedText); + parts.push(isNegative ? pattern.negSuf : pattern.posSuf); + return parts.join(''); +} + +function padNumber(num, digits, trim) { + var neg = ''; + if (num < 0) { + neg = '-'; + num = -num; + } + num = '' + num; + while(num.length < digits) num = '0' + num; + if (trim) + num = num.substr(num.length - digits); + return neg + num; +} + + +function dateGetter(name, size, offset, trim) { + offset = offset || 0; + return function(date) { + var value = date['get' + name](); + if (offset > 0 || value > -offset) + value += offset; + if (value === 0 && offset == -12 ) value = 12; + return padNumber(value, size, trim); + }; +} + +function dateStrGetter(name, shortForm) { + return function(date, formats) { + var value = date['get' + name](); + var get = uppercase(shortForm ? ('SHORT' + name) : name); + + return formats[get][value]; + }; +} + +function timeZoneGetter(date) { + var zone = -1 * date.getTimezoneOffset(); + var paddedZone = (zone >= 0) ? "+" : ""; + + paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + + padNumber(Math.abs(zone % 60), 2); + + return paddedZone; +} + +function ampmGetter(date, formats) { + return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; +} + +var DATE_FORMATS = { + yyyy: dateGetter('FullYear', 4), + yy: dateGetter('FullYear', 2, 0, true), + y: dateGetter('FullYear', 1), + MMMM: dateStrGetter('Month'), + MMM: dateStrGetter('Month', true), + MM: dateGetter('Month', 2, 1), + M: dateGetter('Month', 1, 1), + dd: dateGetter('Date', 2), + d: dateGetter('Date', 1), + HH: dateGetter('Hours', 2), + H: dateGetter('Hours', 1), + hh: dateGetter('Hours', 2, -12), + h: dateGetter('Hours', 1, -12), + mm: dateGetter('Minutes', 2), + m: dateGetter('Minutes', 1), + ss: dateGetter('Seconds', 2), + s: dateGetter('Seconds', 1), + // while ISO 8601 requires fractions to be prefixed with `.` or `,` + // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions + sss: dateGetter('Milliseconds', 3), + EEEE: dateStrGetter('Day'), + EEE: dateStrGetter('Day', true), + a: ampmGetter, + Z: timeZoneGetter +}; + +var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, + NUMBER_STRING = /^\-?\d+$/; + +/** + * @ngdoc filter + * @name date + * @kind function + * + * @description + * Formats `date` to a string based on the requested `format`. + * + * `format` string can be composed of the following elements: + * + * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) + * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) + * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) + * * `'MMMM'`: Month in year (January-December) + * * `'MMM'`: Month in year (Jan-Dec) + * * `'MM'`: Month in year, padded (01-12) + * * `'M'`: Month in year (1-12) + * * `'dd'`: Day in month, padded (01-31) + * * `'d'`: Day in month (1-31) + * * `'EEEE'`: Day in Week,(Sunday-Saturday) + * * `'EEE'`: Day in Week, (Sun-Sat) + * * `'HH'`: Hour in day, padded (00-23) + * * `'H'`: Hour in day (0-23) + * * `'hh'`: Hour in am/pm, padded (01-12) + * * `'h'`: Hour in am/pm, (1-12) + * * `'mm'`: Minute in hour, padded (00-59) + * * `'m'`: Minute in hour (0-59) + * * `'ss'`: Second in minute, padded (00-59) + * * `'s'`: Second in minute (0-59) + * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) + * * `'a'`: am/pm marker + * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) + * + * `format` string can also be one of the following predefined + * {@link guide/i18n localizable formats}: + * + * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale + * (e.g. Sep 3, 2010 12:05:08 pm) + * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) + * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale + * (e.g. Friday, September 3, 2010) + * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) + * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) + * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) + * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) + * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) + * + * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. + * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence + * (e.g. `"h 'o''clock'"`). + * + * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or + * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its + * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is + * specified in the string input, the time is considered to be in the local timezone. + * @param {string=} format Formatting rules (see Description). If not specified, + * `mediumDate` is used. + * @returns {string} Formatted string or the input if input is not recognized as date/millis. + * + * @example + + + {{1288323623006 | date:'medium'}}: + {{1288323623006 | date:'medium'}}
+ {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: + {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
+ {{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: + {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
+ {{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: + {{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}
+
+ + it('should format date', function() { + expect(element(by.binding("1288323623006 | date:'medium'")).getText()). + toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); + expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). + toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); + expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). + toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); + expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()). + toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); + }); + +
+ */ +dateFilter.$inject = ['$locale']; +function dateFilter($locale) { + + + var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; + // 1 2 3 4 5 6 7 8 9 10 11 + function jsonStringToDate(string) { + var match; + if (match = string.match(R_ISO8601_STR)) { + var date = new Date(0), + tzHour = 0, + tzMin = 0, + dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, + timeSetter = match[8] ? date.setUTCHours : date.setHours; + + if (match[9]) { + tzHour = int(match[9] + match[10]); + tzMin = int(match[9] + match[11]); + } + dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); + var h = int(match[4]||0) - tzHour; + var m = int(match[5]||0) - tzMin; + var s = int(match[6]||0); + var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); + timeSetter.call(date, h, m, s, ms); + return date; + } + return string; + } + + + return function(date, format) { + var text = '', + parts = [], + fn, match; + + format = format || 'mediumDate'; + format = $locale.DATETIME_FORMATS[format] || format; + if (isString(date)) { + date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date); + } + + if (isNumber(date)) { + date = new Date(date); + } + + if (!isDate(date)) { + return date; + } + + while(format) { + match = DATE_FORMATS_SPLIT.exec(format); + if (match) { + parts = concat(parts, match, 1); + format = parts.pop(); + } else { + parts.push(format); + format = null; + } + } + + forEach(parts, function(value){ + fn = DATE_FORMATS[value]; + text += fn ? fn(date, $locale.DATETIME_FORMATS) + : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); + }); + + return text; + }; +} + + +/** + * @ngdoc filter + * @name json + * @kind function + * + * @description + * Allows you to convert a JavaScript object into JSON string. + * + * This filter is mostly useful for debugging. When using the double curly {{value}} notation + * the binding is automatically converted to JSON. + * + * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. + * @returns {string} JSON string. + * + * + * @example + + +
{{ {'name':'value'} | json }}
+
+ + it('should jsonify filtered objects', function() { + expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/); + }); + +
+ * + */ +function jsonFilter() { + return function(object) { + return toJson(object, true); + }; +} + + +/** + * @ngdoc filter + * @name lowercase + * @kind function + * @description + * Converts string to lowercase. + * @see angular.lowercase + */ +var lowercaseFilter = valueFn(lowercase); + + +/** + * @ngdoc filter + * @name uppercase + * @kind function + * @description + * Converts string to uppercase. + * @see angular.uppercase + */ +var uppercaseFilter = valueFn(uppercase); + +/** + * @ngdoc filter + * @name limitTo + * @kind function + * + * @description + * Creates a new array or string containing only a specified number of elements. The elements + * are taken from either the beginning or the end of the source array or string, as specified by + * the value and sign (positive or negative) of `limit`. + * + * @param {Array|string} input Source array or string to be limited. + * @param {string|number} limit The length of the returned array or string. If the `limit` number + * is positive, `limit` number of items from the beginning of the source array/string are copied. + * If the number is negative, `limit` number of items from the end of the source array/string + * are copied. The `limit` will be trimmed if it exceeds `array.length` + * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array + * had less than `limit` elements. + * + * @example + + + +
+ Limit {{numbers}} to: +

Output numbers: {{ numbers | limitTo:numLimit }}

+ Limit {{letters}} to: +

Output letters: {{ letters | limitTo:letterLimit }}

+
+
+ + var numLimitInput = element(by.model('numLimit')); + var letterLimitInput = element(by.model('letterLimit')); + var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); + var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); + + it('should limit the number array to first three items', function() { + expect(numLimitInput.getAttribute('value')).toBe('3'); + expect(letterLimitInput.getAttribute('value')).toBe('3'); + expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); + expect(limitedLetters.getText()).toEqual('Output letters: abc'); + }); + + // There is a bug in safari and protractor that doesn't like the minus key + // it('should update the output when -3 is entered', function() { + // numLimitInput.clear(); + // numLimitInput.sendKeys('-3'); + // letterLimitInput.clear(); + // letterLimitInput.sendKeys('-3'); + // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); + // expect(limitedLetters.getText()).toEqual('Output letters: ghi'); + // }); + + it('should not exceed the maximum size of input array', function() { + numLimitInput.clear(); + numLimitInput.sendKeys('100'); + letterLimitInput.clear(); + letterLimitInput.sendKeys('100'); + expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); + expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); + }); + +
+ */ +function limitToFilter(){ + return function(input, limit) { + if (!isArray(input) && !isString(input)) return input; + + if (Math.abs(Number(limit)) === Infinity) { + limit = Number(limit); + } else { + limit = int(limit); + } + + if (isString(input)) { + //NaN check on limit + if (limit) { + return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); + } else { + return ""; + } + } + + var out = [], + i, n; + + // if abs(limit) exceeds maximum length, trim it + if (limit > input.length) + limit = input.length; + else if (limit < -input.length) + limit = -input.length; + + if (limit > 0) { + i = 0; + n = limit; + } else { + i = input.length + limit; + n = input.length; + } + + for (; i=} expression A predicate to be + * used by the comparator to determine the order of elements. + * + * Can be one of: + * + * - `function`: Getter function. The result of this function will be sorted using the + * `<`, `=`, `>` operator. + * - `string`: An Angular expression. The result of this expression is used to compare elements + * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by + * 3 first characters of a property called `name`). The result of a constant expression + * is interpreted as a property name to be used in comparisons (for example `"special name"` + * to sort object by the value of their `special name` property). An expression can be + * optionally prefixed with `+` or `-` to control ascending or descending sort order + * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array + * element itself is used to compare where sorting. + * - `Array`: An array of function or string predicates. The first predicate in the array + * is used for sorting, but when two items are equivalent, the next predicate is used. + * + * If the predicate is missing or empty then it defaults to `'+'`. + * + * @param {boolean=} reverse Reverse the order of the array. + * @returns {Array} Sorted copy of the source array. + * + * @example + + + +
+
Sorting predicate = {{predicate}}; reverse = {{reverse}}
+
+ [ unsorted ] + + + + + + + + + + + +
Name + (^)Phone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
+
+
+
+ * + * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the + * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the + * desired parameters. + * + * Example: + * + * @example + + +
+ + + + + + + + + + + +
Name + (^)Phone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
+
+
+ + + angular.module('orderByExample', []) + .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { + var orderBy = $filter('orderBy'); + $scope.friends = [ + { name: 'John', phone: '555-1212', age: 10 }, + { name: 'Mary', phone: '555-9876', age: 19 }, + { name: 'Mike', phone: '555-4321', age: 21 }, + { name: 'Adam', phone: '555-5678', age: 35 }, + { name: 'Julie', phone: '555-8765', age: 29 } + ]; + $scope.order = function(predicate, reverse) { + $scope.friends = orderBy($scope.friends, predicate, reverse); + }; + $scope.order('-age',false); + }]); + +
+ */ +orderByFilter.$inject = ['$parse']; +function orderByFilter($parse){ + return function(array, sortPredicate, reverseOrder) { + if (!(isArrayLike(array))) return array; + sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; + if (sortPredicate.length === 0) { sortPredicate = ['+']; } + sortPredicate = map(sortPredicate, function(predicate){ + var descending = false, get = predicate || identity; + if (isString(predicate)) { + if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { + descending = predicate.charAt(0) == '-'; + predicate = predicate.substring(1); + } + if ( predicate === '' ) { + // Effectively no predicate was passed so we compare identity + return reverseComparator(function(a,b) { + return compare(a, b); + }, descending); + } + get = $parse(predicate); + if (get.constant) { + var key = get(); + return reverseComparator(function(a,b) { + return compare(a[key], b[key]); + }, descending); + } + } + return reverseComparator(function(a,b){ + return compare(get(a),get(b)); + }, descending); + }); + return slice.call(array).sort(reverseComparator(comparator, reverseOrder)); + + function comparator(o1, o2){ + for ( var i = 0; i < sortPredicate.length; i++) { + var comp = sortPredicate[i](o1, o2); + if (comp !== 0) return comp; + } + return 0; + } + function reverseComparator(comp, descending) { + return toBoolean(descending) + ? function(a,b){return comp(b,a);} + : comp; + } + function compare(v1, v2){ + var t1 = typeof v1; + var t2 = typeof v2; + if (t1 == t2) { + if (isDate(v1) && isDate(v2)) { + v1 = v1.valueOf(); + v2 = v2.valueOf(); + } + if (t1 == "string") { + v1 = v1.toLowerCase(); + v2 = v2.toLowerCase(); + } + if (v1 === v2) return 0; + return v1 < v2 ? -1 : 1; + } else { + return t1 < t2 ? -1 : 1; + } + } + }; +} + +function ngDirective(directive) { + if (isFunction(directive)) { + directive = { + link: directive + }; + } + directive.restrict = directive.restrict || 'AC'; + return valueFn(directive); +} + +/** + * @ngdoc directive + * @name a + * @restrict E + * + * @description + * Modifies the default behavior of the html A tag so that the default action is prevented when + * the href attribute is empty. + * + * This change permits the easy creation of action links with the `ngClick` directive + * without changing the location or causing page reloads, e.g.: + * `Add Item` + */ +var htmlAnchorDirective = valueFn({ + restrict: 'E', + compile: function(element, attr) { + + if (msie <= 8) { + + // turn link into a stylable link in IE + // but only if it doesn't have name attribute, in which case it's an anchor + if (!attr.href && !attr.name) { + attr.$set('href', ''); + } + + // add a comment node to anchors to workaround IE bug that causes element content to be reset + // to new attribute content if attribute is updated with value containing @ and element also + // contains value with @ + // see issue #1949 + element.append(document.createComment('IE fix')); + } + + if (!attr.href && !attr.xlinkHref && !attr.name) { + return function(scope, element) { + // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. + var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? + 'xlink:href' : 'href'; + element.on('click', function(event){ + // if we have no href url, then don't navigate anywhere. + if (!element.attr(href)) { + event.preventDefault(); + } + }); + }; + } + } +}); + +/** + * @ngdoc directive + * @name ngHref + * @restrict A + * @priority 99 + * + * @description + * Using Angular markup like `{{hash}}` in an href attribute will + * make the link go to the wrong URL if the user clicks it before + * Angular has a chance to replace the `{{hash}}` markup with its + * value. Until Angular replaces the markup the link will be broken + * and will most likely return a 404 error. The `ngHref` directive + * solves this problem. + * + * The wrong way to write it: + * ```html + * + * ``` + * + * The correct way to write it: + * ```html + * + * ``` + * + * @element A + * @param {template} ngHref any string which can contain `{{}}` markup. + * + * @example + * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes + * in links and their different behaviors: + + +
+
link 1 (link, don't reload)
+ link 2 (link, don't reload)
+ link 3 (link, reload!)
+ anchor (link, don't reload)
+ anchor (no link)
+ link (link, change location) +
+ + it('should execute ng-click but not reload when href without value', function() { + element(by.id('link-1')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('1'); + expect(element(by.id('link-1')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click but not reload when href empty string', function() { + element(by.id('link-2')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('2'); + expect(element(by.id('link-2')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click and change url when ng-href specified', function() { + expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); + + element(by.id('link-3')).click(); + + // At this point, we navigate away from an Angular page, so we need + // to use browser.driver to get the base webdriver. + + browser.wait(function() { + return browser.driver.getCurrentUrl().then(function(url) { + return url.match(/\/123$/); + }); + }, 5000, 'page should navigate to /123'); + }); + + xit('should execute ng-click but not reload when href empty string and name specified', function() { + element(by.id('link-4')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('4'); + expect(element(by.id('link-4')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click but not reload when no href but name specified', function() { + element(by.id('link-5')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('5'); + expect(element(by.id('link-5')).getAttribute('href')).toBe(null); + }); + + it('should only change url when only ng-href', function() { + element(by.model('value')).clear(); + element(by.model('value')).sendKeys('6'); + expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); + + element(by.id('link-6')).click(); + + // At this point, we navigate away from an Angular page, so we need + // to use browser.driver to get the base webdriver. + browser.wait(function() { + return browser.driver.getCurrentUrl().then(function(url) { + return url.match(/\/6$/); + }); + }, 5000, 'page should navigate to /6'); + }); + + + */ + +/** + * @ngdoc directive + * @name ngSrc + * @restrict A + * @priority 99 + * + * @description + * Using Angular markup like `{{hash}}` in a `src` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until Angular replaces the expression inside + * `{{hash}}`. The `ngSrc` directive solves this problem. + * + * The buggy way to write it: + * ```html + * + * ``` + * + * The correct way to write it: + * ```html + * + * ``` + * + * @element IMG + * @param {template} ngSrc any string which can contain `{{}}` markup. + */ + +/** + * @ngdoc directive + * @name ngSrcset + * @restrict A + * @priority 99 + * + * @description + * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't + * work right: The browser will fetch from the URL with the literal + * text `{{hash}}` until Angular replaces the expression inside + * `{{hash}}`. The `ngSrcset` directive solves this problem. + * + * The buggy way to write it: + * ```html + * + * ``` + * + * The correct way to write it: + * ```html + * + * ``` + * + * @element IMG + * @param {template} ngSrcset any string which can contain `{{}}` markup. + */ + +/** + * @ngdoc directive + * @name ngDisabled + * @restrict A + * @priority 100 + * + * @description + * + * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: + * ```html + *
+ * + *
+ * ``` + * + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as disabled. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngDisabled` directive solves this problem for the `disabled` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * + * @example + + + Click me to toggle:
+ +
+ + it('should toggle button', function() { + expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); + }); + +
+ * + * @element INPUT + * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, + * then special attribute "disabled" will be set on the element + */ + + +/** + * @ngdoc directive + * @name ngChecked + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as checked. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngChecked` directive solves this problem for the `checked` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * @example + + + Check me to check both:
+ +
+ + it('should check both checkBoxes', function() { + expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); + element(by.model('master')).click(); + expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); + }); + +
+ * + * @element INPUT + * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, + * then special attribute "checked" will be set on the element + */ + + +/** + * @ngdoc directive + * @name ngReadonly + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as readonly. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngReadonly` directive solves this problem for the `readonly` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * @example + + + Check me to make text readonly:
+ +
+ + it('should toggle readonly attr', function() { + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); + }); + +
+ * + * @element INPUT + * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, + * then special attribute "readonly" will be set on the element + */ + + +/** + * @ngdoc directive + * @name ngSelected + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as selected. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngSelected` directive solves this problem for the `selected` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * + * @example + + + Check me to select:
+ +
+ + it('should select Greetings!', function() { + expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); + element(by.model('selected')).click(); + expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); + }); + +
+ * + * @element OPTION + * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, + * then special attribute "selected" will be set on the element + */ + +/** + * @ngdoc directive + * @name ngOpen + * @restrict A + * @priority 100 + * + * @description + * The HTML specification does not require browsers to preserve the values of boolean attributes + * such as open. (Their presence means true and their absence means false.) + * If we put an Angular interpolation expression into such an attribute then the + * binding information would be lost when the browser removes the attribute. + * The `ngOpen` directive solves this problem for the `open` attribute. + * This complementary directive is not removed by the browser and so provides + * a permanent reliable place to store the binding information. + * @example + + + Check me check multiple:
+
+ Show/Hide me +
+
+ + it('should toggle open', function() { + expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); + element(by.model('open')).click(); + expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); + }); + +
+ * + * @element DETAILS + * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, + * then special attribute "open" will be set on the element + */ + +var ngAttributeAliasDirectives = {}; + + +// boolean attrs are evaluated +forEach(BOOLEAN_ATTR, function(propName, attrName) { + // binding to multiple is not supported + if (propName == "multiple") return; + + var normalized = directiveNormalize('ng-' + attrName); + ngAttributeAliasDirectives[normalized] = function() { + return { + priority: 100, + link: function(scope, element, attr) { + scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { + attr.$set(attrName, !!value); + }); + } + }; + }; +}); + + +// ng-src, ng-srcset, ng-href are interpolated +forEach(['src', 'srcset', 'href'], function(attrName) { + var normalized = directiveNormalize('ng-' + attrName); + ngAttributeAliasDirectives[normalized] = function() { + return { + priority: 99, // it needs to run after the attributes are interpolated + link: function(scope, element, attr) { + var propName = attrName, + name = attrName; + + if (attrName === 'href' && + toString.call(element.prop('href')) === '[object SVGAnimatedString]') { + name = 'xlinkHref'; + attr.$attr[name] = 'xlink:href'; + propName = null; + } + + attr.$observe(normalized, function(value) { + if (!value) { + if (attrName === 'href') { + attr.$set(name, null); + } + return; + } + + attr.$set(name, value); + + // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist + // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need + // to set the property as well to achieve the desired effect. + // we use attr[attrName] value since $set can sanitize the url. + if (msie && propName) element.prop(propName, attr[name]); + }); + } + }; + }; +}); + +/* global -nullFormCtrl */ +var nullFormCtrl = { + $addControl: noop, + $removeControl: noop, + $setValidity: noop, + $setDirty: noop, + $setPristine: noop +}; + +/** + * @ngdoc type + * @name form.FormController + * + * @property {boolean} $pristine True if user has not interacted with the form yet. + * @property {boolean} $dirty True if user has already interacted with the form. + * @property {boolean} $valid True if all of the containing forms and controls are valid. + * @property {boolean} $invalid True if at least one containing control or form is invalid. + * + * @property {Object} $error Is an object hash, containing references to all invalid controls or + * forms, where: + * + * - keys are validation tokens (error names), + * - values are arrays of controls or forms that are invalid for given error name. + * + * + * Built-in validation tokens: + * + * - `email` + * - `max` + * - `maxlength` + * - `min` + * - `minlength` + * - `number` + * - `pattern` + * - `required` + * - `url` + * + * @description + * `FormController` keeps track of all its controls and nested forms as well as the state of them, + * such as being valid/invalid or dirty/pristine. + * + * Each {@link ng.directive:form form} directive creates an instance + * of `FormController`. + * + */ +//asks for $scope to fool the BC controller module +FormController.$inject = ['$element', '$attrs', '$scope', '$animate']; +function FormController(element, attrs, $scope, $animate) { + var form = this, + parentForm = element.parent().controller('form') || nullFormCtrl, + invalidCount = 0, // used to easily determine if we are valid + errors = form.$error = {}, + controls = []; + + // init state + form.$name = attrs.name || attrs.ngForm; + form.$dirty = false; + form.$pristine = true; + form.$valid = true; + form.$invalid = false; + + parentForm.$addControl(form); + + // Setup initial state of the control + element.addClass(PRISTINE_CLASS); + toggleValidCss(true); + + // convenience method for easy toggling of classes + function toggleValidCss(isValid, validationErrorKey) { + validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; + $animate.setClass(element, + (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey, + (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); + } + + /** + * @ngdoc method + * @name form.FormController#$addControl + * + * @description + * Register a control with the form. + * + * Input elements using ngModelController do this automatically when they are linked. + */ + form.$addControl = function(control) { + // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored + // and not added to the scope. Now we throw an error. + assertNotHasOwnProperty(control.$name, 'input'); + controls.push(control); + + if (control.$name) { + form[control.$name] = control; + } + }; + + /** + * @ngdoc method + * @name form.FormController#$removeControl + * + * @description + * Deregister a control from the form. + * + * Input elements using ngModelController do this automatically when they are destroyed. + */ + form.$removeControl = function(control) { + if (control.$name && form[control.$name] === control) { + delete form[control.$name]; + } + forEach(errors, function(queue, validationToken) { + form.$setValidity(validationToken, true, control); + }); + + arrayRemove(controls, control); + }; + + /** + * @ngdoc method + * @name form.FormController#$setValidity + * + * @description + * Sets the validity of a form control. + * + * This method will also propagate to parent forms. + */ + form.$setValidity = function(validationToken, isValid, control) { + var queue = errors[validationToken]; + + if (isValid) { + if (queue) { + arrayRemove(queue, control); + if (!queue.length) { + invalidCount--; + if (!invalidCount) { + toggleValidCss(isValid); + form.$valid = true; + form.$invalid = false; + } + errors[validationToken] = false; + toggleValidCss(true, validationToken); + parentForm.$setValidity(validationToken, true, form); + } + } + + } else { + if (!invalidCount) { + toggleValidCss(isValid); + } + if (queue) { + if (includes(queue, control)) return; + } else { + errors[validationToken] = queue = []; + invalidCount++; + toggleValidCss(false, validationToken); + parentForm.$setValidity(validationToken, false, form); + } + queue.push(control); + + form.$valid = false; + form.$invalid = true; + } + }; + + /** + * @ngdoc method + * @name form.FormController#$setDirty + * + * @description + * Sets the form to a dirty state. + * + * This method can be called to add the 'ng-dirty' class and set the form to a dirty + * state (ng-dirty class). This method will also propagate to parent forms. + */ + form.$setDirty = function() { + $animate.removeClass(element, PRISTINE_CLASS); + $animate.addClass(element, DIRTY_CLASS); + form.$dirty = true; + form.$pristine = false; + parentForm.$setDirty(); + }; + + /** + * @ngdoc method + * @name form.FormController#$setPristine + * + * @description + * Sets the form to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the form to its pristine + * state (ng-pristine class). This method will also propagate to all the controls contained + * in this form. + * + * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after + * saving or resetting it. + */ + form.$setPristine = function () { + $animate.removeClass(element, DIRTY_CLASS); + $animate.addClass(element, PRISTINE_CLASS); + form.$dirty = false; + form.$pristine = true; + forEach(controls, function(control) { + control.$setPristine(); + }); + }; +} + + +/** + * @ngdoc directive + * @name ngForm + * @restrict EAC + * + * @description + * Nestable alias of {@link ng.directive:form `form`} directive. HTML + * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a + * sub-group of controls needs to be determined. + * + * Note: the purpose of `ngForm` is to group controls, + * but not to be a replacement for the `
` tag with all of its capabilities + * (e.g. posting to the server, ...). + * + * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into + * related scope, under this name. + * + */ + + /** + * @ngdoc directive + * @name form + * @restrict E + * + * @description + * Directive that instantiates + * {@link form.FormController FormController}. + * + * If the `name` attribute is specified, the form controller is published onto the current scope under + * this name. + * + * # Alias: {@link ng.directive:ngForm `ngForm`} + * + * In Angular forms can be nested. This means that the outer form is valid when all of the child + * forms are valid as well. However, browsers do not allow nesting of `` elements, so + * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to + * `` but can be nested. This allows you to have nested forms, which is very useful when + * using Angular validation directives in forms that are dynamically generated using the + * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` + * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an + * `ngForm` directive and nest these in an outer `form` element. + * + * + * # CSS classes + * - `ng-valid` is set if the form is valid. + * - `ng-invalid` is set if the form is invalid. + * - `ng-pristine` is set if the form is pristine. + * - `ng-dirty` is set if the form is dirty. + * + * Keep in mind that ngAnimate can detect each of these classes when added and removed. + * + * + * # Submitting a form and preventing the default action + * + * Since the role of forms in client-side Angular applications is different than in classical + * roundtrip apps, it is desirable for the browser not to translate the form submission into a full + * page reload that sends the data to the server. Instead some javascript logic should be triggered + * to handle the form submission in an application-specific way. + * + * For this reason, Angular prevents the default action (form submission to the server) unless the + * `` element has an `action` attribute specified. + * + * You can use one of the following two ways to specify what javascript method should be called when + * a form is submitted: + * + * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element + * - {@link ng.directive:ngClick ngClick} directive on the first + * button or input field of type submit (input[type=submit]) + * + * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} + * or {@link ng.directive:ngClick ngClick} directives. + * This is because of the following form submission rules in the HTML specification: + * + * - If a form has only one input field then hitting enter in this field triggers form submit + * (`ngSubmit`) + * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter + * doesn't trigger submit + * - if a form has one or more input fields and one or more buttons or input[type=submit] then + * hitting enter in any of the input fields will trigger the click handler on the *first* button or + * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) + * + * + * ## Animation Hooks + * + * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. + * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any + * other validations that are performed within the form. Animations in ngForm are similar to how + * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well + * as JS animations. + * + * The following example shows a simple way to utilize CSS transitions to style a form element + * that has been rendered as invalid after it has been validated: + * + *
+ * //be sure to include ngAnimate as a module to hook into more
+ * //advanced animations
+ * .my-form {
+ *   transition:0.5s linear all;
+ *   background: white;
+ * }
+ * .my-form.ng-invalid {
+ *   background: red;
+ *   color:white;
+ * }
+ * 
+ * + * @example + + + + + + userType: + Required!
+ userType = {{userType}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+ +
+ + it('should initialize to model', function() { + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); + + expect(userType.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); + var userInput = element(by.model('userType')); + + userInput.clear(); + userInput.sendKeys(''); + + expect(userType.getText()).toEqual('userType ='); + expect(valid.getText()).toContain('false'); + }); + +
+ * + * @param {string=} name Name of the form. If specified, the form controller will be published into + * related scope, under this name. + */ +var formDirectiveFactory = function(isNgForm) { + return ['$timeout', function($timeout) { + var formDirective = { + name: 'form', + restrict: isNgForm ? 'EAC' : 'E', + controller: FormController, + compile: function() { + return { + pre: function(scope, formElement, attr, controller) { + if (!attr.action) { + // we can't use jq events because if a form is destroyed during submission the default + // action is not prevented. see #1238 + // + // IE 9 is not affected because it doesn't fire a submit event and try to do a full + // page reload if the form was destroyed by submission of the form via a click handler + // on a button in the form. Looks like an IE9 specific bug. + var preventDefaultListener = function(event) { + event.preventDefault + ? event.preventDefault() + : event.returnValue = false; // IE + }; + + addEventListenerFn(formElement[0], 'submit', preventDefaultListener); + + // unregister the preventDefault listener so that we don't not leak memory but in a + // way that will achieve the prevention of the default action. + formElement.on('$destroy', function() { + $timeout(function() { + removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); + }, 0, false); + }); + } + + var parentFormCtrl = formElement.parent().controller('form'), + alias = attr.name || attr.ngForm; + + if (alias) { + setter(scope, alias, controller, alias); + } + if (parentFormCtrl) { + formElement.on('$destroy', function() { + parentFormCtrl.$removeControl(controller); + if (alias) { + setter(scope, alias, undefined, alias); + } + extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards + }); + } + } + }; + } + }; + + return formDirective; + }]; +}; + +var formDirective = formDirectiveFactory(); +var ngFormDirective = formDirectiveFactory(true); + +/* global VALID_CLASS: true, + INVALID_CLASS: true, + PRISTINE_CLASS: true, + DIRTY_CLASS: true +*/ + +var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; +var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; +var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; + +var inputType = { + + /** + * @ngdoc input + * @name input[text] + * + * @description + * Standard HTML text input with angular data binding, inherited by most of the `input` elements. + * + * *NOTE* Not every feature offered is available for all input types. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Adds `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. + * This parameter is ignored for input[type=password] controls, which will never trim the + * input. + * + * @example + + + +
+ Single word: + + Required! + + Single word only! + + text = {{text}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); + + it('should be invalid if multi word', function() { + input.clear(); + input.sendKeys('hello world'); + + expect(valid.getText()).toContain('false'); + }); + +
+ */ + 'text': textInputType, + + + /** + * @ngdoc input + * @name input[number] + * + * @description + * Text input with number validation and transformation. Sets the `number` validation + * error if not a valid number. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ Number: + + Required! + + Not valid number! + value = {{value}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var value = element(by.binding('value')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('value')); + + it('should initialize to model', function() { + expect(value.getText()).toContain('12'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); + }); + + it('should be invalid if over max', function() { + input.clear(); + input.sendKeys('123'); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); + }); + +
+ */ + 'number': numberInputType, + + + /** + * @ngdoc input + * @name input[url] + * + * @description + * Text input with URL validation. Sets the `url` validation error key if the content is not a + * valid URL. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ URL: + + Required! + + Not valid url! + text = {{text}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+ myForm.$error.url = {{!!myForm.$error.url}}
+
+
+ + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('http://google.com/'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); + + it('should be invalid if not url', function() { + input.clear(); + input.sendKeys('box'); + + expect(valid.getText()).toContain('false'); + }); + +
+ */ + 'url': urlInputType, + + + /** + * @ngdoc input + * @name input[email] + * + * @description + * Text input with email validation. Sets the `email` validation error key if not a valid email + * address. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ Email: + + Required! + + Not valid email! + text = {{text}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+ myForm.$error.email = {{!!myForm.$error.email}}
+
+
+ + var text = element(by.binding('text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('me@example.com'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); + + it('should be invalid if not email', function() { + input.clear(); + input.sendKeys('xxx'); + + expect(valid.getText()).toContain('false'); + }); + +
+ */ + 'email': emailInputType, + + + /** + * @ngdoc input + * @name input[radio] + * + * @description + * HTML radio button. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string} value The value to which the expression should be set when selected. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {string} ngValue Angular expression which sets the value to which the expression should + * be set when selected. + * + * @example + + + +
+ Red
+ Green
+ Blue
+ color = {{color | json}}
+
+ Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. +
+ + it('should change state', function() { + var color = element(by.binding('color')); + + expect(color.getText()).toContain('blue'); + + element.all(by.model('color')).get(0).click(); + + expect(color.getText()).toContain('red'); + }); + +
+ */ + 'radio': radioInputType, + + + /** + * @ngdoc input + * @name input[checkbox] + * + * @description + * HTML checkbox. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} ngTrueValue The value to which the expression should be set when selected. + * @param {string=} ngFalseValue The value to which the expression should be set when not selected. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ Value1:
+ Value2:
+ value1 = {{value1}}
+ value2 = {{value2}}
+
+
+ + it('should change state', function() { + var value1 = element(by.binding('value1')); + var value2 = element(by.binding('value2')); + + expect(value1.getText()).toContain('true'); + expect(value2.getText()).toContain('YES'); + + element(by.model('value1')).click(); + element(by.model('value2')).click(); + + expect(value1.getText()).toContain('false'); + expect(value2.getText()).toContain('NO'); + }); + +
+ */ + 'checkbox': checkboxInputType, + + 'hidden': noop, + 'button': noop, + 'submit': noop, + 'reset': noop, + 'file': noop +}; + +// A helper function to call $setValidity and return the value / undefined, +// a pattern that is repeated a lot in the input validation logic. +function validate(ctrl, validatorName, validity, value){ + ctrl.$setValidity(validatorName, validity); + return validity ? value : undefined; +} + +function testFlags(validity, flags) { + var i, flag; + if (flags) { + for (i=0; i= minlength, value); + }; + + ctrl.$parsers.push(minLengthValidator); + ctrl.$formatters.push(minLengthValidator); + } + + // max length validator + if (attr.ngMaxlength) { + var maxlength = int(attr.ngMaxlength); + var maxLengthValidator = function(value) { + return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value); + }; + + ctrl.$parsers.push(maxLengthValidator); + ctrl.$formatters.push(maxLengthValidator); + } +} + +var numberBadFlags = ['badInput']; + +function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { + textInputType(scope, element, attr, ctrl, $sniffer, $browser); + + ctrl.$parsers.push(function(value) { + var empty = ctrl.$isEmpty(value); + if (empty || NUMBER_REGEXP.test(value)) { + ctrl.$setValidity('number', true); + return value === '' ? null : (empty ? value : parseFloat(value)); + } else { + ctrl.$setValidity('number', false); + return undefined; + } + }); + + addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState); + + ctrl.$formatters.push(function(value) { + return ctrl.$isEmpty(value) ? '' : '' + value; + }); + + if (attr.min) { + var minValidator = function(value) { + var min = parseFloat(attr.min); + return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value); + }; + + ctrl.$parsers.push(minValidator); + ctrl.$formatters.push(minValidator); + } + + if (attr.max) { + var maxValidator = function(value) { + var max = parseFloat(attr.max); + return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value); + }; + + ctrl.$parsers.push(maxValidator); + ctrl.$formatters.push(maxValidator); + } + + ctrl.$formatters.push(function(value) { + return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value); + }); +} + +function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { + textInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var urlValidator = function(value) { + return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value); + }; + + ctrl.$formatters.push(urlValidator); + ctrl.$parsers.push(urlValidator); +} + +function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { + textInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var emailValidator = function(value) { + return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value); + }; + + ctrl.$formatters.push(emailValidator); + ctrl.$parsers.push(emailValidator); +} + +function radioInputType(scope, element, attr, ctrl) { + // make the name unique, if not defined + if (isUndefined(attr.name)) { + element.attr('name', nextUid()); + } + + element.on('click', function() { + if (element[0].checked) { + scope.$apply(function() { + ctrl.$setViewValue(attr.value); + }); + } + }); + + ctrl.$render = function() { + var value = attr.value; + element[0].checked = (value == ctrl.$viewValue); + }; + + attr.$observe('value', ctrl.$render); +} + +function checkboxInputType(scope, element, attr, ctrl) { + var trueValue = attr.ngTrueValue, + falseValue = attr.ngFalseValue; + + if (!isString(trueValue)) trueValue = true; + if (!isString(falseValue)) falseValue = false; + + element.on('click', function() { + scope.$apply(function() { + ctrl.$setViewValue(element[0].checked); + }); + }); + + ctrl.$render = function() { + element[0].checked = ctrl.$viewValue; + }; + + // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox. + ctrl.$isEmpty = function(value) { + return value !== trueValue; + }; + + ctrl.$formatters.push(function(value) { + return value === trueValue; + }); + + ctrl.$parsers.push(function(value) { + return value ? trueValue : falseValue; + }); +} + + +/** + * @ngdoc directive + * @name textarea + * @restrict E + * + * @description + * HTML textarea element control with angular data-binding. The data-binding and validation + * properties of this element are exactly the same as those of the + * {@link ng.directive:input input element}. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. + */ + + +/** + * @ngdoc directive + * @name input + * @restrict E + * + * @description + * HTML input element control with angular data-binding. Input control follows HTML5 input types + * and polyfills the HTML5 validation behavior for older browsers. + * + * *NOTE* Not every feature offered is available for all input types. + * + * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {boolean=} ngRequired Sets `required` attribute if set to true + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. + * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the + * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for + * patterns defined as scope expressions. + * @param {string=} ngChange Angular expression to be executed when input changes due to user + * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. + * This parameter is ignored for input[type=password] controls, which will never trim the + * input. + * + * @example + + + +
+
+ User name: + + Required!
+ Last name: + + Too short! + + Too long!
+
+
+ user = {{user}}
+ myForm.userName.$valid = {{myForm.userName.$valid}}
+ myForm.userName.$error = {{myForm.userName.$error}}
+ myForm.lastName.$valid = {{myForm.lastName.$valid}}
+ myForm.lastName.$error = {{myForm.lastName.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+ myForm.$error.minlength = {{!!myForm.$error.minlength}}
+ myForm.$error.maxlength = {{!!myForm.$error.maxlength}}
+
+
+ + var user = element(by.binding('{{user}}')); + var userNameValid = element(by.binding('myForm.userName.$valid')); + var lastNameValid = element(by.binding('myForm.lastName.$valid')); + var lastNameError = element(by.binding('myForm.lastName.$error')); + var formValid = element(by.binding('myForm.$valid')); + var userNameInput = element(by.model('user.name')); + var userLastInput = element(by.model('user.last')); + + it('should initialize to model', function() { + expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); + expect(userNameValid.getText()).toContain('true'); + expect(formValid.getText()).toContain('true'); + }); + + it('should be invalid if empty when required', function() { + userNameInput.clear(); + userNameInput.sendKeys(''); + + expect(user.getText()).toContain('{"last":"visitor"}'); + expect(userNameValid.getText()).toContain('false'); + expect(formValid.getText()).toContain('false'); + }); + + it('should be valid if empty when min length is set', function() { + userLastInput.clear(); + userLastInput.sendKeys(''); + + expect(user.getText()).toContain('{"name":"guest","last":""}'); + expect(lastNameValid.getText()).toContain('true'); + expect(formValid.getText()).toContain('true'); + }); + + it('should be invalid if less than required min length', function() { + userLastInput.clear(); + userLastInput.sendKeys('xx'); + + expect(user.getText()).toContain('{"name":"guest"}'); + expect(lastNameValid.getText()).toContain('false'); + expect(lastNameError.getText()).toContain('minlength'); + expect(formValid.getText()).toContain('false'); + }); + + it('should be invalid if longer than max length', function() { + userLastInput.clear(); + userLastInput.sendKeys('some ridiculously long name'); + + expect(user.getText()).toContain('{"name":"guest"}'); + expect(lastNameValid.getText()).toContain('false'); + expect(lastNameError.getText()).toContain('maxlength'); + expect(formValid.getText()).toContain('false'); + }); + +
+ */ +var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { + return { + restrict: 'E', + require: '?ngModel', + link: function(scope, element, attr, ctrl) { + if (ctrl) { + (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, + $browser); + } + } + }; +}]; + +var VALID_CLASS = 'ng-valid', + INVALID_CLASS = 'ng-invalid', + PRISTINE_CLASS = 'ng-pristine', + DIRTY_CLASS = 'ng-dirty'; + +/** + * @ngdoc type + * @name ngModel.NgModelController + * + * @property {string} $viewValue Actual string value in the view. + * @property {*} $modelValue The value in the model, that the control is bound to. + * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever + the control reads value from the DOM. Each function is called, in turn, passing the value + through to the next. The last return value is used to populate the model. + Used to sanitize / convert the value as well as validation. For validation, + the parsers should update the validity state using + {@link ngModel.NgModelController#$setValidity $setValidity()}, + and return `undefined` for invalid values. + + * + * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever + the model value changes. Each function is called, in turn, passing the value through to the + next. Used to format / convert values for display in the control and validation. + * ```js + * function formatter(value) { + * if (value) { + * return value.toUpperCase(); + * } + * } + * ngModel.$formatters.push(formatter); + * ``` + * + * @property {Array.} $viewChangeListeners Array of functions to execute whenever the + * view value has changed. It is called with no arguments, and its return value is ignored. + * This can be used in place of additional $watches against the model value. + * + * @property {Object} $error An object hash with all errors as keys. + * + * @property {boolean} $pristine True if user has not interacted with the control yet. + * @property {boolean} $dirty True if user has already interacted with the control. + * @property {boolean} $valid True if there is no error. + * @property {boolean} $invalid True if at least one error on the control. + * + * @description + * + * `NgModelController` provides API for the `ng-model` directive. The controller contains + * services for data-binding, validation, CSS updates, and value formatting and parsing. It + * purposefully does not contain any logic which deals with DOM rendering or listening to + * DOM events. Such DOM related logic should be provided by other directives which make use of + * `NgModelController` for data-binding. + * + * ## Custom Control Example + * This example shows how to use `NgModelController` with a custom control to achieve + * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) + * collaborate together to achieve the desired result. + * + * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element + * contents be edited in place by the user. This will not work on older browsers. + * + * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} + * module to automatically remove "bad" content like inline event listener (e.g. ``). + * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks + * that content using the `$sce` service. + * + * + + [contenteditable] { + border: 1px solid black; + background-color: white; + min-height: 20px; + } + + .ng-invalid { + border: 1px solid red; + } + + + + angular.module('customControl', ['ngSanitize']). + directive('contenteditable', ['$sce', function($sce) { + return { + restrict: 'A', // only activate on element attribute + require: '?ngModel', // get a hold of NgModelController + link: function(scope, element, attrs, ngModel) { + if(!ngModel) return; // do nothing if no ng-model + + // Specify how UI should be updated + ngModel.$render = function() { + element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); + }; + + // Listen for change events to enable binding + element.on('blur keyup change', function() { + scope.$evalAsync(read); + }); + read(); // initialize + + // Write data to the model + function read() { + var html = element.html(); + // When we clear the content editable the browser leaves a
behind + // If strip-br attribute is provided then we strip this out + if( attrs.stripBr && html == '
' ) { + html = ''; + } + ngModel.$setViewValue(html); + } + } + }; + }]); +
+ +
+
Change me!
+ Required! +
+ +
+
+ + it('should data-bind and become invalid', function() { + if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { + // SafariDriver can't handle contenteditable + // and Firefox driver can't clear contenteditables very well + return; + } + var contentEditable = element(by.css('[contenteditable]')); + var content = 'Change me!'; + + expect(contentEditable.getText()).toEqual(content); + + contentEditable.clear(); + contentEditable.sendKeys(protractor.Key.BACK_SPACE); + expect(contentEditable.getText()).toEqual(''); + expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); + }); + + *
+ * + * + */ +var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', + function($scope, $exceptionHandler, $attr, $element, $parse, $animate) { + this.$viewValue = Number.NaN; + this.$modelValue = Number.NaN; + this.$parsers = []; + this.$formatters = []; + this.$viewChangeListeners = []; + this.$pristine = true; + this.$dirty = false; + this.$valid = true; + this.$invalid = false; + this.$name = $attr.name; + + var ngModelGet = $parse($attr.ngModel), + ngModelSet = ngModelGet.assign; + + if (!ngModelSet) { + throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", + $attr.ngModel, startingTag($element)); + } + + /** + * @ngdoc method + * @name ngModel.NgModelController#$render + * + * @description + * Called when the view needs to be updated. It is expected that the user of the ng-model + * directive will implement this method. + */ + this.$render = noop; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$isEmpty + * + * @description + * This is called when we need to determine if the value of the input is empty. + * + * For instance, the required directive does this to work out if the input has data or not. + * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. + * + * You can override this for input directives whose concept of being empty is different to the + * default. The `checkboxInputType` directive does this because in its case a value of `false` + * implies empty. + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is empty. + */ + this.$isEmpty = function(value) { + return isUndefined(value) || value === '' || value === null || value !== value; + }; + + var parentForm = $element.inheritedData('$formController') || nullFormCtrl, + invalidCount = 0, // used to easily determine if we are valid + $error = this.$error = {}; // keep invalid keys here + + + // Setup initial state of the control + $element.addClass(PRISTINE_CLASS); + toggleValidCss(true); + + // convenience method for easy toggling of classes + function toggleValidCss(isValid, validationErrorKey) { + validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; + $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); + $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); + } + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setValidity + * + * @description + * Change the validity state, and notifies the form when the control changes validity. (i.e. it + * does not notify form if given validator is already marked as invalid). + * + * This method should be called by validators - i.e. the parser or formatter functions. + * + * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign + * to `$error[validationErrorKey]=!isValid` so that it is available for data-binding. + * The `validationErrorKey` should be in camelCase and will get converted into dash-case + * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` + * class and can be bound to as `{{someForm.someControl.$error.myError}}` . + * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). + */ + this.$setValidity = function(validationErrorKey, isValid) { + // Purposeful use of ! here to cast isValid to boolean in case it is undefined + // jshint -W018 + if ($error[validationErrorKey] === !isValid) return; + // jshint +W018 + + if (isValid) { + if ($error[validationErrorKey]) invalidCount--; + if (!invalidCount) { + toggleValidCss(true); + this.$valid = true; + this.$invalid = false; + } + } else { + toggleValidCss(false); + this.$invalid = true; + this.$valid = false; + invalidCount++; + } + + $error[validationErrorKey] = !isValid; + toggleValidCss(isValid, validationErrorKey); + + parentForm.$setValidity(validationErrorKey, isValid, this); + }; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setPristine + * + * @description + * Sets the control to its pristine state. + * + * This method can be called to remove the 'ng-dirty' class and set the control to its pristine + * state (ng-pristine class). + */ + this.$setPristine = function () { + this.$dirty = false; + this.$pristine = true; + $animate.removeClass($element, DIRTY_CLASS); + $animate.addClass($element, PRISTINE_CLASS); + }; + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setViewValue + * + * @description + * Update the view value. + * + * This method should be called when the view value changes, typically from within a DOM event handler. + * For example {@link ng.directive:input input} and + * {@link ng.directive:select select} directives call it. + * + * It will update the $viewValue, then pass this value through each of the functions in `$parsers`, + * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to + * `$modelValue` and the **expression** specified in the `ng-model` attribute. + * + * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. + * + * Note that calling this function does not trigger a `$digest`. + * + * @param {string} value Value from the view. + */ + this.$setViewValue = function(value) { + this.$viewValue = value; + + // change to dirty + if (this.$pristine) { + this.$dirty = true; + this.$pristine = false; + $animate.removeClass($element, PRISTINE_CLASS); + $animate.addClass($element, DIRTY_CLASS); + parentForm.$setDirty(); + } + + forEach(this.$parsers, function(fn) { + value = fn(value); + }); + + if (this.$modelValue !== value) { + this.$modelValue = value; + ngModelSet($scope, value); + forEach(this.$viewChangeListeners, function(listener) { + try { + listener(); + } catch(e) { + $exceptionHandler(e); + } + }); + } + }; + + // model -> value + var ctrl = this; + + $scope.$watch(function ngModelWatch() { + var value = ngModelGet($scope); + + // if scope model value and ngModel value are out of sync + if (ctrl.$modelValue !== value) { + + var formatters = ctrl.$formatters, + idx = formatters.length; + + ctrl.$modelValue = value; + while(idx--) { + value = formatters[idx](value); + } + + if (ctrl.$viewValue !== value) { + ctrl.$viewValue = value; + ctrl.$render(); + } + } + + return value; + }); +}]; + + +/** + * @ngdoc directive + * @name ngModel + * + * @element input + * + * @description + * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a + * property on the scope using {@link ngModel.NgModelController NgModelController}, + * which is created and exposed by this directive. + * + * `ngModel` is responsible for: + * + * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` + * require. + * - Providing validation behavior (i.e. required, number, email, url). + * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors). + * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations. + * - Registering the control with its parent {@link ng.directive:form form}. + * + * Note: `ngModel` will try to bind to the property given by evaluating the expression on the + * current scope. If the property doesn't already exist on this scope, it will be created + * implicitly and added to the scope. + * + * For best practices on using `ngModel`, see: + * + * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) + * + * For basic examples, how to use `ngModel`, see: + * + * - {@link ng.directive:input input} + * - {@link input[text] text} + * - {@link input[checkbox] checkbox} + * - {@link input[radio] radio} + * - {@link input[number] number} + * - {@link input[email] email} + * - {@link input[url] url} + * - {@link ng.directive:select select} + * - {@link ng.directive:textarea textarea} + * + * # CSS classes + * The following CSS classes are added and removed on the associated input/select/textarea element + * depending on the validity of the model. + * + * - `ng-valid` is set if the model is valid. + * - `ng-invalid` is set if the model is invalid. + * - `ng-pristine` is set if the model is pristine. + * - `ng-dirty` is set if the model is dirty. + * + * Keep in mind that ngAnimate can detect each of these classes when added and removed. + * + * ## Animation Hooks + * + * Animations within models are triggered when any of the associated CSS classes are added and removed + * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, + * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. + * The animations that are triggered within ngModel are similar to how they work in ngClass and + * animations can be hooked into using CSS transitions, keyframes as well as JS animations. + * + * The following example shows a simple way to utilize CSS transitions to style an input element + * that has been rendered as invalid after it has been validated: + * + *
+ * //be sure to include ngAnimate as a module to hook into more
+ * //advanced animations
+ * .my-input {
+ *   transition:0.5s linear all;
+ *   background: white;
+ * }
+ * .my-input.ng-invalid {
+ *   background: red;
+ *   color:white;
+ * }
+ * 
+ * + * @example + * + + + + Update input to see transitions when valid/invalid. + Integer is a valid value. +
+ +
+
+ *
+ */ +var ngModelDirective = function() { + return { + require: ['ngModel', '^?form'], + controller: NgModelController, + link: function(scope, element, attr, ctrls) { + // notify others, especially parent forms + + var modelCtrl = ctrls[0], + formCtrl = ctrls[1] || nullFormCtrl; + + formCtrl.$addControl(modelCtrl); + + scope.$on('$destroy', function() { + formCtrl.$removeControl(modelCtrl); + }); + } + }; +}; + + +/** + * @ngdoc directive + * @name ngChange + * + * @description + * Evaluate the given expression when the user changes the input. + * The expression is evaluated immediately, unlike the JavaScript onchange event + * which only triggers at the end of a change (usually, when the user leaves the + * form element or presses the return key). + * The expression is not evaluated when the value change is coming from the model. + * + * Note, this directive requires `ngModel` to be present. + * + * @element input + * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change + * in input value. + * + * @example + * + * + * + *
+ * + * + *
+ * debug = {{confirmed}}
+ * counter = {{counter}}
+ *
+ *
+ * + * var counter = element(by.binding('counter')); + * var debug = element(by.binding('confirmed')); + * + * it('should evaluate the expression if changing from view', function() { + * expect(counter.getText()).toContain('0'); + * + * element(by.id('ng-change-example1')).click(); + * + * expect(counter.getText()).toContain('1'); + * expect(debug.getText()).toContain('true'); + * }); + * + * it('should not evaluate the expression if changing from model', function() { + * element(by.id('ng-change-example2')).click(); + + * expect(counter.getText()).toContain('0'); + * expect(debug.getText()).toContain('true'); + * }); + * + *
+ */ +var ngChangeDirective = valueFn({ + require: 'ngModel', + link: function(scope, element, attr, ctrl) { + ctrl.$viewChangeListeners.push(function() { + scope.$eval(attr.ngChange); + }); + } +}); + + +var requiredDirective = function() { + return { + require: '?ngModel', + link: function(scope, elm, attr, ctrl) { + if (!ctrl) return; + attr.required = true; // force truthy in case we are on non input element + + var validator = function(value) { + if (attr.required && ctrl.$isEmpty(value)) { + ctrl.$setValidity('required', false); + return; + } else { + ctrl.$setValidity('required', true); + return value; + } + }; + + ctrl.$formatters.push(validator); + ctrl.$parsers.unshift(validator); + + attr.$observe('required', function() { + validator(ctrl.$viewValue); + }); + } + }; +}; + + +/** + * @ngdoc directive + * @name ngList + * + * @description + * Text input that converts between a delimited string and an array of strings. The delimiter + * can be a fixed string (by default a comma) or a regular expression. + * + * @element input + * @param {string=} ngList optional delimiter that should be used to split the value. If + * specified in form `/something/` then the value will be converted into a regular expression. + * + * @example + + + +
+ List: + + Required! +
+ names = {{names}}
+ myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
+ myForm.namesInput.$error = {{myForm.namesInput.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var listInput = element(by.model('names')); + var names = element(by.binding('{{names}}')); + var valid = element(by.binding('myForm.namesInput.$valid')); + var error = element(by.css('span.error')); + + it('should initialize to model', function() { + expect(names.getText()).toContain('["igor","misko","vojta"]'); + expect(valid.getText()).toContain('true'); + expect(error.getCssValue('display')).toBe('none'); + }); + + it('should be invalid if empty', function() { + listInput.clear(); + listInput.sendKeys(''); + + expect(names.getText()).toContain(''); + expect(valid.getText()).toContain('false'); + expect(error.getCssValue('display')).not.toBe('none'); }); + +
+ */ +var ngListDirective = function() { + return { + require: 'ngModel', + link: function(scope, element, attr, ctrl) { + var match = /\/(.*)\//.exec(attr.ngList), + separator = match && new RegExp(match[1]) || attr.ngList || ','; + + var parse = function(viewValue) { + // If the viewValue is invalid (say required but empty) it will be `undefined` + if (isUndefined(viewValue)) return; + + var list = []; + + if (viewValue) { + forEach(viewValue.split(separator), function(value) { + if (value) list.push(trim(value)); + }); + } + + return list; + }; + + ctrl.$parsers.push(parse); + ctrl.$formatters.push(function(value) { + if (isArray(value)) { + return value.join(', '); + } + + return undefined; + }); + + // Override the standard $isEmpty because an empty array means the input is empty. + ctrl.$isEmpty = function(value) { + return !value || !value.length; + }; + } + }; +}; + + +var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; +/** + * @ngdoc directive + * @name ngValue + * + * @description + * Binds the given expression to the value of `input[select]` or `input[radio]`, so + * that when the element is selected, the `ngModel` of that element is set to the + * bound value. + * + * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as + * shown below. + * + * @element input + * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute + * of the `input` element + * + * @example + + + +
+

Which is your favorite?

+ +
You chose {{my.favorite}}
+
+
+ + var favorite = element(by.binding('my.favorite')); + + it('should initialize to model', function() { + expect(favorite.getText()).toContain('unicorns'); + }); + it('should bind the values to the inputs', function() { + element.all(by.model('my.favorite')).get(0).click(); + expect(favorite.getText()).toContain('pizza'); + }); + +
+ */ +var ngValueDirective = function() { + return { + priority: 100, + compile: function(tpl, tplAttr) { + if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { + return function ngValueConstantLink(scope, elm, attr) { + attr.$set('value', scope.$eval(attr.ngValue)); + }; + } else { + return function ngValueLink(scope, elm, attr) { + scope.$watch(attr.ngValue, function valueWatchAction(value) { + attr.$set('value', value); + }); + }; + } + } + }; +}; + +/** + * @ngdoc directive + * @name ngBind + * @restrict AC + * + * @description + * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element + * with the value of a given expression, and to update the text content when the value of that + * expression changes. + * + * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like + * `{{ expression }}` which is similar but less verbose. + * + * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily + * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an + * element attribute, it makes the bindings invisible to the user while the page is loading. + * + * An alternative solution to this problem would be using the + * {@link ng.directive:ngCloak ngCloak} directive. + * + * + * @element ANY + * @param {expression} ngBind {@link guide/expression Expression} to evaluate. + * + * @example + * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. + + + +
+ Enter name:
+ Hello ! +
+
+ + it('should check ng-bind', function() { + var nameInput = element(by.model('name')); + + expect(element(by.binding('name')).getText()).toBe('Whirled'); + nameInput.clear(); + nameInput.sendKeys('world'); + expect(element(by.binding('name')).getText()).toBe('world'); + }); + +
+ */ +var ngBindDirective = ngDirective({ + compile: function(templateElement) { + templateElement.addClass('ng-binding'); + return function (scope, element, attr) { + element.data('$binding', attr.ngBind); + scope.$watch(attr.ngBind, function ngBindWatchAction(value) { + // We are purposefully using == here rather than === because we want to + // catch when value is "null or undefined" + // jshint -W041 + element.text(value == undefined ? '' : value); + }); + }; + } +}); + + +/** + * @ngdoc directive + * @name ngBindTemplate + * + * @description + * The `ngBindTemplate` directive specifies that the element + * text content should be replaced with the interpolation of the template + * in the `ngBindTemplate` attribute. + * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` + * expressions. This directive is needed since some HTML elements + * (such as TITLE and OPTION) cannot contain SPAN elements. + * + * @element ANY + * @param {string} ngBindTemplate template of form + * {{ expression }} to eval. + * + * @example + * Try it here: enter text in text box and watch the greeting change. + + + +
+ Salutation:
+ Name:
+

+       
+
+ + it('should check ng-bind', function() { + var salutationElem = element(by.binding('salutation')); + var salutationInput = element(by.model('salutation')); + var nameInput = element(by.model('name')); + + expect(salutationElem.getText()).toBe('Hello World!'); + + salutationInput.clear(); + salutationInput.sendKeys('Greetings'); + nameInput.clear(); + nameInput.sendKeys('user'); + + expect(salutationElem.getText()).toBe('Greetings user!'); + }); + +
+ */ +var ngBindTemplateDirective = ['$interpolate', function($interpolate) { + return function(scope, element, attr) { + // TODO: move this to scenario runner + var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); + element.addClass('ng-binding').data('$binding', interpolateFn); + attr.$observe('ngBindTemplate', function(value) { + element.text(value); + }); + }; +}]; + + +/** + * @ngdoc directive + * @name ngBindHtml + * + * @description + * Creates a binding that will innerHTML the result of evaluating the `expression` into the current + * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link + * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` + * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in + * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to + * include "angular-sanitize.js" in your application. + * + * You may also bypass sanitization for values you know are safe. To do so, bind to + * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example + * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. + * + * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you + * will have an exception (instead of an exploit.) + * + * @element ANY + * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. + * + * @example + + + +
+

+
+
+ + + angular.module('bindHtmlExample', ['ngSanitize']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.myHTML = + 'I am an HTMLstring with ' + + 'links! and other stuff'; + }]); + + + + it('should check ng-bind-html', function() { + expect(element(by.binding('myHTML')).getText()).toBe( + 'I am an HTMLstring with links! and other stuff'); + }); + +
+ */ +var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) { + return { + compile: function (tElement) { + tElement.addClass('ng-binding'); + + return function (scope, element, attr) { + element.data('$binding', attr.ngBindHtml); + + var parsed = $parse(attr.ngBindHtml); + + function getStringValue() { + return (parsed(scope) || '').toString(); + } + + scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) { + element.html($sce.getTrustedHtml(parsed(scope)) || ''); + }); + }; + } + }; +}]; + +function classDirective(name, selector) { + name = 'ngClass' + name; + return ['$animate', function($animate) { + return { + restrict: 'AC', + link: function(scope, element, attr) { + var oldVal; + + scope.$watch(attr[name], ngClassWatchAction, true); + + attr.$observe('class', function(value) { + ngClassWatchAction(scope.$eval(attr[name])); + }); + + + if (name !== 'ngClass') { + scope.$watch('$index', function($index, old$index) { + // jshint bitwise: false + var mod = $index & 1; + if (mod !== (old$index & 1)) { + var classes = arrayClasses(scope.$eval(attr[name])); + mod === selector ? + addClasses(classes) : + removeClasses(classes); + } + }); + } + + function addClasses(classes) { + var newClasses = digestClassCounts(classes, 1); + attr.$addClass(newClasses); + } + + function removeClasses(classes) { + var newClasses = digestClassCounts(classes, -1); + attr.$removeClass(newClasses); + } + + function digestClassCounts (classes, count) { + var classCounts = element.data('$classCounts') || {}; + var classesToUpdate = []; + forEach(classes, function (className) { + if (count > 0 || classCounts[className]) { + classCounts[className] = (classCounts[className] || 0) + count; + if (classCounts[className] === +(count > 0)) { + classesToUpdate.push(className); + } + } + }); + element.data('$classCounts', classCounts); + return classesToUpdate.join(' '); + } + + function updateClasses (oldClasses, newClasses) { + var toAdd = arrayDifference(newClasses, oldClasses); + var toRemove = arrayDifference(oldClasses, newClasses); + toRemove = digestClassCounts(toRemove, -1); + toAdd = digestClassCounts(toAdd, 1); + + if (toAdd.length === 0) { + $animate.removeClass(element, toRemove); + } else if (toRemove.length === 0) { + $animate.addClass(element, toAdd); + } else { + $animate.setClass(element, toAdd, toRemove); + } + } + + function ngClassWatchAction(newVal) { + if (selector === true || scope.$index % 2 === selector) { + var newClasses = arrayClasses(newVal || []); + if (!oldVal) { + addClasses(newClasses); + } else if (!equals(newVal,oldVal)) { + var oldClasses = arrayClasses(oldVal); + updateClasses(oldClasses, newClasses); + } + } + oldVal = shallowCopy(newVal); + } + } + }; + + function arrayDifference(tokens1, tokens2) { + var values = []; + + outer: + for(var i = 0; i < tokens1.length; i++) { + var token = tokens1[i]; + for(var j = 0; j < tokens2.length; j++) { + if(token == tokens2[j]) continue outer; + } + values.push(token); + } + return values; + } + + function arrayClasses (classVal) { + if (isArray(classVal)) { + return classVal; + } else if (isString(classVal)) { + return classVal.split(' '); + } else if (isObject(classVal)) { + var classes = [], i = 0; + forEach(classVal, function(v, k) { + if (v) { + classes = classes.concat(k.split(' ')); + } + }); + return classes; + } + return classVal; + } + }]; +} + +/** + * @ngdoc directive + * @name ngClass + * @restrict AC + * + * @description + * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding + * an expression that represents all classes to be added. + * + * The directive operates in three different ways, depending on which of three types the expression + * evaluates to: + * + * 1. If the expression evaluates to a string, the string should be one or more space-delimited class + * names. + * + * 2. If the expression evaluates to an array, each element of the array should be a string that is + * one or more space-delimited class names. + * + * 3. If the expression evaluates to an object, then for each key-value pair of the + * object with a truthy value the corresponding key is used as a class name. + * + * The directive won't add duplicate classes if a particular class was already set. + * + * When the expression changes, the previously added classes are removed and only then the + * new classes are added. + * + * @animations + * add - happens just before the class is applied to the element + * remove - happens just before the class is removed from the element + * + * @element ANY + * @param {expression} ngClass {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class + * names, an array, or a map of class names to boolean values. In the case of a map, the + * names of the properties whose values are truthy will be added as css classes to the + * element. + * + * @example Example that demonstrates basic bindings via ngClass directive. + + +

Map Syntax Example

+ deleted (apply "strike" class)
+ important (apply "bold" class)
+ error (apply "red" class) +
+

Using String Syntax

+ +
+

Using Array Syntax

+
+
+
+
+ + .strike { + text-decoration: line-through; + } + .bold { + font-weight: bold; + } + .red { + color: red; + } + + + var ps = element.all(by.css('p')); + + it('should let you toggle the class', function() { + + expect(ps.first().getAttribute('class')).not.toMatch(/bold/); + expect(ps.first().getAttribute('class')).not.toMatch(/red/); + + element(by.model('important')).click(); + expect(ps.first().getAttribute('class')).toMatch(/bold/); + + element(by.model('error')).click(); + expect(ps.first().getAttribute('class')).toMatch(/red/); + }); + + it('should let you toggle string example', function() { + expect(ps.get(1).getAttribute('class')).toBe(''); + element(by.model('style')).clear(); + element(by.model('style')).sendKeys('red'); + expect(ps.get(1).getAttribute('class')).toBe('red'); + }); + + it('array example should have 3 classes', function() { + expect(ps.last().getAttribute('class')).toBe(''); + element(by.model('style1')).sendKeys('bold'); + element(by.model('style2')).sendKeys('strike'); + element(by.model('style3')).sendKeys('red'); + expect(ps.last().getAttribute('class')).toBe('bold strike red'); + }); + +
+ + ## Animations + + The example below demonstrates how to perform animations using ngClass. + + + + + +
+ Sample Text +
+ + .base-class { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .base-class.my-class { + color: red; + font-size:3em; + } + + + it('should check ng-class', function() { + expect(element(by.css('.base-class')).getAttribute('class')).not. + toMatch(/my-class/); + + element(by.id('setbtn')).click(); + + expect(element(by.css('.base-class')).getAttribute('class')). + toMatch(/my-class/); + + element(by.id('clearbtn')).click(); + + expect(element(by.css('.base-class')).getAttribute('class')).not. + toMatch(/my-class/); + }); + +
+ + + ## ngClass and pre-existing CSS3 Transitions/Animations + The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. + Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder + any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure + to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and + {@link ngAnimate.$animate#removeclass $animate.removeClass}. + */ +var ngClassDirective = classDirective('', true); + +/** + * @ngdoc directive + * @name ngClassOdd + * @restrict AC + * + * @description + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. + * + * This directive can be applied only within the scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @element ANY + * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class names or an array. + * + * @example + + +
    +
  1. + + {{name}} + +
  2. +
+
+ + .odd { + color: red; + } + .even { + color: blue; + } + + + it('should check ng-class-odd and ng-class-even', function() { + expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). + toMatch(/odd/); + expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). + toMatch(/even/); + }); + +
+ */ +var ngClassOddDirective = classDirective('Odd', 0); + +/** + * @ngdoc directive + * @name ngClassEven + * @restrict AC + * + * @description + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. + * + * This directive can be applied only within the scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @element ANY + * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The + * result of the evaluation can be a string representing space delimited class names or an array. + * + * @example + + +
    +
  1. + + {{name}}       + +
  2. +
+
+ + .odd { + color: red; + } + .even { + color: blue; + } + + + it('should check ng-class-odd and ng-class-even', function() { + expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). + toMatch(/odd/); + expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). + toMatch(/even/); + }); + +
+ */ +var ngClassEvenDirective = classDirective('Even', 1); + +/** + * @ngdoc directive + * @name ngCloak + * @restrict AC + * + * @description + * The `ngCloak` directive is used to prevent the Angular html template from being briefly + * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this + * directive to avoid the undesirable flicker effect caused by the html template display. + * + * The directive can be applied to the `` element, but the preferred usage is to apply + * multiple `ngCloak` directives to small portions of the page to permit progressive rendering + * of the browser view. + * + * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and + * `angular.min.js`. + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```css + * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { + * display: none !important; + * } + * ``` + * + * When this css rule is loaded by the browser, all html elements (including their children) that + * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive + * during the compilation of the template it deletes the `ngCloak` element attribute, making + * the compiled element visible. + * + * For the best result, the `angular.js` script must be loaded in the head section of the html + * document; alternatively, the css rule above must be included in the external stylesheet of the + * application. + * + * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they + * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css + * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. + * + * @element ANY + * + * @example + + +
{{ 'hello' }}
+
{{ 'hello IE7' }}
+
+ + it('should remove the template directive and css class', function() { + expect($('#template1').getAttribute('ng-cloak')). + toBeNull(); + expect($('#template2').getAttribute('ng-cloak')). + toBeNull(); + }); + +
+ * + */ +var ngCloakDirective = ngDirective({ + compile: function(element, attr) { + attr.$set('ngCloak', undefined); + element.removeClass('ng-cloak'); + } +}); + +/** + * @ngdoc directive + * @name ngController + * + * @description + * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular + * supports the principles behind the Model-View-Controller design pattern. + * + * MVC components in angular: + * + * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties + * are accessed through bindings. + * * View — The template (HTML with data bindings) that is rendered into the View. + * * Controller — The `ngController` directive specifies a Controller class; the class contains business + * logic behind the application to decorate the scope with functions and values + * + * Note that you can also attach controllers to the DOM by declaring it in a route definition + * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller + * again using `ng-controller` in the template itself. This will cause the controller to be attached + * and executed twice. + * + * @element ANY + * @scope + * @priority 500 + * @param {expression} ngController Name of a globally accessible constructor function or an + * {@link guide/expression expression} that on the current scope evaluates to a + * constructor function. The controller instance can be published into a scope property + * by specifying `as propertyName`. + * + * @example + * Here is a simple form for editing user contact information. Adding, removing, clearing, and + * greeting are methods declared on the controller (see source tab). These methods can + * easily be called from the angular markup. Any changes to the data are automatically reflected + * in the View without the need for a manual update. + * + * Two different declaration styles are included below: + * + * * one binds methods and properties directly onto the controller using `this`: + * `ng-controller="SettingsController1 as settings"` + * * one injects `$scope` into the controller: + * `ng-controller="SettingsController2"` + * + * The second option is more common in the Angular community, and is generally used in boilerplates + * and in this guide. However, there are advantages to binding properties directly to the controller + * and avoiding scope. + * + * * Using `controller as` makes it obvious which controller you are accessing in the template when + * multiple controllers apply to an element. + * * If you are writing your controllers as classes you have easier access to the properties and + * methods, which will appear on the scope, from inside the controller code. + * * Since there is always a `.` in the bindings, you don't have to worry about prototypal + * inheritance masking primitives. + * + * This example demonstrates the `controller as` syntax. + * + * + * + *
+ * Name: + * [ greet ]
+ * Contact: + *
    + *
  • + * + * + * [ clear + * | X ] + *
  • + *
  • [ add ]
  • + *
+ *
+ *
+ * + * angular.module('controllerAsExample', []) + * .controller('SettingsController1', SettingsController1); + * + * function SettingsController1() { + * this.name = "John Smith"; + * this.contacts = [ + * {type: 'phone', value: '408 555 1212'}, + * {type: 'email', value: 'john.smith@example.org'} ]; + * } + * + * SettingsController1.prototype.greet = function() { + * alert(this.name); + * }; + * + * SettingsController1.prototype.addContact = function() { + * this.contacts.push({type: 'email', value: 'yourname@example.org'}); + * }; + * + * SettingsController1.prototype.removeContact = function(contactToRemove) { + * var index = this.contacts.indexOf(contactToRemove); + * this.contacts.splice(index, 1); + * }; + * + * SettingsController1.prototype.clearContact = function(contact) { + * contact.type = 'phone'; + * contact.value = ''; + * }; + * + * + * it('should check controller as', function() { + * var container = element(by.id('ctrl-as-exmpl')); + * expect(container.element(by.model('settings.name')) + * .getAttribute('value')).toBe('John Smith'); + * + * var firstRepeat = + * container.element(by.repeater('contact in settings.contacts').row(0)); + * var secondRepeat = + * container.element(by.repeater('contact in settings.contacts').row(1)); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('408 555 1212'); + * + * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('john.smith@example.org'); + * + * firstRepeat.element(by.linkText('clear')).click(); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe(''); + * + * container.element(by.linkText('add')).click(); + * + * expect(container.element(by.repeater('contact in settings.contacts').row(2)) + * .element(by.model('contact.value')) + * .getAttribute('value')) + * .toBe('yourname@example.org'); + * }); + * + *
+ * + * This example demonstrates the "attach to `$scope`" style of controller. + * + * + * + *
+ * Name: + * [ greet ]
+ * Contact: + *
    + *
  • + * + * + * [ clear + * | X ] + *
  • + *
  • [ add ]
  • + *
+ *
+ *
+ * + * angular.module('controllerExample', []) + * .controller('SettingsController2', ['$scope', SettingsController2]); + * + * function SettingsController2($scope) { + * $scope.name = "John Smith"; + * $scope.contacts = [ + * {type:'phone', value:'408 555 1212'}, + * {type:'email', value:'john.smith@example.org'} ]; + * + * $scope.greet = function() { + * alert($scope.name); + * }; + * + * $scope.addContact = function() { + * $scope.contacts.push({type:'email', value:'yourname@example.org'}); + * }; + * + * $scope.removeContact = function(contactToRemove) { + * var index = $scope.contacts.indexOf(contactToRemove); + * $scope.contacts.splice(index, 1); + * }; + * + * $scope.clearContact = function(contact) { + * contact.type = 'phone'; + * contact.value = ''; + * }; + * } + * + * + * it('should check controller', function() { + * var container = element(by.id('ctrl-exmpl')); + * + * expect(container.element(by.model('name')) + * .getAttribute('value')).toBe('John Smith'); + * + * var firstRepeat = + * container.element(by.repeater('contact in contacts').row(0)); + * var secondRepeat = + * container.element(by.repeater('contact in contacts').row(1)); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('408 555 1212'); + * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('john.smith@example.org'); + * + * firstRepeat.element(by.linkText('clear')).click(); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe(''); + * + * container.element(by.linkText('add')).click(); + * + * expect(container.element(by.repeater('contact in contacts').row(2)) + * .element(by.model('contact.value')) + * .getAttribute('value')) + * .toBe('yourname@example.org'); + * }); + * + *
+ + */ +var ngControllerDirective = [function() { + return { + scope: true, + controller: '@', + priority: 500 + }; +}]; + +/** + * @ngdoc directive + * @name ngCsp + * + * @element html + * @description + * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. + * + * This is necessary when developing things like Google Chrome Extensions. + * + * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). + * For Angular to be CSP compatible there are only two things that we need to do differently: + * + * - don't use `Function` constructor to generate optimized value getters + * - don't inject custom stylesheet into the document + * + * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` + * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will + * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will + * be raised. + * + * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically + * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). + * To make those directives work in CSP mode, include the `angular-csp.css` manually. + * + * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This + * autodetection however triggers a CSP error to be logged in the console: + * + * ``` + * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of + * script in the following Content Security Policy directive: "default-src 'self'". Note that + * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. + * ``` + * + * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` + * directive on the root element of the application or on the `angular.js` script tag, whichever + * appears first in the html document. + * + * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* + * + * @example + * This example shows how to apply the `ngCsp` directive to the `html` tag. + ```html + + + ... + ... + + ``` + */ + +// ngCsp is not implemented as a proper directive any more, because we need it be processed while we +// bootstrap the system (before $parse is instantiated), for this reason we just have +// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc + +/** + * @ngdoc directive + * @name ngClick + * + * @description + * The ngClick directive allows you to specify custom behavior when + * an element is clicked. + * + * @element ANY + * @priority 0 + * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon + * click. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + + count: {{count}} + + + + it('should check ng-click', function() { + expect(element(by.binding('count')).getText()).toMatch('0'); + element(by.css('button')).click(); + expect(element(by.binding('count')).getText()).toMatch('1'); + }); + + + */ +/* + * A collection of directives that allows creation of custom event handlers that are defined as + * angular expressions and are compiled and executed within the current scope. + */ +var ngEventDirectives = {}; + +// For events that might fire synchronously during DOM manipulation +// we need to execute their event handlers asynchronously using $evalAsync, +// so that they are not executed in an inconsistent state. +var forceAsyncEvents = { + 'blur': true, + 'focus': true +}; +forEach( + 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), + function(eventName) { + var directiveName = directiveNormalize('ng-' + eventName); + ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) { + return { + compile: function($element, attr) { + // We expose the powerful $event object on the scope that provides access to the Window, + // etc. that isn't protected by the fast paths in $parse. We explicitly request better + // checks at the cost of speed since event handler expressions are not executed as + // frequently as regular change detection. + var fn = $parse(attr[directiveName], /* expensiveChecks */ true); + return function ngEventHandler(scope, element) { + element.on(eventName, function(event) { + var callback = function() { + fn(scope, {$event:event}); + }; + if (forceAsyncEvents[eventName] && $rootScope.$$phase) { + scope.$evalAsync(callback); + } else { + scope.$apply(callback); + } + }); + }; + } + }; + }]; + } +); + +/** + * @ngdoc directive + * @name ngDblclick + * + * @description + * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. + * + * @element ANY + * @priority 0 + * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon + * a dblclick. (The Event object is available as `$event`) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMousedown + * + * @description + * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon + * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMouseup + * + * @description + * Specify custom behavior on mouseup event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon + * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + +/** + * @ngdoc directive + * @name ngMouseover + * + * @description + * Specify custom behavior on mouseover event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon + * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMouseenter + * + * @description + * Specify custom behavior on mouseenter event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon + * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMouseleave + * + * @description + * Specify custom behavior on mouseleave event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon + * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngMousemove + * + * @description + * Specify custom behavior on mousemove event. + * + * @element ANY + * @priority 0 + * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon + * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngKeydown + * + * @description + * Specify custom behavior on keydown event. + * + * @element ANY + * @priority 0 + * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon + * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + + + + key down count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngKeyup + * + * @description + * Specify custom behavior on keyup event. + * + * @element ANY + * @priority 0 + * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon + * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * + * @example + + +

Typing in the input box below updates the key count

+ key up count: {{count}} + +

Typing in the input box below updates the keycode

+ +

event keyCode: {{ event.keyCode }}

+

event altKey: {{ event.altKey }}

+
+
+ */ + + +/** + * @ngdoc directive + * @name ngKeypress + * + * @description + * Specify custom behavior on keypress event. + * + * @element ANY + * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon + * keypress. ({@link guide/expression#-event- Event object is available as `$event`} + * and can be interrogated for keyCode, altKey, etc.) + * + * @example + + + + key press count: {{count}} + + + */ + + +/** + * @ngdoc directive + * @name ngSubmit + * + * @description + * Enables binding angular expressions to onsubmit events. + * + * Additionally it prevents the default action (which for form means sending the request to the + * server and reloading the current page), but only if the form does not contain `action`, + * `data-action`, or `x-action` attributes. + * + *
+ * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and + * `ngSubmit` handlers together. See the + * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} + * for a detailed discussion of when `ngSubmit` may be triggered. + *
+ * + * @element form + * @priority 0 + * @param {expression} ngSubmit {@link guide/expression Expression} to eval. + * ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + +
+ Enter text and hit enter: + + +
list={{list}}
+
+
+ + it('should check ng-submit', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + expect(element(by.model('text')).getAttribute('value')).toBe(''); + }); + it('should ignore empty strings', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + }); + +
+ */ + +/** + * @ngdoc directive + * @name ngFocus + * + * @description + * Specify custom behavior on focus event. + * + * Note: As the `focus` event is executed synchronously when calling `input.focus()` + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon + * focus. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ngBlur + * + * @description + * Specify custom behavior on blur event. + * + * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when + * an element has lost focus. + * + * Note: As the `blur` event is executed synchronously also during DOM manipulations + * (e.g. removing a focussed input), + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon + * blur. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ngCopy + * + * @description + * Specify custom behavior on copy event. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon + * copy. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + copied: {{copied}} + + + */ + +/** + * @ngdoc directive + * @name ngCut + * + * @description + * Specify custom behavior on cut event. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon + * cut. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + cut: {{cut}} + + + */ + +/** + * @ngdoc directive + * @name ngPaste + * + * @description + * Specify custom behavior on paste event. + * + * @element window, input, select, textarea, a + * @priority 0 + * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon + * paste. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + pasted: {{paste}} + + + */ + +/** + * @ngdoc directive + * @name ngIf + * @restrict A + * + * @description + * The `ngIf` directive removes or recreates a portion of the DOM tree based on an + * {expression}. If the expression assigned to `ngIf` evaluates to a false + * value then the element is removed from the DOM, otherwise a clone of the + * element is reinserted into the DOM. + * + * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the + * element in the DOM rather than changing its visibility via the `display` css property. A common + * case when this difference is significant is when using css selectors that rely on an element's + * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. + * + * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope + * is created when the element is restored. The scope created within `ngIf` inherits from + * its parent scope using + * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). + * An important implication of this is if `ngModel` is used within `ngIf` to bind to + * a javascript primitive defined in the parent scope. In this case any modifications made to the + * variable within the child scope will override (hide) the value in the parent scope. + * + * Also, `ngIf` recreates elements using their compiled state. An example of this behavior + * is if an element's class attribute is directly modified after it's compiled, using something like + * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element + * the added class will be lost because the original compiled state is used to regenerate the element. + * + * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` + * and `leave` effects. + * + * @animations + * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container + * leave - happens just before the `ngIf` contents are removed from the DOM + * + * @element ANY + * @scope + * @priority 600 + * @param {expression} ngIf If the {@link guide/expression expression} is falsy then + * the element is removed from the DOM tree. If it is truthy a copy of the compiled + * element is added to the DOM tree. + * + * @example + + + Click me:
+ Show when checked: + + I'm removed when the checkbox is unchecked. + +
+ + .animate-if { + background:white; + border:1px solid black; + padding:10px; + } + + .animate-if.ng-enter, .animate-if.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .animate-if.ng-enter, + .animate-if.ng-leave.ng-leave-active { + opacity:0; + } + + .animate-if.ng-leave, + .animate-if.ng-enter.ng-enter-active { + opacity:1; + } + +
+ */ +var ngIfDirective = ['$animate', function($animate) { + return { + transclude: 'element', + priority: 600, + terminal: true, + restrict: 'A', + $$tlb: true, + link: function ($scope, $element, $attr, ctrl, $transclude) { + var block, childScope, previousElements; + $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { + + if (toBoolean(value)) { + if (!childScope) { + childScope = $scope.$new(); + $transclude(childScope, function (clone) { + clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block = { + clone: clone + }; + $animate.enter(clone, $element.parent(), $element); + }); + } + } else { + if(previousElements) { + previousElements.remove(); + previousElements = null; + } + if(childScope) { + childScope.$destroy(); + childScope = null; + } + if(block) { + previousElements = getBlockElements(block.clone); + $animate.leave(previousElements, function() { + previousElements = null; + }); + block = null; + } + } + }); + } + }; +}]; + +/** + * @ngdoc directive + * @name ngInclude + * @restrict ECA + * + * @description + * Fetches, compiles and includes an external HTML fragment. + * + * By default, the template URL is restricted to the same domain and protocol as the + * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols + * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or + * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link + * ng.$sce Strict Contextual Escaping}. + * + * In addition, the browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy may further restrict whether the template is successfully loaded. + * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` + * access on some browsers. + * + * @animations + * enter - animation is used to bring new content into the browser. + * leave - animation is used to animate existing content away. + * + * The enter and leave animation occur concurrently. + * + * @scope + * @priority 400 + * + * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, + * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. + * @param {string=} onload Expression to evaluate when a new partial is loaded. + * + * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll + * $anchorScroll} to scroll the viewport after the content is loaded. + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the expression evaluates to truthy value. + * + * @example + + +
+ + url of the template: {{template.url}} +
+
+
+
+
+
+ + angular.module('includeExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.templates = + [ { name: 'template1.html', url: 'template1.html'}, + { name: 'template2.html', url: 'template2.html'} ]; + $scope.template = $scope.templates[0]; + }]); + + + Content of template1.html + + + Content of template2.html + + + .slide-animate-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .slide-animate { + padding:10px; + } + + .slide-animate.ng-enter, .slide-animate.ng-leave { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + display:block; + padding:10px; + } + + .slide-animate.ng-enter { + top:-50px; + } + .slide-animate.ng-enter.ng-enter-active { + top:0; + } + + .slide-animate.ng-leave { + top:0; + } + .slide-animate.ng-leave.ng-leave-active { + top:50px; + } + + + var templateSelect = element(by.model('template')); + var includeElem = element(by.css('[ng-include]')); + + it('should load template1.html', function() { + expect(includeElem.getText()).toMatch(/Content of template1.html/); + }); + + it('should load template2.html', function() { + if (browser.params.browser == 'firefox') { + // Firefox can't handle using selects + // See https://github.com/angular/protractor/issues/480 + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(2).click(); + expect(includeElem.getText()).toMatch(/Content of template2.html/); + }); + + it('should change to blank', function() { + if (browser.params.browser == 'firefox') { + // Firefox can't handle using selects + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(0).click(); + expect(includeElem.isPresent()).toBe(false); + }); + +
+ */ + + +/** + * @ngdoc event + * @name ngInclude#$includeContentRequested + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted every time the ngInclude content is requested. + */ + + +/** + * @ngdoc event + * @name ngInclude#$includeContentLoaded + * @eventType emit on the current ngInclude scope + * @description + * Emitted every time the ngInclude content is reloaded. + */ +var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce', + function($http, $templateCache, $anchorScroll, $animate, $sce) { + return { + restrict: 'ECA', + priority: 400, + terminal: true, + transclude: 'element', + controller: angular.noop, + compile: function(element, attr) { + var srcExp = attr.ngInclude || attr.src, + onloadExp = attr.onload || '', + autoScrollExp = attr.autoscroll; + + return function(scope, $element, $attr, ctrl, $transclude) { + var changeCounter = 0, + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function() { + if(previousElement) { + previousElement.remove(); + previousElement = null; + } + if(currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if(currentElement) { + $animate.leave(currentElement, function() { + previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; + + scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { + var afterAnimation = function() { + if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }; + var thisChangeId = ++changeCounter; + + if (src) { + $http.get(src, {cache: $templateCache}).success(function(response) { + if (thisChangeId !== changeCounter) return; + var newScope = scope.$new(); + ctrl.template = response; + + // Note: This will also link all children of ng-include that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-include on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, null, $element, afterAnimation); + }); + + currentScope = newScope; + currentElement = clone; + + currentScope.$emit('$includeContentLoaded'); + scope.$eval(onloadExp); + }).error(function() { + if (thisChangeId === changeCounter) cleanupLastIncludeContent(); + }); + scope.$emit('$includeContentRequested'); + } else { + cleanupLastIncludeContent(); + ctrl.template = null; + } + }); + }; + } + }; +}]; + +// This directive is called during the $transclude call of the first `ngInclude` directive. +// It will replace and compile the content of the element with the loaded template. +// We need this directive so that the element content is already filled when +// the link function of another directive on the same element as ngInclude +// is called. +var ngIncludeFillContentDirective = ['$compile', + function($compile) { + return { + restrict: 'ECA', + priority: -400, + require: 'ngInclude', + link: function(scope, $element, $attr, ctrl) { + $element.html(ctrl.template); + $compile($element.contents())(scope); + } + }; + }]; + +/** + * @ngdoc directive + * @name ngInit + * @restrict AC + * + * @description + * The `ngInit` directive allows you to evaluate an expression in the + * current scope. + * + *
+ * The only appropriate use of `ngInit` is for aliasing special properties of + * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you + * should use {@link guide/controller controllers} rather than `ngInit` + * to initialize values on a scope. + *
+ *
+ * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make + * sure you have parenthesis for correct precedence: + *
+ *   
+ *
+ *
+ * + * @priority 450 + * + * @element ANY + * @param {expression} ngInit {@link guide/expression Expression} to eval. + * + * @example + + + +
+
+
+ list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}}; +
+
+
+
+ + it('should alias index positions', function() { + var elements = element.all(by.css('.example-init')); + expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); + expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); + expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); + expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); + }); + +
+ */ +var ngInitDirective = ngDirective({ + priority: 450, + compile: function() { + return { + pre: function(scope, element, attrs) { + scope.$eval(attrs.ngInit); + } + }; + } +}); + +/** + * @ngdoc directive + * @name ngNonBindable + * @restrict AC + * @priority 1000 + * + * @description + * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current + * DOM element. This is useful if the element contains what appears to be Angular directives and + * bindings but which should be ignored by Angular. This could be the case if you have a site that + * displays snippets of code, for instance. + * + * @element ANY + * + * @example + * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, + * but the one wrapped in `ngNonBindable` is left alone. + * + * @example + + +
Normal: {{1 + 2}}
+
Ignored: {{1 + 2}}
+
+ + it('should check ng-non-bindable', function() { + expect(element(by.binding('1 + 2')).getText()).toContain('3'); + expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); + }); + +
+ */ +var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); + +/** + * @ngdoc directive + * @name ngPluralize + * @restrict EA + * + * @description + * `ngPluralize` is a directive that displays messages according to en-US localization rules. + * These rules are bundled with angular.js, but can be overridden + * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive + * by specifying the mappings between + * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) + * and the strings to be displayed. + * + * # Plural categories and explicit number rules + * There are two + * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) + * in Angular's default en-US locale: "one" and "other". + * + * While a plural category may match many numbers (for example, in en-US locale, "other" can match + * any number that is not 1), an explicit number rule can only match one number. For example, the + * explicit number rule for "3" matches the number 3. There are examples of plural categories + * and explicit number rules throughout the rest of this documentation. + * + * # Configuring ngPluralize + * You configure ngPluralize by providing 2 attributes: `count` and `when`. + * You can also provide an optional attribute, `offset`. + * + * The value of the `count` attribute can be either a string or an {@link guide/expression + * Angular expression}; these are evaluated on the current scope for its bound value. + * + * The `when` attribute specifies the mappings between plural categories and the actual + * string to be displayed. The value of the attribute should be a JSON object. + * + * The following example shows how to configure ngPluralize: + * + * ```html + * + * + *``` + * + * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not + * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" + * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for + * other numbers, for example 12, so that instead of showing "12 people are viewing", you can + * show "a dozen people are viewing". + * + * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted + * into pluralized strings. In the previous example, Angular will replace `{}` with + * `{{personCount}}`. The closed braces `{}` is a placeholder + * for {{numberExpression}}. + * + * # Configuring ngPluralize with offset + * The `offset` attribute allows further customization of pluralized text, which can result in + * a better user experience. For example, instead of the message "4 people are viewing this document", + * you might display "John, Kate and 2 others are viewing this document". + * The offset attribute allows you to offset a number by any desired value. + * Let's take a look at an example: + * + * ```html + * + * + * ``` + * + * Notice that we are still using two plural categories(one, other), but we added + * three explicit number rules 0, 1 and 2. + * When one person, perhaps John, views the document, "John is viewing" will be shown. + * When three people view the document, no explicit number rule is found, so + * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. + * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" + * is shown. + * + * Note that when you specify offsets, you must provide explicit number rules for + * numbers from 0 up to and including the offset. If you use an offset of 3, for example, + * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for + * plural categories "one" and "other". + * + * @param {string|expression} count The variable to be bound to. + * @param {string} when The mapping between plural category to its corresponding strings. + * @param {number=} offset Offset to deduct from the total number. + * + * @example + + + +
+ Person 1:
+ Person 2:
+ Number of People:
+ + + Without Offset: + +
+ + + With Offset(2): + + +
+
+ + it('should show correct pluralized string', function() { + var withoutOffset = element.all(by.css('ng-pluralize')).get(0); + var withOffset = element.all(by.css('ng-pluralize')).get(1); + var countInput = element(by.model('personCount')); + + expect(withoutOffset.getText()).toEqual('1 person is viewing.'); + expect(withOffset.getText()).toEqual('Igor is viewing.'); + + countInput.clear(); + countInput.sendKeys('0'); + + expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); + expect(withOffset.getText()).toEqual('Nobody is viewing.'); + + countInput.clear(); + countInput.sendKeys('2'); + + expect(withoutOffset.getText()).toEqual('2 people are viewing.'); + expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); + + countInput.clear(); + countInput.sendKeys('3'); + + expect(withoutOffset.getText()).toEqual('3 people are viewing.'); + expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); + + countInput.clear(); + countInput.sendKeys('4'); + + expect(withoutOffset.getText()).toEqual('4 people are viewing.'); + expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); + }); + it('should show data-bound names', function() { + var withOffset = element.all(by.css('ng-pluralize')).get(1); + var personCount = element(by.model('personCount')); + var person1 = element(by.model('person1')); + var person2 = element(by.model('person2')); + personCount.clear(); + personCount.sendKeys('4'); + person1.clear(); + person1.sendKeys('Di'); + person2.clear(); + person2.sendKeys('Vojta'); + expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); + }); + +
+ */ +var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { + var BRACE = /{}/g; + return { + restrict: 'EA', + link: function(scope, element, attr) { + var numberExp = attr.count, + whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs + offset = attr.offset || 0, + whens = scope.$eval(whenExp) || {}, + whensExpFns = {}, + startSymbol = $interpolate.startSymbol(), + endSymbol = $interpolate.endSymbol(), + isWhen = /^when(Minus)?(.+)$/; + + forEach(attr, function(expression, attributeName) { + if (isWhen.test(attributeName)) { + whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = + element.attr(attr.$attr[attributeName]); + } + }); + forEach(whens, function(expression, key) { + whensExpFns[key] = + $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + + offset + endSymbol)); + }); + + scope.$watch(function ngPluralizeWatch() { + var value = parseFloat(scope.$eval(numberExp)); + + if (!isNaN(value)) { + //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, + //check it against pluralization rules in $locale service + if (!(value in whens)) value = $locale.pluralCat(value - offset); + return whensExpFns[value](scope, element, true); + } else { + return ''; + } + }, function ngPluralizeWatchAction(newVal) { + element.text(newVal); + }); + } + }; +}]; + +/** + * @ngdoc directive + * @name ngRepeat + * + * @description + * The `ngRepeat` directive instantiates a template once per item from a collection. Each template + * instance gets its own scope, where the given loop variable is set to the current collection item, + * and `$index` is set to the item index or key. + * + * Special properties are exposed on the local scope of each template instance, including: + * + * | Variable | Type | Details | + * |-----------|-----------------|-----------------------------------------------------------------------------| + * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | + * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | + * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | + * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | + * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | + * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | + * + * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. + * This may be useful when, for instance, nesting ngRepeats. + * + * # Special repeat start and end points + * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending + * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. + * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) + * up to and including the ending HTML tag where **ng-repeat-end** is placed. + * + * The example below makes use of this feature: + * ```html + *
+ * Header {{ item }} + *
+ *
+ * Body {{ item }} + *
+ *
+ * Footer {{ item }} + *
+ * ``` + * + * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: + * ```html + *
+ * Header A + *
+ *
+ * Body A + *
+ *
+ * Footer A + *
+ *
+ * Header B + *
+ *
+ * Body B + *
+ *
+ * Footer B + *
+ * ``` + * + * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such + * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). + * + * @animations + * **.enter** - when a new item is added to the list or when an item is revealed after a filter + * + * **.leave** - when an item is removed from the list or when an item is filtered out + * + * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered + * + * @element ANY + * @scope + * @priority 1000 + * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These + * formats are currently supported: + * + * * `variable in expression` – where variable is the user defined loop variable and `expression` + * is a scope expression giving the collection to enumerate. + * + * For example: `album in artist.albums`. + * + * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, + * and `expression` is the scope expression giving the collection to enumerate. + * + * For example: `(name, age) in {'adam':10, 'amalie':12}`. + * + * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function + * which can be used to associate the objects in the collection with the DOM elements. If no tracking function + * is specified the ng-repeat associates elements by identity in the collection. It is an error to have + * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are + * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, + * before specifying a tracking expression. + * + * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements + * will be associated by item identity in the array. + * + * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique + * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements + * with the corresponding item in the array by identity. Moving the same object in array would move the DOM + * element in the same way in the DOM. + * + * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this + * case the object identity does not matter. Two objects are considered equivalent as long as their `id` + * property is same. + * + * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter + * to items in conjunction with a tracking expression. + * + * @example + * This example initializes the scope to a list of names and + * then uses `ngRepeat` to display every person: + + +
+ I have {{friends.length}} friends. They are: + +
    +
  • + [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. +
  • +
+
+
+ + .example-animate-container { + background:white; + border:1px solid black; + list-style:none; + margin:0; + padding:0 10px; + } + + .animate-repeat { + line-height:40px; + list-style:none; + box-sizing:border-box; + } + + .animate-repeat.ng-move, + .animate-repeat.ng-enter, + .animate-repeat.ng-leave { + -webkit-transition:all linear 0.5s; + transition:all linear 0.5s; + } + + .animate-repeat.ng-leave.ng-leave-active, + .animate-repeat.ng-move, + .animate-repeat.ng-enter { + opacity:0; + max-height:0; + } + + .animate-repeat.ng-leave, + .animate-repeat.ng-move.ng-move-active, + .animate-repeat.ng-enter.ng-enter-active { + opacity:1; + max-height:40px; + } + + + var friends = element.all(by.repeater('friend in friends')); + + it('should render initial data set', function() { + expect(friends.count()).toBe(10); + expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); + expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); + expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.'); + expect(element(by.binding('friends.length')).getText()) + .toMatch("I have 10 friends. They are:"); + }); + + it('should update repeater when filter predicate changes', function() { + expect(friends.count()).toBe(10); + + element(by.model('q')).sendKeys('ma'); + + expect(friends.count()).toBe(2); + expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); + expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); + }); + +
+ */ +var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { + var NG_REMOVED = '$$NG_REMOVED'; + var ngRepeatMinErr = minErr('ngRepeat'); + return { + transclude: 'element', + priority: 1000, + terminal: true, + $$tlb: true, + link: function($scope, $element, $attr, ctrl, $transclude){ + var expression = $attr.ngRepeat; + var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/), + trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn, + lhs, rhs, valueIdentifier, keyIdentifier, + hashFnLocals = {$id: hashKey}; + + if (!match) { + throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", + expression); + } + + lhs = match[1]; + rhs = match[2]; + trackByExp = match[3]; + + if (trackByExp) { + trackByExpGetter = $parse(trackByExp); + trackByIdExpFn = function(key, value, index) { + // assign key, value, and $index to the locals so that they can be used in hash functions + if (keyIdentifier) hashFnLocals[keyIdentifier] = key; + hashFnLocals[valueIdentifier] = value; + hashFnLocals.$index = index; + return trackByExpGetter($scope, hashFnLocals); + }; + } else { + trackByIdArrayFn = function(key, value) { + return hashKey(value); + }; + trackByIdObjFn = function(key) { + return key; + }; + } + + match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); + if (!match) { + throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", + lhs); + } + valueIdentifier = match[3] || match[1]; + keyIdentifier = match[2]; + + // Store a list of elements from previous run. This is a hash where key is the item from the + // iterator, and the value is objects with following properties. + // - scope: bound scope + // - element: previous element. + // - index: position + var lastBlockMap = {}; + + //watch props + $scope.$watchCollection(rhs, function ngRepeatAction(collection){ + var index, length, + previousNode = $element[0], // current position of the node + nextNode, + // Same as lastBlockMap but it has the current state. It will become the + // lastBlockMap on the next iteration. + nextBlockMap = {}, + arrayLength, + childScope, + key, value, // key/value of iteration + trackById, + trackByIdFn, + collectionKeys, + block, // last object information {scope, element, id} + nextBlockOrder = [], + elementsToRemove; + + + if (isArrayLike(collection)) { + collectionKeys = collection; + trackByIdFn = trackByIdExpFn || trackByIdArrayFn; + } else { + trackByIdFn = trackByIdExpFn || trackByIdObjFn; + // if object, extract keys, sort them and use to determine order of iteration over obj props + collectionKeys = []; + for (key in collection) { + if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { + collectionKeys.push(key); + } + } + collectionKeys.sort(); + } + + arrayLength = collectionKeys.length; + + // locate existing items + length = nextBlockOrder.length = collectionKeys.length; + for(index = 0; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + trackById = trackByIdFn(key, value, index); + assertNotHasOwnProperty(trackById, '`track by` id'); + if(lastBlockMap.hasOwnProperty(trackById)) { + block = lastBlockMap[trackById]; + delete lastBlockMap[trackById]; + nextBlockMap[trackById] = block; + nextBlockOrder[index] = block; + } else if (nextBlockMap.hasOwnProperty(trackById)) { + // restore lastBlockMap + forEach(nextBlockOrder, function(block) { + if (block && block.scope) lastBlockMap[block.id] = block; + }); + // This is a duplicate and we need to throw an error + throw ngRepeatMinErr('dupes', + "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}", + expression, trackById, toJson(value)); + } else { + // new never before seen block + nextBlockOrder[index] = { id: trackById }; + nextBlockMap[trackById] = false; + } + } + + // remove existing items + for (key in lastBlockMap) { + // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn + if (lastBlockMap.hasOwnProperty(key)) { + block = lastBlockMap[key]; + elementsToRemove = getBlockElements(block.clone); + $animate.leave(elementsToRemove); + forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; }); + block.scope.$destroy(); + } + } + + // we are not using forEach for perf reasons (trying to avoid #call) + for (index = 0, length = collectionKeys.length; index < length; index++) { + key = (collection === collectionKeys) ? index : collectionKeys[index]; + value = collection[key]; + block = nextBlockOrder[index]; + if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]); + + if (block.scope) { + // if we have already seen this object, then we need to reuse the + // associated scope/element + childScope = block.scope; + + nextNode = previousNode; + do { + nextNode = nextNode.nextSibling; + } while(nextNode && nextNode[NG_REMOVED]); + + if (getBlockStart(block) != nextNode) { + // existing item which got moved + $animate.move(getBlockElements(block.clone), null, jqLite(previousNode)); + } + previousNode = getBlockEnd(block); + } else { + // new item which we don't know about + childScope = $scope.$new(); + } + + childScope[valueIdentifier] = value; + if (keyIdentifier) childScope[keyIdentifier] = key; + childScope.$index = index; + childScope.$first = (index === 0); + childScope.$last = (index === (arrayLength - 1)); + childScope.$middle = !(childScope.$first || childScope.$last); + // jshint bitwise: false + childScope.$odd = !(childScope.$even = (index&1) === 0); + // jshint bitwise: true + + if (!block.scope) { + $transclude(childScope, function(clone) { + clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' '); + $animate.enter(clone, null, jqLite(previousNode)); + previousNode = clone; + block.scope = childScope; + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block.clone = clone; + nextBlockMap[block.id] = block; + }); + } + } + lastBlockMap = nextBlockMap; + }); + } + }; + + function getBlockStart(block) { + return block.clone[0]; + } + + function getBlockEnd(block) { + return block.clone[block.clone.length - 1]; + } +}]; + +/** + * @ngdoc directive + * @name ngShow + * + * @description + * The `ngShow` directive shows or hides the given HTML element based on the expression + * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding + * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined + * in AngularJS and sets the display style to none (using an !important flag). + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```html + * + *
+ * + * + *
+ * ``` + * + * When the `ngShow` expression evaluates to false then the `.ng-hide` CSS class is added to the class attribute + * on the element causing it to become hidden. When true, the `.ng-hide` CSS class is removed + * from the element causing the element not to appear hidden. + * + *
+ * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):
+ * "f" / "0" / "false" / "no" / "n" / "[]" + *
+ * + * ## Why is !important used? + * + * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding `.ng-hide` + * + * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change + * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` + * class in CSS: + * + * ```css + * .ng-hide { + * //this is just another form of hiding an element + * display:block!important; + * position:absolute; + * top:-9999px; + * left:-9999px; + * } + * ``` + * + * By default you don't need to override in CSS anything and the animations will work around the display style. + * + * ## A note about animations with `ngShow` + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works like the animation system present with ngClass except that + * you must also include the !important flag to override the display property + * so that you can perform an animation when the element is hidden during the time of the animation. + * + * ```css + * // + * //a working example can be found at the bottom of this page + * // + * .my-element.ng-hide-add, .my-element.ng-hide-remove { + * transition:0.5s linear all; + * } + * + * .my-element.ng-hide-add { ... } + * .my-element.ng-hide-add.ng-hide-add-active { ... } + * .my-element.ng-hide-remove { ... } + * .my-element.ng-hide-remove.ng-hide-remove-active { ... } + * ``` + * + * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display + * property to block during animation states--ngAnimate will handle the style toggling automatically for you. + * + * @animations + * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible + * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden + * + * @element ANY + * @param {expression} ngShow If the {@link guide/expression expression} is truthy + * then the element is shown or hidden respectively. + * + * @example + + + Click me:
+
+ Show: +
+ I show up when your checkbox is checked. +
+
+
+ Hide: +
+ I hide when your checkbox is checked. +
+
+
+ + @import url(https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); + + + .animate-show { + -webkit-transition:all linear 0.5s; + transition:all linear 0.5s; + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .animate-show.ng-hide { + line-height:0; + opacity:0; + padding:0 10px; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + + var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); + var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); + + it('should check ng-show / ng-hide', function() { + expect(thumbsUp.isDisplayed()).toBeFalsy(); + expect(thumbsDown.isDisplayed()).toBeTruthy(); + + element(by.model('checked')).click(); + + expect(thumbsUp.isDisplayed()).toBeTruthy(); + expect(thumbsDown.isDisplayed()).toBeFalsy(); + }); + +
+ */ +var ngShowDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngShow, function ngShowWatchAction(value){ + $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide'); + }); + }; +}]; + + +/** + * @ngdoc directive + * @name ngHide + * + * @description + * The `ngHide` directive shows or hides the given HTML element based on the expression + * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding + * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined + * in AngularJS and sets the display style to none (using an !important flag). + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```html + * + *
+ * + * + *
+ * ``` + * + * When the `.ngHide` expression evaluates to true then the `.ng-hide` CSS class is added to the class attribute + * on the element causing it to become hidden. When false, the `.ng-hide` CSS class is removed + * from the element causing the element not to appear hidden. + * + *
+ * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):
+ * "f" / "0" / "false" / "no" / "n" / "[]" + *
+ * + * ## Why is !important used? + * + * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector + * can be easily overridden by heavier selectors. For example, something as simple + * as changing the display style on a HTML list item would make hidden elements appear visible. + * This also becomes a bigger issue when dealing with CSS frameworks. + * + * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector + * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the + * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * + * ### Overriding `.ng-hide` + * + * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change + * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` + * class in CSS: + * + * ```css + * .ng-hide { + * //this is just another form of hiding an element + * display:block!important; + * position:absolute; + * top:-9999px; + * left:-9999px; + * } + * ``` + * + * By default you don't need to override in CSS anything and the animations will work around the display style. + * + * ## A note about animations with `ngHide` + * + * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression + * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` + * CSS class is added and removed for you instead of your own CSS class. + * + * ```css + * // + * //a working example can be found at the bottom of this page + * // + * .my-element.ng-hide-add, .my-element.ng-hide-remove { + * transition:0.5s linear all; + * } + * + * .my-element.ng-hide-add { ... } + * .my-element.ng-hide-add.ng-hide-add-active { ... } + * .my-element.ng-hide-remove { ... } + * .my-element.ng-hide-remove.ng-hide-remove-active { ... } + * ``` + * + * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display + * property to block during animation states--ngAnimate will handle the style toggling automatically for you. + * + * @animations + * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden + * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible + * + * @element ANY + * @param {expression} ngHide If the {@link guide/expression expression} is truthy then + * the element is shown or hidden respectively. + * + * @example + + + Click me:
+
+ Show: +
+ I show up when your checkbox is checked. +
+
+
+ Hide: +
+ I hide when your checkbox is checked. +
+
+
+ + @import url(https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css); + + + .animate-hide { + -webkit-transition:all linear 0.5s; + transition:all linear 0.5s; + line-height:20px; + opacity:1; + padding:10px; + border:1px solid black; + background:white; + } + + .animate-hide.ng-hide { + line-height:0; + opacity:0; + padding:0 10px; + } + + .check-element { + padding:10px; + border:1px solid black; + background:white; + } + + + var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); + var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); + + it('should check ng-show / ng-hide', function() { + expect(thumbsUp.isDisplayed()).toBeFalsy(); + expect(thumbsDown.isDisplayed()).toBeTruthy(); + + element(by.model('checked')).click(); + + expect(thumbsUp.isDisplayed()).toBeTruthy(); + expect(thumbsDown.isDisplayed()).toBeFalsy(); + }); + +
+ */ +var ngHideDirective = ['$animate', function($animate) { + return function(scope, element, attr) { + scope.$watch(attr.ngHide, function ngHideWatchAction(value){ + $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide'); + }); + }; +}]; + +/** + * @ngdoc directive + * @name ngStyle + * @restrict AC + * + * @description + * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. + * + * @element ANY + * @param {expression} ngStyle + * + * {@link guide/expression Expression} which evals to an + * object whose keys are CSS style names and values are corresponding values for those CSS + * keys. + * + * Since some CSS style names are not valid keys for an object, they must be quoted. + * See the 'background-color' style in the example below. + * + * @example + + + + + +
+ Sample Text +
myStyle={{myStyle}}
+
+ + span { + color: black; + } + + + var colorSpan = element(by.css('span')); + + it('should check ng-style', function() { + expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); + element(by.css('input[value=\'set color\']')).click(); + expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); + element(by.css('input[value=clear]')).click(); + expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); + }); + +
+ */ +var ngStyleDirective = ngDirective(function(scope, element, attr) { + scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { + if (oldStyles && (newStyles !== oldStyles)) { + forEach(oldStyles, function(val, style) { element.css(style, '');}); + } + if (newStyles) element.css(newStyles); + }, true); +}); + +/** + * @ngdoc directive + * @name ngSwitch + * @restrict EA + * + * @description + * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. + * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location + * as specified in the template. + * + * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it + * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element + * matches the value obtained from the evaluated expression. In other words, you define a container element + * (where you place the directive), place an expression on the **`on="..."` attribute** + * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place + * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on + * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default + * attribute is displayed. + * + *
+ * Be aware that the attribute values to match against cannot be expressions. They are interpreted + * as literal string values to match against. + * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the + * value of the expression `$scope.someVal`. + *
+ + * @animations + * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container + * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM + * + * @usage + * + * ``` + * + * ... + * ... + * ... + * + * ``` + * + * + * @scope + * @priority 800 + * @param {*} ngSwitch|on expression to match against ng-switch-when. + * On child elements add: + * + * * `ngSwitchWhen`: the case statement to match against. If match then this + * case will be displayed. If the same match appears multiple times, all the + * elements will be displayed. + * * `ngSwitchDefault`: the default case when no other case match. If there + * are multiple default cases, all of them will be displayed when no other + * case match. + * + * + * @example + + +
+ + selection={{selection}} +
+
+
Settings Div
+
Home Span
+
default
+
+
+
+ + angular.module('switchExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.items = ['settings', 'home', 'other']; + $scope.selection = $scope.items[0]; + }]); + + + .animate-switch-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .animate-switch { + padding:10px; + } + + .animate-switch.ng-animate { + -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + } + + .animate-switch.ng-leave.ng-leave-active, + .animate-switch.ng-enter { + top:-50px; + } + .animate-switch.ng-leave, + .animate-switch.ng-enter.ng-enter-active { + top:0; + } + + + var switchElem = element(by.css('[ng-switch]')); + var select = element(by.model('selection')); + + it('should start in settings', function() { + expect(switchElem.getText()).toMatch(/Settings Div/); + }); + it('should change to home', function() { + select.all(by.css('option')).get(1).click(); + expect(switchElem.getText()).toMatch(/Home Span/); + }); + it('should select default', function() { + select.all(by.css('option')).get(2).click(); + expect(switchElem.getText()).toMatch(/default/); + }); + +
+ */ +var ngSwitchDirective = ['$animate', function($animate) { + return { + restrict: 'EA', + require: 'ngSwitch', + + // asks for $scope to fool the BC controller module + controller: ['$scope', function ngSwitchController() { + this.cases = {}; + }], + link: function(scope, element, attr, ngSwitchController) { + var watchExpr = attr.ngSwitch || attr.on, + selectedTranscludes = [], + selectedElements = [], + previousElements = [], + selectedScopes = []; + + scope.$watch(watchExpr, function ngSwitchWatchAction(value) { + var i, ii; + for (i = 0, ii = previousElements.length; i < ii; ++i) { + previousElements[i].remove(); + } + previousElements.length = 0; + + for (i = 0, ii = selectedScopes.length; i < ii; ++i) { + var selected = selectedElements[i]; + selectedScopes[i].$destroy(); + previousElements[i] = selected; + $animate.leave(selected, function() { + previousElements.splice(i, 1); + }); + } + + selectedElements.length = 0; + selectedScopes.length = 0; + + if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { + scope.$eval(attr.change); + forEach(selectedTranscludes, function(selectedTransclude) { + var selectedScope = scope.$new(); + selectedScopes.push(selectedScope); + selectedTransclude.transclude(selectedScope, function(caseElement) { + var anchor = selectedTransclude.element; + + selectedElements.push(caseElement); + $animate.enter(caseElement, anchor.parent(), anchor); + }); + }); + } + }); + } + }; +}]; + +var ngSwitchWhenDirective = ngDirective({ + transclude: 'element', + priority: 800, + require: '^ngSwitch', + link: function(scope, element, attrs, ctrl, $transclude) { + ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); + ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); + } +}); + +var ngSwitchDefaultDirective = ngDirective({ + transclude: 'element', + priority: 800, + require: '^ngSwitch', + link: function(scope, element, attr, ctrl, $transclude) { + ctrl.cases['?'] = (ctrl.cases['?'] || []); + ctrl.cases['?'].push({ transclude: $transclude, element: element }); + } +}); + +/** + * @ngdoc directive + * @name ngTransclude + * @restrict AC + * + * @description + * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. + * + * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. + * + * @element ANY + * + * @example + + + +
+
+
+ {{text}} +
+
+ + it('should have transcluded', function() { + var titleElement = element(by.model('title')); + titleElement.clear(); + titleElement.sendKeys('TITLE'); + var textElement = element(by.model('text')); + textElement.clear(); + textElement.sendKeys('TEXT'); + expect(element(by.binding('title')).getText()).toEqual('TITLE'); + expect(element(by.binding('text')).getText()).toEqual('TEXT'); + }); + +
+ * + */ +var ngTranscludeDirective = ngDirective({ + link: function($scope, $element, $attrs, controller, $transclude) { + if (!$transclude) { + throw minErr('ngTransclude')('orphan', + 'Illegal use of ngTransclude directive in the template! ' + + 'No parent directive that requires a transclusion found. ' + + 'Element: {0}', + startingTag($element)); + } + + $transclude(function(clone) { + $element.empty(); + $element.append(clone); + }); + } +}); + +/** + * @ngdoc directive + * @name script + * @restrict E + * + * @description + * Load the content of a ` + + Load inlined template +
+ + + it('should load template defined inside script tag', function() { + element(by.css('#tpl-link')).click(); + expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); + }); + + + */ +var scriptDirective = ['$templateCache', function($templateCache) { + return { + restrict: 'E', + terminal: true, + compile: function(element, attr) { + if (attr.type == 'text/ng-template') { + var templateUrl = attr.id, + text = element[0].text; + + $templateCache.put(templateUrl, text); + } + } + }; +}]; + +var ngOptionsMinErr = minErr('ngOptions'); +/** + * @ngdoc directive + * @name select + * @restrict E + * + * @description + * HTML `SELECT` element with angular data-binding. + * + * # `ngOptions` + * + * The `ngOptions` attribute can be used to dynamically generate a list of `` + * DOM element. + * * `trackexpr`: Used when working with an array of objects. The result of this expression will be + * used to identify the objects in the array. The `trackexpr` will most likely refer to the + * `value` variable (e.g. `value.propertyName`). + * + * @example + + + +
+
    +
  • + Name: + [X] +
  • +
  • + [add] +
  • +
+
+ Color (null not allowed): +
+ + Color (null allowed): + + +
+ + Color grouped by shade: +
+ + + Select bogus.
+
+ Currently selected: {{ {selected_color:myColor} }} +
+
+
+
+ + it('should check ng-options', function() { + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); + element.all(by.model('myColor')).first().click(); + element.all(by.css('select[ng-model="myColor"] option')).first().click(); + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); + element(by.css('.nullable select[ng-model="myColor"]')).click(); + element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); + expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); + }); + +
+ */ + +var ngOptionsDirective = valueFn({ terminal: true }); +// jshint maxlen: false +var selectDirective = ['$compile', '$parse', function($compile, $parse) { + //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888 + var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, + nullModelCtrl = {$setViewValue: noop}; +// jshint maxlen: 100 + + return { + restrict: 'E', + require: ['select', '?ngModel'], + controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { + var self = this, + optionsMap = {}, + ngModelCtrl = nullModelCtrl, + nullOption, + unknownOption; + + + self.databound = $attrs.ngModel; + + + self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { + ngModelCtrl = ngModelCtrl_; + nullOption = nullOption_; + unknownOption = unknownOption_; + }; + + + self.addOption = function(value) { + assertNotHasOwnProperty(value, '"option value"'); + optionsMap[value] = true; + + if (ngModelCtrl.$viewValue == value) { + $element.val(value); + if (unknownOption.parent()) unknownOption.remove(); + } + }; + + + self.removeOption = function(value) { + if (this.hasOption(value)) { + delete optionsMap[value]; + if (ngModelCtrl.$viewValue == value) { + this.renderUnknownOption(value); + } + } + }; + + + self.renderUnknownOption = function(val) { + var unknownVal = '? ' + hashKey(val) + ' ?'; + unknownOption.val(unknownVal); + $element.prepend(unknownOption); + $element.val(unknownVal); + unknownOption.prop('selected', true); // needed for IE + }; + + + self.hasOption = function(value) { + return optionsMap.hasOwnProperty(value); + }; + + $scope.$on('$destroy', function() { + // disable unknown option so that we don't do work when the whole select is being destroyed + self.renderUnknownOption = noop; + }); + }], + + link: function(scope, element, attr, ctrls) { + // if ngModel is not defined, we don't need to do anything + if (!ctrls[1]) return; + + var selectCtrl = ctrls[0], + ngModelCtrl = ctrls[1], + multiple = attr.multiple, + optionsExp = attr.ngOptions, + nullOption = false, // if false, user will not be able to select it (used by ngOptions) + emptyOption, + // we can't just jqLite('