diff --git a/.gitignore b/.gitignore index 7a300c0af..2ea470b9e 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ _infrastructure/tests/build node_modules .sublimets +.settings/launch.json diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6abf7201b..a41d225ec 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -16,7 +16,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](angular-growl-v2/angular-growl-v2.d.ts) [Angular Growl 2 v.0.7.3](http://janstevens.github.io/angular-growl-2) by [Tadeusz Hucal](https://github.com/mkp05) * [:link:](angularjs/angular.d.ts) [Angular JS](http://angularjs.org) by [Diego Vilar](http://github.com/diegovilar) * [:link:](angularjs/angular-animate.d.ts) [Angular JS (ngAnimate module)](http://angularjs.org) by [Michel Salib](https://github.com/michelsalib), [Adi Dahiya](https://github.com/adidahiya), [Raphael Schweizer](https://github.com/rasch) -* [:link:](angularjs/angular-cookies.d.ts) [Angular JS (ngCookies module)](http://angularjs.org) by [Diego Vilar](http://github.com/diegovilar) +* [:link:](angularjs/angular-cookies.d.ts) [Angular JS (ngCookies module)](http://angularjs.org) by [Diego Vilar](http://github.com/diegovilar), [Anthony Ciccarello](http://github.com/aciccarello) * [:link:](angularjs/angular-mocks.d.ts) [Angular JS (ngMock, ngMockE2E module)](http://angularjs.org) by [Diego Vilar](http://github.com/diegovilar) * [:link:](angularjs/angular-resource.d.ts) [Angular JS (ngResource module)](http://angularjs.org) by [Diego Vilar](http://github.com/diegovilar), [Michael Jess](http://github.com/miffels) * [:link:](angularjs/angular-route.d.ts) [Angular JS (ngRoute module)](http://angularjs.org) by [Jonathan Park](https://github.com/park9140) @@ -40,6 +40,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](angularfire/angularfire.d.ts) [AngularFire](http://angularfire.com) by [Dénes Harmath](http://github.com/thSoft) * [:link:](angularLocalStorage/angularLocalStorage.d.ts) [AngularLocalStorage](https://github.com/agrublev/angularLocalStorage) by [Horiuchi_H](https://github.com/horiuchi) * [:link:](animation-frame/animation-frame.d.ts) [animation-frame](https://github.com/kof/animation-frame) by [Qinfeng Chen](https://github.com/qinfchen) +* [:link:](ansi-styles/ansi-styles.d.ts) [ansi-styles](https://github.com/sindresorhus/ansi-styles) by [bryn austin bellomy](https://github.com/brynbellomy) * [:link:](ansicolors/ansicolors.d.ts) [ansicolors](https://github.com/thlorenz/ansicolors) by [rogierschouten](https://github.com/rogierschouten) * [:link:](any-db/any-db.d.ts) [any-db](https://github.com/grncdr/node-any-db) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](any-db-transaction/any-db-transaction.d.ts) [any-db-transaction](https://github.com/grncdr/node-any-db-transaction) by [Rogier Schouten](https://github.com/rogierschouten) @@ -109,7 +110,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](camljs/camljs.d.ts) [camljs](http://camljs.codeplex.com) by [Andrey Markeev](http://markeev.com) * [:link:](canvasjs/canvasjs.d.ts) [CanvasJS](http://canvasjs.com) by [Mark Overholt](https://github.com/mover5) * [:link:](casperjs/casperjs.d.ts) [CasperJS](http://casperjs.org) by [Jed Mao](https://github.com/jedmao) -* [:link:](chai/chai.d.ts) [chai](http://chaijs.com) by [Jed Hunsaker](https://github.com/jedhunsaker), [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](chai/chai.d.ts) [chai](http://chaijs.com) by [Jed Mao](https://github.com/jedmao), [Bart van der Schoor](https://github.com/Bartvds) * [:link:](chai-as-promised/chai-as-promised.d.ts) [chai-as-promised](https://github.com/domenic/chai-as-promised) by [jt000](https://github.com/jt000) * [:link:](chai-datetime/chai-datetime.d.ts) [chai-datetime](https://github.com/gaslight/chai-datetime.git) by [Cliff Burger](https://github.com/cliffburger) * [:link:](chai-fuzzy/chai-fuzzy.d.ts) [chai-fuzzy](http://chaijs.com/plugins/chai-fuzzy) by [Bart van der Schoor](https://github.com/Bartvds) @@ -131,6 +132,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](cli-color/cli-color.d.ts) [cli-color](https://github.com/medikoo/cli-color) by [Joel Spadin](https://github.com/ChaosinaCan) * [:link:](clone/clone.d.ts) [clone](https://github.com/pvorb/node-clone) by [Kieran Simpson](https://github.com/kierans/DefinitelyTyped) * [:link:](codemirror/codemirror.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [mihailik](https://github.com/mihailik) +* [:link:](colorbrewer/colorbrewer.d.ts) [colorbrewer](https://github.com/jeanlauliac/colorbrewer) by [Matt Traynham](https://github.com/mtraynham) * [:link:](colors/colors.d.ts) [Colors.js 0.6.0-1](https://github.com/Marak/colors.js) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](cometd/cometd.d.ts) [CometD](http://cometd.org) by [Derek Cicerone](https://github.com/derekcicerone) * [:link:](commander/commander.d.ts) [commanderjs](https://github.com/visionmedia/commander.js) by [Marcelo Dezem](http://github.com/mdezem), [vvakame](http://github.com/vvakame) @@ -174,6 +176,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](deployJava/deployJava.d.ts) [deployJava.js](https://www.java.com/js/deployJava.txt) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](detect-indent/detect-indent.d.ts) [detect-indent](https://github.com/sindresorhus/detect-indent) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](devextreme/dx.devextreme.d.ts) [DevExtreme](http://js.devexpress.com) by [DevExpress Inc.](http://devexpress.com) +* [:link:](dexie/dexie.d.ts) [Dexie](https://github.com/dfahlander/Dexie.js) by [David Fahlander](http://github.com/dfahlander) * [:link:](dhtmlxgantt/dhtmlxgantt.d.ts) [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) by [Maksim Kozhukh](http://github.com/mkozhukh) * [:link:](dhtmlxscheduler/dhtmlxscheduler.d.ts) [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) by [Maksim Kozhukh](http://github.com/mkozhukh) * [:link:](di-lite/di-lite.d.ts) [di-lite](https://github.com/NickQiZhu/di.js) by [Timothy Morris](https://github.com/dcrusader) @@ -199,6 +202,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](easy-session/easy-session.d.ts) [easy-session](https://github.com/DeadAlready/node-easy-session) by [Karl Düüna](https://github.com/DeadAlready) * [:link:](easy-table/easy-table.d.ts) [easy-table](https://github.com/eldargab/easy-table) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](easystarjs/easystarjs.d.ts) [EasyStar.js](http://easystarjs.com) by [Magnus Gustafsson](https://github.com/borundin) +* [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](element-resize-event/element-resize-event.d.ts) [element-resize-event](https://github.com/KyleAMathews/element-resize-event) by [Rogier Schouten](https://github.com/rogierschouten) @@ -229,6 +233,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](express-validator/express-validator.d.ts) [express-validator](https://github.com/ctavan/express-validator) by [Nathan Ridley](https://github.com/axefrog), [Jonathan Häberle](http://dreampulse.de) * [:link:](extend/extend.d.ts) [extend](https://www.npmjs.com/package/extend) by [Stefan Steinhart](https://github.com/reppners) * [:link:](extjs/ExtJS.d.ts) [ExtJS](http://www.sencha.com/products/extjs) by [Brian Kotek](https://github.com/brian428) +* [:link:](eyes/eyes.d.ts) [eyes](https://github.com/cloudhead/eyes.js) by [bryn austin bellomy](https://github.com/brynbellomy) * [:link:](fabricjs/fabricjs.d.ts) [FabricJS](http://fabricjs.com) by [Oliver Klemencic](https://github.com/oklemencic) * [:link:](fbsdk/fbsdk.d.ts) [Facebook Javascript SDK](https://developers.facebook.com/docs/javascript) by [Joshua Strobl](https://github.com/JoshStrobl) * [:link:](fancybox/fancybox.d.ts) [fancyBox](https://github.com/fancyapps/fancyBox) by [Boris Yankov](https://github.com/borisyankov) @@ -271,6 +276,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](gently/gently.d.ts) [gently](https://www.npmjs.org/package/gently) by [bonnici](https://github.com/bonnici) * [:link:](geojson/geojson.d.ts) [GeoJSON Format Specification](http://geojson.org) by [Jacob Bruun](https://github.com/cobster) * [:link:](giraffe/giraffe.d.ts) [Giraffe](https://github.com/barc/backbone.giraffe) by [Matt McCray](https://github.com/darthapo) +* [:link:](gl-matrix/gl-matrix.d.ts) [gl-matrix](https://github.com/toji/gl-matrix) by [Tat](https://github.com/tatchx) * [:link:](gldatepicker/gldatepicker.d.ts) [glDatePicker](http://glad.github.com/glDatePicker) by [Dániel Tar](https://github.com/qcz) * [:link:](glidejs/glidejs.d.ts) [Glide.js](http://glide.jedrzejchalubek.com) by [Milan Jaros](https://github.com/milanjaros) * [:link:](glob/glob.d.ts) [Glob](https://github.com/isaacs/node-glob) by [vvakame](https://github.com/vvakame) @@ -342,6 +348,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](humane/humane.d.ts) [Humane](http://wavded.github.com/humane-js) by [jmvrbanac](https://github.com/jmvrbanac) * [:link:](hypertext-application-language/hypertext-application-language.d.ts) [Hypertext Application Language Draft 6](https://tools.ietf.org/html/draft-kelly-json-hal-06) by [Maks3w](https://github.com/maks3w) * [:link:](i18n-node/i18n-node.d.ts) [i18n-node](https://github.com/mashpie/i18n-node) by [Maxime LUCE](https://github.com/SomaticIT) +* [:link:](ng-i18next/ng-i18next.d.ts) [i18next](https://github.com/i18next/ng-i18next) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](i18next/i18next.d.ts) [i18next](http://i18next.com) by [Maarten Docter](https://github.com/mdocter) * [:link:](iban/iban.d.ts) [iban.js](https://github.com/arhs/iban.js) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](icheck/icheck.d.ts) [iCheck](http://damirfoy.com/iCheck) by [Dániel Tar](https://github.com/qcz) @@ -476,6 +483,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jssha/jssha.d.ts) [jsSHA](https://github.com/Caligatio/jsSHA) by [David Li](https://github.com/randombk) * [:link:](jstorage/jstorage.d.ts) [jStorage](http://www.jstorage.info) by [Danil Flores](https://github.com/dflor003) * [:link:](jstree/jstree.d.ts) [jsTree](http://www.jstree.com) by [Adam Pluciński](https://github.com/adaskothebeast) +* [:link:](jsuri/jsuri.d.ts) [jsUri](https://github.com/derek-watson/jsUri) by [Chris Charabaruk](http://github.com/coldacid) * [:link:](jszip/jszip.d.ts) [JSZip](http://stuk.github.com/jszip) by [mzeiher](https://github.com/mzeiher) * [:link:](jwplayer/jwplayer.d.ts) [JW Player](http://developer.longtailvideo.com/trac) by [Martin Duparc](https://github.com/martinduparc) * [:link:](jwt-simple/jwt-simple.d.ts) [jwt-simple](https://github.com/hokaccha/node-jwt-simple) by [Ken Fukuyama](https://github.com/kenfdev) @@ -500,6 +508,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](knockout-transformations/knockout-transformations.d.ts) [knockout-transformations](https://github.com/One-com/knockout-transformations) by [John Reilly](https://github.com/johnnyreilly), [Wim Looman](https://github.com/Nemo157) * [:link:](knockout.mapper/knockout.mapper.d.ts) [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) by [Brandon Meyer](https://github.com/BMeyerKC) * [:link:](knockout.mapping/knockout.mapping.d.ts) [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](knockout.punches/knockout.punches.d.ts) [knockout.punches](https://github.com/mbest/knockout.punches) by [Stephen Lautier](https://github.com/johnnyreilly) * [:link:](knockout.rx/knockout.rx.d.ts) [knockout.rx](https://github.com/Igorbek/knockout.rx) by [Igor Oleinikov](https://github.com/Igorbek) * [:link:](knockstrap/knockstrap.d.ts) [Knockstrap](http://faulknercs.github.io/Knockstrap) by [Adam Pluciński](https://github.com/adaskothebeast) * [:link:](knockout.kogrid/ko-grid.d.ts) [ko-grid](http://knockout-contrib.github.io/KoGrid) by [huer12](https://github.com/huer12) @@ -545,6 +554,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](marked/marked.d.ts) [Marked](https://github.com/chjj/marked) by [William Orr](https://github.com/worr) * [:link:](maskedinput/maskedinput.d.ts) [Masked Input plugin for jQuery](http://digitalbush.com/projects/masked-input-plugin) by [Lokesh Peta](https://github.com/lokeshpeta) * [:link:](mathjax/mathjax.d.ts) [MathJax](https://github.com/mathjax/MathJax) by [Roland Zwaga](https://github.com/rolandzwaga) +* [:link:](matter-js/matter-js.d.ts) [Matter.js](https://github.com/liabru/matter-js) by [Ivane Gegia](https://twitter.com/ivanegegia) * [:link:](mCustomScrollbar/mCustomScrollbar.d.ts) [mCustomScrollbar](https://github.com/malihu/malihu-custom-scrollbar-plugin) by [Sarah Williams](https://github.com/flurg) * [:link:](memory-cache/memory-cache.d.ts) [memory-cache](http://github.com/ptarjan/node-cache) by [Jeff Goddard](https://github.com/jedigo) * [:link:](merge-stream/merge-stream.d.ts) [merge-stream](https://github.com/grncdr/merge-stream) by [Keita Kagurazaka](https://github.com/k-kagurazaka) @@ -716,6 +726,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](q-io/Q-io.d.ts) [Q-io](https://github.com/kriskowal/q-io) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](q-retry/q-retry.d.ts) [q-retry](https://github.com/vilic/q-retry) by [VILIC VANE](https://github.com/vilic) * [:link:](qajax/qajax.d.ts) [Qajax](https://github.com/gre/qajax) by [Boltmade](https://github.com/Boltmade) +* [:link:](qtip2/qtip2.d.ts) [qtip2](http://qtip2.com) by [Nathan Pitman](https://github.com/Seltzer) * [:link:](qunit/qunit.d.ts) [QUnit](http://qunitjs.com) by [Diullei Gomes](https://github.com/diullei) * [:link:](rabbit.js/rabbit.js.d.ts) [rabbit.js](https://github.com/squaremo/rabbit.js) by [Wonshik Kim](https://github.com/wokim) * [:link:](ractive/ractive.d.ts) [Ractive](http://ractivejs.org) by [Han Lin Yap](http://yap.nu) @@ -728,6 +739,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](react/react-addons.d.ts) [ReactWithAddons (external module)](http://facebook.github.io/react) by [Asana](https://asana.com), [AssureSign](http://www.assuresign.com) * [:link:](react/react-addons-global.d.ts) [ReactWithAddons (internal module)](http://facebook.github.io/react) by [Asana](https://asana.com), [AssureSign](http://www.assuresign.com) * [:link:](readdir-stream/readdir-stream.d.ts) [readdir-stream](https://github.com/logicalparadox/readdir-stream) by [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](recursive-readdir/recursive-readdir.d.ts) [recursive-readdir](https://github.com/jergason/recursive-readdir) by [Elisée Maurer](https://github.com/elisee) * [:link:](redis/redis.d.ts) [redis](https://github.com/mranney/node_redis) by [Carlos Ballesteros Velasco](https://github.com/soywiz), [Peter Harris](https://github.com/CodeAnimal) * [:link:](ref/ref.d.ts) [ref](https://github.com/TooTallNate/ref) by [Paul Loyd](https://github.com/loyd) * [:link:](ref-array/ref-array.d.ts) [ref-array](https://github.com/TooTallNate/ref-array) by [Paul Loyd](https://github.com/loyd) @@ -788,7 +800,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](simple-cw-node/simple-cw-node.d.ts) [simple-cw-node](https://github.com/astronaughts/simple-cw-node) by [vvakame](https://github.com/vvakame) * [:link:](jquery.simplemodal/jquery.simplemodal.d.ts) [SimpleModal](http://www.ericmmartin.com/projects/simplemodal) by [Friedrich von Never](https://github.com/ForNeVeR) * [:link:](sinon/sinon.d.ts) [Sinon](http://sinonjs.org) by [William Sears](https://github.com/mrbigdog2u) -* [:link:](sinon-chai/sinon-chai.d.ts) [sinon-chai](https://github.com/domenic/sinon-chai) by [Kazi Manzur Rashid](https://github.com/kazimanzurrashid) +* [:link:](sinon-chai/sinon-chai.d.ts) [sinon-chai](https://github.com/domenic/sinon-chai) by [Kazi Manzur Rashid](https://github.com/kazimanzurrashid), [Jed Mao](https://github.com/jedmao) * [:link:](sipml/sipml.d.ts) [SIPml5](http://sipml5.org) by [A. Groenenboom](https://github.com/chookies) * [:link:](sjcl/sjcl.d.ts) [sjcl](http://crypto.stanford.edu/sjcl) by [Eugene Chernyshov](https://github.com/Evgenus) * [:link:](slickgrid/SlickGrid.d.ts) [SlickGrid](https://github.com/mleibman/SlickGrid) by [Josh Baldwin](https://github.com/jbaldwin) @@ -879,6 +891,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](twig/twig.d.ts) [twig](https://github.com/justjohn/twig.js) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](twitter/twitter.d.ts) [Twitter for Websites](https://dev.twitter.com/web) by [Chitoku](https://github.com/chitoku-k) * [:link:](jquery.bootstrap.wizard/jquery.bootstrap.wizard.d.ts) [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) by [Blake Niemyjski](https://github.com/niemyjski) +* [:link:](twix/twix.d.ts) [twix.js](https://github.com/icambron/twix.js) by [j3ko](https://github.com/j3ko) * [:link:](type-detect/type-detect.d.ts) [type-detect](https://github.com/chaijs/type-detect) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](type-name/type-name.d.ts) [type-name](https://github.com/twada/type-name) by [OKUNOKENTARO](https://github.com/armorik83) * [:link:](typeahead/typeahead.d.ts) [typeahead.js](http://twitter.github.io/typeahead.js) by [Ivaylo Gochkov](https://github.com/igochkov), [Gidon Junge](https://github.com/gjunge) @@ -902,6 +915,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](vega/vega.d.ts) [Vega](http://trifacta.github.io/vega) by [Tom Crockett](http://github.com/pelotom) * [:link:](velocity-animate/velocity-animate.d.ts) [Velocity](http://velocityjs.org) by [Greg Smith](https://github.com/smrq) * [:link:](vex-js/vex-js.d.ts) [Vex](https://github.com/HubSpot/vex) by [Greg Cohan](https://github.com/gdcohan) +* [:link:](victor/victor.d.ts) [Victor.js](http://victorjs.org) by [Ivane Gegia](https://twitter.com/ivanegegia) * [:link:](videojs/videojs.d.ts) [Video.js](https://github.com/zencoder/video-js) by [Vincent Bortone](https://github.com/vbortone) * [:link:](vimeo/froogaloop.d.ts) [Vimeo](http://developer.vimeo.com/player/js-api) by [Daz Wilkin](https://github.com/DazWilkin) * [:link:](vinyl/vinyl.d.ts) [vinyl](https://github.com/wearefractal/vinyl) by [vvakame](https://github.com/vvakame), [jedmao](https://github.com/jedmao) diff --git a/DataStream.js/DataStream.js-tests.ts b/DataStream.js/DataStream.js-tests.ts new file mode 100644 index 000000000..71bb08537 --- /dev/null +++ b/DataStream.js/DataStream.js-tests.ts @@ -0,0 +1,180 @@ +/// + +var buf = new ArrayBuffer(100); +var ds = new DataStream(buf); +ds = new DataStream(buf, 10); +ds = new DataStream(buf, 10, DataStream.BIG_ENDIAN); + +ds.save('somefile.ext'); +ds.dynamicSize = true; + +for (var i=0; i +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class DataStream { + + /** + Big-endian const to use as default endianness. + */ + static BIG_ENDIAN: boolean; + + /** + Little-endian const to use as default endianness. + */ + static LITTLE_ENDIAN: boolean; + + /** + DataStream reads scalars, arrays and structs of data from an ArrayBuffer. + It's like a file-like DataView on steroids. + + @param {ArrayBuffer} arrayBuffer ArrayBuffer to read from. + */ + constructor(arrayBuffer: ArrayBuffer); + + /** + DataStream reads scalars, arrays and structs of data from an ArrayBuffer. + It's like a file-like DataView on steroids. + + @param arrayBuffer ArrayBuffer to read from. + @param byteOffset Offset from arrayBuffer beginning for the DataStream. + */ + constructor(arrayBuffer: ArrayBuffer, byteOffset: number); + + /** + DataStream reads scalars, arrays and structs of data from an ArrayBuffer. + It's like a file-like DataView on steroids. + + @param arrayBuffer ArrayBuffer to read from. + @param byteOffset Offset from arrayBuffer beginning for the DataStream. + @param endianness DataStream.BIG_ENDIAN or DataStream.LITTLE_ENDIAN (the default). + */ + constructor(arrayBuffer: ArrayBuffer, byteOffset: number, endianness: boolean); + + /** + Saves the DataStream contents to the given filename. + Uses Chrome's anchor download property to initiate download. + * + @param filename Filename to save as. + @return nothing + */ + save(filename: string): void; + + /** + Whether to extend DataStream buffer when trying to write beyond its size. + If set, the buffer is reallocated to twice its current size until the + requested write fits the buffer. + */ + dynamicSize: boolean; + + /** + Returns the byte length of the DataStream object. + */ + byteLength: number; + + /** + Set/get the backing ArrayBuffer of the DataStream object. + The setter updates the DataView to point to the new buffer. + */ + buffer: ArrayBuffer; + + /** + Set/get the byteOffset of the DataStream object. + The setter updates the DataView to point to the new byteOffset. + */ + byteOffset: number; + + /** + Set/get the backing DataView of the DataStream object. + The setter updates the buffer and byteOffset to point to the DataView values. + */ + dataView: Object; + + /** + Sets the DataStream read/write position to given position. + Clamps between 0 and DataStream length. + * + @param pos Position to seek to. + @return nothing + */ + seek(pos: number): void; + + /** + Returns true if the DataStream seek pointer is at the end of buffer and + there's no more data to read. + * + @return true if the seek pointer is at the end of the buffer. + */ + isEof(): boolean; + + /** + Maps an Int32Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @return Int32Array to the DataStream backing buffer. + */ + mapInt32Array(length: number): Int32Array; + + /** + Maps an Int32Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return Int32Array to the DataStream backing buffer. + */ + mapInt32Array(length: number, e: boolean): Int32Array; + + /** + Maps an Int16Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @return Int16Array to the DataStream backing buffer. + */ + mapInt16Array(length: number): Int16Array; + + /** + Maps an Int16Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return Int16Array to the DataStream backing buffer. + */ + mapInt16Array(length: number, e: boolean): Int16Array; + + /** + Maps an Int8Array into the DataStream buffer. + * + Nice for quickly reading in data. + * + @param length Number of elements to map. + @return Int8Array to the DataStream backing buffer. + */ + mapInt8Array(length: number): Int8Array; + + /** + Maps a Uint32Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @return Uint32Array to the DataStream backing buffer. + */ + mapUint32Array(length: number): Uint32Array; + + /** + Maps a Uint32Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return Uint32Array to the DataStream backing buffer. + */ + mapUint32Array(length: number, e: boolean): Uint32Array; + + /** + Maps a Uint16Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @return Uint16Array to the DataStream backing buffer. + */ + mapUint16Array(length: number): Uint16Array; + + /** + Maps a Uint16Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return Uint16Array to the DataStream backing buffer. + */ + mapUint16Array(length: number, e: boolean): Uint16Array; + + /** + Maps a Uint8Array into the DataStream buffer. + * + Nice for quickly reading in data. + * + @param length Number of elements to map. + @return Uint8Array to the DataStream backing buffer. + */ + mapUint8Array(length: number): Uint8Array; + + /** + Maps a Float64Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @return Float64Array to the DataStream backing buffer. + */ + mapFloat64Array(length: number): Float64Array; + + /** + Maps a Float64Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return Float64Array to the DataStream backing buffer. + */ + mapFloat64Array(length: number, e: boolean): Float64Array; + + /** + Maps a Float32Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @return Float32Array to the DataStream backing buffer. + */ + mapFloat32Array(length: number): Float32Array; + + /** + Maps a Float32Array into the DataStream buffer, swizzling it to native + endianness in-place. The current offset from the start of the buffer needs to + be a multiple of element size, just like with typed array views. + * + Nice for quickly reading in data. Warning: potentially modifies the buffer + contents. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return Float32Array to the DataStream backing buffer. + */ + mapFloat32Array(length: number, e: boolean): Float32Array; + + /** + Reads an Int32Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @return The read Int32Array. + */ + readInt32Array(length: number): Int32Array; + + /** + Reads an Int32Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return The read Int32Array. + */ + readInt32Array(length: number, e: boolean): Int32Array; + + /** + Reads an Int16Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @return The read Int16Array. + */ + readInt16Array(length: number): Int16Array; + + /** + Reads an Int16Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return The read Int16Array. + */ + readInt16Array(length: number, e: boolean): Int16Array; + + /** + Reads an Int8Array of desired length from the DataStream. + * + @param length Number of elements to map. + @return The read Int8Array. + */ + readInt8Array(length: number): Int8Array; + + /** + Reads an Uint32Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @return The read Uint32Array. + */ + readUint32Array(length: number): Uint32Array; + + /** + Reads an Uint32Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return The read Uint32Array. + */ + readUint32Array(length: number, e: boolean): Uint32Array; + + /** + Reads an Uint16Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @return The read Uint16Array. + */ + readUint16Array(length: number): Uint16Array; + + /** + Reads an Uint16Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return The read Uint16Array. + */ + readUint16Array(length: number, e: boolean): Uint16Array; + + /** + Reads an Uint8Array of desired length from the DataStream. + * + @param length Number of elements to map. + @return The read Uint8Array. + */ + readUint8Array(length: number): Uint8Array; + + /** + Reads a Float64Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return The read Float64Array. + */ + readFloat64Array(length: number, e: boolean): Float64Array; + + /** + Reads a Float64Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @return The read Float64Array. + */ + readFloat64Array(length: number): Float64Array; + + /** + Reads a Float32Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @param e Endianness of the data to read. + @return The read Float32Array. + */ + readFloat32Array(length: number, e: boolean): Float32Array; + + /** + Reads a Float32Array of desired length and endianness from the DataStream. + * + @param length Number of elements to map. + @return The read Float32Array. + */ + readFloat32Array(length: number): Float32Array; + + /** + Writes an Int32Array of specified endianness to the DataStream. + * + @param arr The array to write. + @param e Endianness of the data to write. + */ + writeInt32Array(arr: Int32Array, e: boolean): void; + + /** + Writes an Int32Array of specified endianness to the DataStream. + * + @param arr The array to write. + */ + writeInt32Array(arr: Int32Array): void; + + /** + Writes an Int16Array of specified endianness to the DataStream. + * + @param arr The array to write. + @param e Endianness of the data to write. + */ + writeInt16Array(arr: Int16Array, e: boolean): void; + + /** + Writes an Int16Array of specified endianness to the DataStream. + * + @param arr The array to write. + */ + writeInt16Array(arr: Int16Array): void; + + /** + Writes an Int8Array to the DataStream. + * + @param arr The array to write. + */ + writeInt8Array(arr: Int8Array): void; + + /** + Writes an Uint32Array of specified endianness to the DataStream. + * + @param arr The array to write. + @param e Endianness of the data to write. + */ + writeUint32Array(arr: Uint32Array, e: boolean): void; + + /** + Writes an Uint32Array of specified endianness to the DataStream. + * + @param arr The array to write. + */ + writeUint32Array(arr: Uint32Array): void; + + /** + Writes an Uint16Array of specified endianness to the DataStream. + * + @param arr The array to write. + @param e Endianness of the data to write. + */ + writeUint16Array(arr: Uint16Array, e: boolean): void; + + /** + Writes an Uint16Array of specified endianness to the DataStream. + * + @param arr The array to write. + */ + writeUint16Array(arr: Uint16Array): void; + + /** + Writes an Uint8Array to the DataStream. + * + @param arr The array to write. + */ + writeUint8Array(arr: Uint8Array): void; + + /** + Writes a Float64Array of specified endianness to the DataStream. + * + @param arr The array to write. + */ + writeFloat64Array(arr: Float64Array): void; + + /** + Writes a Float64Array of specified endianness to the DataStream. + * + @param arr The array to write. + @param e Endianness of the data to write. + */ + writeFloat64Array(arr: Float64Array, e: boolean): void; + + /** + Writes a Float32Array of specified endianness to the DataStream. + * + @param arr The array to write. + */ + writeFloat32Array(arr: Float32Array): void; + + /** + Writes a Float32Array of specified endianness to the DataStream. + * + @param arr The array to write. + @param e Endianness of the data to write. + */ + writeFloat32Array(arr: Float32Array, e: boolean): void; + + /** + Reads a 32-bit int from the DataStream with the desired endianness. + * + @return The read number. + */ + readInt32(): number; + + /** + Reads a 32-bit int from the DataStream with the desired endianness. + * + @param e Endianness of the number. + @return The read number. + */ + readInt32(e: boolean): number; + + /** + Reads a 16-bit int from the DataStream with the desired endianness. + * + @return The read number. + */ + readInt16(): number; + + /** + Reads a 16-bit int from the DataStream with the desired endianness. + * + @param e Endianness of the number. + @return The read number. + */ + readInt16(e: boolean): number; + + /** + Reads an 8-bit int from the DataStream. + * + @return The read number. + */ + readInt8(): number; + + /** + Reads a 32-bit unsigned int from the DataStream with the desired endianness. + * + @return The read number. + */ + readUint32(): number; + + /** + Reads a 32-bit unsigned int from the DataStream with the desired endianness. + * + @param e Endianness of the number. + @return The read number. + */ + readUint32(e: boolean): number; + + /** + Reads a 16-bit unsigned int from the DataStream with the desired endianness. + * + @return The read number. + */ + readUint16(): number; + + /** + Reads a 16-bit unsigned int from the DataStream with the desired endianness. + * + @param e Endianness of the number. + @return The read number. + */ + readUint16(e: boolean): number; + + /** + Reads an 8-bit unsigned intfrom the DataStream. + * + @return The read number. + */ + readUint8(): number; + + /** + Reads a 32-bit float from the DataStream with the desired endianness. + * + @return The read number. + */ + readFloat32(): number; + + /** + Reads a 32-bit float from the DataStream with the desired endianness. + * + @param e Endianness of the number. + @return The read number. + */ + readFloat32(e: boolean): number; + + /** + Reads a 64-bit float from the DataStream with the desired endianness. + * + @return The read number. + */ + readFloat64(): number; + + /** + Reads a 64-bit float from the DataStream with the desired endianness. + * + @param e Endianness of the number. + @return The read number. + */ + readFloat64(e: boolean): number; + + /** + Writes a 32-bit int to the DataStream with the desired endianness. + * + @param v Number to write. + */ + writeInt32(v: number): void; + + /** + Writes a 32-bit int to the DataStream with the desired endianness. + * + @param v Number to write. + @param e Endianness of the number. + */ + writeInt32(v: number, e: boolean): void; + + /** + Writes a 16-bit int to the DataStream with the desired endianness. + * + @param v Number to write. + */ + writeInt16(v: number): void; + + /** + Writes a 16-bit int to the DataStream with the desired endianness. + * + @param v Number to write. + @param e Endianness of the number. + */ + writeInt16(v: number, e: boolean): void; + + /** + Writes an 8-bit int to the DataStream. + * + @param v Number to write. + */ + writeInt8(v: number): void; + + /** + Writes a 32-bit undigned int to the DataStream with the desired endianness. + * + @param v Number to write. + */ + writeUint32(v: number): void; + + /** + Writes a 32-bit undigned int to the DataStream with the desired endianness. + * + @param v Number to write. + @param e Endianness of the number. + */ + writeUint32(v: number, e: boolean): void; + + /** + Writes a 16-bit undigned int to the DataStream with the desired endianness. + * + @param v Number to write. + */ + writeUint16(v: number): void; + + /** + Writes a 16-bit undigned int to the DataStream with the desired endianness. + * + @param v Number to write. + @param e Endianness of the number. + */ + writeUint16(v: number, e: boolean): void; + + /** + Writes an 8-bit undigned int to the DataStream. + * + @param v Number to write. + */ + writeUint8(v: number): void; + + /** + Writes a 32-bit float to the DataStream with the desired endianness. + * + @param v Number to write. + */ + writeFloat32(v: number): void; + + /** + Writes a 32-bit float to the DataStream with the desired endianness. + * + @param v Number to write. + @param e Endianness of the number. + */ + writeFloat32(v: number, e: boolean): void; + + /** + Writes a 64-bit float to the DataStream with the desired endianness. + * + @param v Number to write. + */ + writeFloat64(v: number): void; + + /** + Writes a 64-bit float to the DataStream with the desired endianness. + * + @param v Number to write. + @param e Endianness of the number. + */ + writeFloat64(v: number, e: boolean): void; + + /** + Reads a struct of data from the DataStream. The struct is defined as + a flat array of [name, type]-pairs. See the example below: + * + ds.readStruct([ + 'headerTag', 'uint32', // Uint32 in DataStream endianness. + 'headerTag2', 'uint32be', // Big-endian Uint32. + 'headerTag3', 'uint32le', // Little-endian Uint32. + 'array', ['[]', 'uint32', 16], // Uint32Array of length 16. + 'array2Length', 'uint32', + 'array2', ['[]', 'uint32', 'array2Length'] // Uint32Array of length array2Length + ]); + * + The possible values for the type are as follows: + * + // Number types + // Unsuffixed number types use DataStream endianness. + // To explicitly specify endianness, suffix the type with + // 'le' for little-endian or 'be' for big-endian, + // e.g. 'int32be' for big-endian int32. + 'uint8' -- 8-bit unsigned int + 'uint16' -- 16-bit unsigned int + 'uint32' -- 32-bit unsigned int + 'int8' -- 8-bit int + 'int16' -- 16-bit int + 'int32' -- 32-bit int + 'float32' -- 32-bit float + 'float64' -- 64-bit float + * + // String types + 'cstring' -- ASCII string terminated by a zero byte. + 'string:N' -- ASCII string of length N, where N is a literal integer. + 'string:variableName' -- ASCII string of length $variableName, + where 'variableName' is a previously parsed number in the current struct. + 'string,CHARSET:N' -- String of byteLength N encoded with given CHARSET. + 'u16string:N' -- UCS-2 string of length N in DataStream endianness. + 'u16stringle:N' -- UCS-2 string of length N in little-endian. + 'u16stringbe:N' -- UCS-2 string of length N in big-endian. + * + // Complex types + [name, type, name_2, type_2, ..., name_N, type_N] -- Struct + function(dataStream, struct) {} -- Callback function to read and return data. + {get: function(dataStream, struct) {}, + set: function(dataStream, struct) {}} + -- Getter/setter functions to read and return data, handy for using the same + struct definition for reading and writing structs. + ['[]', type, length] -- Array of given type and length. The length can be either + a number, a string that references a previously-read + field, or a callback function(struct, dataStream, type){}. + If length is '*', reads in as many elements as it can. + * + @param structDefinition Struct definition object. + @return The read struct. Null if failed to read struct. + */ + readStruct(structDefinition: any[]): Object; + + /** + Writes a struct to the DataStream. Takes a structDefinition that gives the + types and a struct object that gives the values. Refer to readStruct for the + structure of structDefinition. + * + @param structDefinition Type definition of the struct. + @param struct The struct data object. + */ + writeStruct(structDefinition: Object, struct: Object): void; + + /** + Read UCS-2 string of desired length and endianness from the DataStream. + * + @param length The length of the string to read. + @return The read string. + */ + readUCS2String(length: number): string; + + /** + Read UCS-2 string of desired length and endianness from the DataStream. + * + @param length The length of the string to read. + @param endianness The endianness of the string data in the DataStream. + @return The read string. + */ + readUCS2String(length: number, endianness: boolean): string; + + /** + Write a UCS-2 string of desired endianness to the DataStream. The + lengthOverride argument lets you define the number of characters to write. + If the string is shorter than lengthOverride, the extra space is padded with + zeroes. + * + @param str The string to write. + */ + writeUCS2String(str: string): void; + + /** + Write a UCS-2 string of desired endianness to the DataStream. The + lengthOverride argument lets you define the number of characters to write. + If the string is shorter than lengthOverride, the extra space is padded with + zeroes. + * + @param str The string to write. + @param endianness The endianness to use for the written string data. + */ + writeUCS2String(str: string, endianness: boolean): void; + + /** + Write a UCS-2 string of desired endianness to the DataStream. The + lengthOverride argument lets you define the number of characters to write. + If the string is shorter than lengthOverride, the extra space is padded with + zeroes. + * + @param str The string to write. + @param endianness The endianness to use for the written string data. + @param lengthOverride The number of characters to write. + */ + writeUCS2String(str: string, endianness: boolean, lengthOverride: number): void; + + /** + Read a string of desired length and encoding from the DataStream. + * + @param length The length of the string to read in bytes. + @return The read string. + */ + readString(length: number): string; + + /** + Read a string of desired length and encoding from the DataStream. + * + @param length The length of the string to read in bytes. + @param encoding The encoding of the string data in the DataStream. Defaults to ASCII. + @return The read string. + */ + readString(length: number, encoding: string): string; + + /** + Writes a string of desired length and encoding to the DataStream. + * + @param s The string to write. + */ + writeString(s: string): void; + + /** + Writes a string of desired length and encoding to the DataStream. + * + @param s The string to write. + @param encoding The encoding for the written string data. Defaults to ASCII. + */ + writeString(s: string, encoding: string): void; + + /** + Writes a string of desired length and encoding to the DataStream. + * + @param s The string to write. + @param encoding The encoding for the written string data. Defaults to ASCII. + @param length The number of characters to write. + */ + writeString(s: string, encoding: string, length: number): void; + + /** + Read null-terminated string of desired length from the DataStream. Truncates + the returned string so that the null byte is not a part of it. + * + @return The read string. + */ + readCString(): string; + + /** + Read null-terminated string of desired length from the DataStream. Truncates + the returned string so that the null byte is not a part of it. + * + @param length The length of the string to read. + @return The read string. + */ + readCString(length: number): string; + + /** + Writes a null-terminated string to DataStream and zero-pads it to length + bytes. If length is not given, writes the string followed by a zero. + If string is longer than length, the written part of the string does not have + a trailing zero. + * + @param s The string to write. + */ + writeCString(s: string): void; + + /** + Writes a null-terminated string to DataStream and zero-pads it to length + bytes. If length is not given, writes the string followed by a zero. + If string is longer than length, the written part of the string does not have + a trailing zero. + * + @param s The string to write. + @param length The number of characters to write. + */ + writeCString(s: string, length: number): void; + + /** + Reads an object of type t from the DataStream, passing struct as the thus-far + read struct to possible callbacks that refer to it. Used by readStruct for + reading in the values, so the type is one of the readStruct types. + * + @param t Type of the object to read. + @return Returns the object on successful read, null on unsuccessful. + */ + readType(t: Object): Object; + + /** + Reads an object of type t from the DataStream, passing struct as the thus-far + read struct to possible callbacks that refer to it. Used by readStruct for + reading in the values, so the type is one of the readStruct types. + * + @param t Type of the object to read. + @param struct Struct to refer to when resolving length references and for calling callbacks. + @return Returns the object on successful read, null on unsuccessful. + */ + readType(t: Object, struct: Object): Object; + + /** + Writes object v of type t to the DataStream. + * + @param t Type of data to write. + @param v Value of data to write. + @param struct Struct to pass to write callback functions. + */ + writeType(t: Object, v: Object, struct: Object): void; +} diff --git a/ace/ace.d.ts b/ace/ace.d.ts index 29fadf3bc..72fefbc6e 100644 --- a/ace/ace.d.ts +++ b/ace/ace.d.ts @@ -576,7 +576,7 @@ declare module AceAjax { /** * Returns the current tab size. **/ - getTabSize(): string; + getTabSize(): number; /** * Returns `true` if the character at the position is a soft tab. @@ -1034,6 +1034,9 @@ declare module AceAjax { * Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them. **/ export interface Editor { + + addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any); + addEventListener(ev: string, callback: Function); inMultiSelectMode: boolean; @@ -1710,6 +1713,13 @@ declare module AceAjax { **/ new(renderer: VirtualRenderer, session?: IEditSession): Editor; } + + interface EditorChangeEvent { + start: Position; + end: Position; + action: string; // insert, remove + lines: any[]; + } //////////////////////////////// /// PlaceHolder diff --git a/angular-file-upload/angular-file-upload.d.ts b/angular-file-upload/angular-file-upload.d.ts index 2eb0e72b5..bd76a6e7e 100644 --- a/angular-file-upload/angular-file-upload.d.ts +++ b/angular-file-upload/angular-file-upload.d.ts @@ -9,7 +9,7 @@ declare module angular.angularFileUpload { interface IUploadService { - http(config: ng.IRequestConfig): IUploadPromise; + http(config: IRequestConfig): IUploadPromise; upload(config: IFileUploadConfig): IUploadPromise; } @@ -18,7 +18,7 @@ declare module angular.angularFileUpload { progress(callback: IHttpPromiseCallback): IUploadPromise; } - interface IFileUploadConfig extends ng.IRequestConfig { + interface IFileUploadConfig extends IRequestConfig { file: File; fileName?: string; diff --git a/angular-local-storage/angular-local-storage.d.ts b/angular-local-storage/angular-local-storage.d.ts index 374f57af0..f0500a96f 100644 --- a/angular-local-storage/angular-local-storage.d.ts +++ b/angular-local-storage/angular-local-storage.d.ts @@ -129,7 +129,7 @@ declare module angular.local.storage { * @param value optional * @param key The corresponding key used in local storage */ - bind(scope:ng.IScope, property: string, value?: any, key?: string): Function; + bind(scope: angular.IScope, property: string, value?: any, key?: string): Function; /** * Return the derive key * Returns String diff --git a/angular-localForage/angular-localForage-tests.ts b/angular-localForage/angular-localForage-tests.ts new file mode 100644 index 000000000..8b31143c2 --- /dev/null +++ b/angular-localForage/angular-localForage-tests.ts @@ -0,0 +1,126 @@ +/// +/// + +var app = angular.module('angular-localForage-tests', ['LocalForageModule']); +app.config(function (localStorageServiceProvider:angular.localForage.ILocalForageProvider) { + + //TODO +}); + +var $rootScope:angular.IRootScopeService, + $localForage:angular.localForage.ILocalForageService, + instanceVersion = 0; + +// create a fresh instance +$localForage.clear().then(function () { + $localForage = $localForage.createInstance({ + name: ++instanceVersion + }); +}); + +$localForage.getItem('this key is unknown').then(function (value) { + +}); + + +$localForage.setItem('myName', 'Olivier Combe').then(function (data) { + + $localForage.getItem('myName').then(function (data) { + }); +}); + +var values = ['Olivier Combe', 'AngularJs', 'Open Source']; + +$localForage.setItem(['myName', 'myPassion', 'myHobbie'], values).then(function (data) { + + $localForage.getItem(['myHobbie', 'myName']).then(function (data) { + }); + +}); + +$localForage.removeItem('myName').then(function () { + + $localForage.getItem('myName').then(function (data) { + }); + +}); + +$localForage.removeItem(['myName', 'myPassion']).then(function () { + + $localForage.getItem(['myName', 'myPassion', 'myHobbie']).then(function (data) { + }); + +}); + +$localForage.pull('myName').then(function (data) { + + $localForage.getItem('myName').then(function (data) { + }); + +}); +$localForage.pull(['myName', 'myPassion']).then(function (data) { + + $localForage.getItem(['myName', 'myPassion', 'myHobbie']).then(function (data) { + }); + +}); + + +$localForage.setItem('myName', 'Olivier Combe').then(function (d) { + + $localForage.getItem('myName').then(function (data) { + }); + +}); + + +$localForage.setDriver('localStorageWrapper').then(function () { + $localForage.setItem('myName', 'Olivier Combe').then(function (d) { + $localForage.getItem('myName').then(function (data) { + }); + }); +}); + +$localForage.setItem('myArray', [{ + $$hashKey: '00A', + name: 'Olivier Combe' +}]).then(function (d) { + + $localForage.getItem('myArray').then(function (data) { + }); + +}); + +$localForage.setDriver('localStorageWrapper').then(function () { + $localForage.setItem('myArray', [{ + $$hashKey: '00A', + name: 'Olivier Combe' + }]).then(function (d) { + + $localForage.getItem('myArray').then(function (data) { + }); + + }); +}); + +var aFileParts = ["hey!<\/b><\/a>"]; +var oMyBlob = new Blob(aFileParts, {"type": "text\/xml"}); // the blob + +$localForage.setItem('myBlob', oMyBlob).then(function (data) { +}); + +// $localForage.setItem(['myName', 'myPassion', 'myHobbie'], 'value'); + +// $localForage.setItem(); + + +$localForage.iterate(function (value, key) { +}).then(function (data) { +}); + +$localForage.iterate(function (value, key) { + if (key == 'myPassion') { + return value; + } +}).then(function (data) { +}); diff --git a/angular-localForage/angular-localForage.d.ts b/angular-localForage/angular-localForage.d.ts new file mode 100644 index 000000000..ee2aeeb6d --- /dev/null +++ b/angular-localForage/angular-localForage.d.ts @@ -0,0 +1,63 @@ +// Type definitions for angular-localForage 1.2.2 +// Project: https://github.com/ocombe/angular-localForage +// Definitions by: Stefan Steinhart +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module angular.localForage { + + interface LocalForageConfig { + driver?:string; + name?:string | number; + version?:number; + storeName?:string; + description?:string; + } + + interface ILocalForageProvider { + config(config:LocalForageConfig):void; + setNotify(onItemSet:boolean, onItemRemove:boolean):void; + } + + interface ILocalForageService { + setDriver(driver:string):angular.IPromise; + driver():lf.ILocalForage; + + setItem(key:string, value:any):angular.IPromise; + setItem(keys:Array, values:Array):angular.IPromise; + + getItem(key:string):angular.IPromise; + getItem(keys:Array):angular.IPromise>; + + removeItem(key:string | Array):angular.IPromise; + + pull(key:string):angular.IPromise; + pull(keys:Array):angular.IPromise>; + + clear():angular.IPromise; + + key(n:number):angular.IPromise; + + keys():angular.IPromise; + + length():angular.IPromise; + + iterate(iteratorCallback:(value:string | number, key:string)=>T):angular.IPromise; + + bind($scope:ng.IScope, key:string):void; + + bind($scope:ng.IScope, config:{ + key:string; + defaultValue:any; + scopeKey:string; + name:string; + }):void; + + unbind($scope:ng.IScope, key:string, scopeKey?:string):void; + + createInstance(config:LocalForageConfig):ILocalForageService; + instance(name:string):ILocalForageService; + } +} diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 89cf14154..06c1ecf25 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -102,6 +102,7 @@ declare module angular.material { capsule(capsule: boolean): T; theme(theme: string): T; hideDelay(delay: number): T; + position(position: string): T; } interface MDSimpleToastPreset extends MDToastPreset { diff --git a/angular-meteor/angular-meteor-tests.ts b/angular-meteor/angular-meteor-tests.ts new file mode 100644 index 000000000..9ce0a33e9 --- /dev/null +++ b/angular-meteor/angular-meteor-tests.ts @@ -0,0 +1,255 @@ +/// + +interface ITodo { + _id?: string; + name: string; + public?: boolean; + sticky?: boolean; +} + +interface TodoAngularMeteorObject extends ITodo, angular.meteor.AngularMeteorObject {} + +interface CustomScope extends angular.meteor.IScope { + sticky: boolean; + + todos: angular.meteor.AngularMeteorCollection; + stickyTodos: angular.meteor.AngularMeteorCollection; + notAutoTodos: angular.meteor.AngularMeteorCollection; + + todo: ITodo; + todoNotAuto: TodoAngularMeteorObject; + todoSubscribed: TodoAngularMeteorObject; + + save: (todo: ITodo) => void; + saveAll: () =>void; + autoSave: (todo: ITodo) => void; + remove: (todoId: string) => void; + removeAll: () => void; + removeAuto: (todo: ITodo) => void; + toSticky: (todo: ITodo) => void; +} + +var Todos = new Mongo.Collection('todos'); + +var app = angular.module('angularMeteorTestApp'); + +app.controller("mainCtrl", ['$scope', '$meteor', ($scope: CustomScope, $meteor: angular.meteor.IMeteorService) => { + // Bind all the todos to $scope.todos + $scope.todos = $meteor.collection(Todos); + + $scope.sticky = true; + // Bind all sticky todos to $scope.stickyTodos + // Binds the query to $scope.sticky so that if it changes, Meteor will re-run the query and bind it + // to $scope.stickyTodos + $scope.stickyTodos = $meteor.collection(function(){ + return Todos.find({sticky: $scope.getReactively('sticky')}); + }); + + // Bind without auto-save all todos to $scope.notAutoTodos + $scope.notAutoTodos = $meteor.collection(Todos, false).subscribe("publicTodos"); + + $scope.todoNotAuto = $meteor.object(Todos, 'TodoID', false); + $scope.todoSubscribed = $meteor.object(Todos, 'TodoID').subscribe('todos'); + $scope.todo = $scope.todoNotAuto.getRawObject(); + $scope.todoNotAuto.reset(); + $scope.todoNotAuto.save($scope.todo).then((data) => { return data == 1; });; + + // todo might be an object like this {text: "Learn Angular", sticky: false} + // or an array like this: + // [{text: "Learn Angular", sticky: false}, {text: "Hello World", sticky: true}] + + $scope.save = function(todo) { + $scope.notAutoTodos.save(todo); + }; + + $scope.saveAll = function() { + $scope.notAutoTodos.save(); + }; + + $scope.autoSave = function(todo) { + $scope.todos.push(todo); + }; + + // todoId might be an string like this "WhrnEez5yBRgo4yEm" + // or an array like this ["WhrnEez5yBRgo4yEm","gH6Fa4DXA3XxQjXNS"] + $scope.remove = function(todoId) { + $scope.notAutoTodos.remove(todoId); + }; + + $scope.removeAll = function() { + $scope.notAutoTodos.remove(); + }; + + $scope.removeAuto = function(todo) { + $scope.todos.splice( $scope.todos.indexOf(todo), 1 ); + } + + $scope.toSticky = function(todo) { + if (angular.isArray(todo)){ + angular.forEach(todo, function(object) { + object.sticky = true; + }); + } else { + todo.sticky = true; + } + + $scope.stickyTodos.save(todo); + }; + + var todoObject = {name:'first todo'}; + var todosArray = [{name:'second todo'}, {name:'third todo'}]; + var todoSecondObject = {name:'forth todo'}; + + $scope.todos.save(todoObject); // todos equals [{name:'first todo'}] + + $scope.todos.save(todosArray); // todos equals [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}] + + $scope.todos.push(todoSecondObject); // The scope variable equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}] + // but the collection still equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}] + + $scope.todos.save(); // Now the collection also equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}] + + $scope.todos.remove('firstTodoId'); // scope and collection equals to [{name:'second todo'}, {name:'third todo'}, {name:'forth todo'}] + + var todoIdsArray = ['secondTodoId', 'thirdTodoId']; + $scope.todos.remove(todoIdsArray); // removes everything matches the array of IDs both in scope and in collection + + $scope.todos.pop(); // removes only in scope + + $scope.todos.remove(); // syncs also in Meteor collection + + // Subscribe -> + + $meteor.subscribe('todos').then((subscriptionHandle) => { + // Bind all the todos to $scope.todos + $scope.todos = $meteor.collection(Todos); + + console.log($scope.todos + ' is ready'); + + // You can use the subscription handle to stop the subscription if you want + subscriptionHandle.stop(); + }); + + $scope.subscribe('todos').then((subscriptionHandle) => { + // Bind all the todos to $scope.books + $scope.todos = $meteor.collection(Todos); + + console.log($scope.todos + ' is ready'); + + // No need to stop the subscription, it will automatically close on scope destroy + }); + + $meteor.call('subscribe', $scope.todo._id, $scope.currentUser._id).then((data) => { + // Handle success + console.log('success subscribing', data.name); + }, (err) => { + // Handle error + console.log('failed', err); + }); + + if (!$scope.loggingIn) { + $meteor.waitForUser(); + + $meteor.requireUser(); + + $meteor.requireValidUser(user => { + return user.username == 'admin'; + }); + + $meteor.loginWithPassword('user', 'password').then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + + $meteor.createUser({ + username:'moma', + email:'example@gmail.com', + password: 'Bksd@asdf', + profile: {expertize: 'Developer'} + }).then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + + $meteor.changePassword('old', 'new232f3').then(() => { + console.log('Change password success'); + }, err => { + console.log('Error changing password - ', err); + }); + + $meteor.forgotPassword({email: 'sample@gmail.com'}).then(() => { + console.log('Success sending forgot password email'); + }, err => { + console.log('Error sending forgot password email - ', err); + }); + + $meteor.resetPassword('tokenID', 'new232f3').then(() => { + console.log('Reset password success'); + }, err => { + console.log('Error resetting password - ', err); + }); + + $meteor.verifyEmail('tokenID').then(() => { + console.log('Success verifying password '); + }, err => { + console.log('Error verifying password - ', err); + }); + + $meteor.logout().then(() => { + console.log('Logout success'); + }, err => { + console.log('logout error - ', err); + }); + + $meteor.logoutOtherClients().then(() => { + console.log('Logout success'); + }, err => { + console.log('logout error - ', err); + }); + + var loginWithOptions = {requestPermissions: ['email']}; + + $meteor.loginWithFacebook({requestPermissions: ['email']}).then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + $meteor.loginWithGithub({requestPermissions: ['email']}).then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + $meteor.loginWithGoogle({requestPermissions: ['email']}).then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + $meteor.loginWithMeetup({requestPermissions: ['email']}).then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + $meteor.loginWithTwitter({requestPermissions: ['email']}).then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + $meteor.loginWithWeibo({requestPermissions: ['email']}).then(() => { + console.log('Login success'); + }, err => { + console.log('Login error - ', err); + }); + } + + $meteor.autorun($scope, () => { console.log("Aurorun triggered."); }); + $meteor.getCollectionByName('collectionName'); + + // requires meteor add mdg:camera + $meteor.getPicture().then(function(data){ + $scope['picture'] = data; + }); + + $meteor.session('counter').bind($scope, 'counter'); +}]); diff --git a/angular-meteor/angular-meteor.d.ts b/angular-meteor/angular-meteor.d.ts new file mode 100644 index 000000000..b3f520ac5 --- /dev/null +++ b/angular-meteor/angular-meteor.d.ts @@ -0,0 +1,330 @@ +// Type definitions for Angular JS Meteor v0.8.8 (angular.meteor module) +// Project: https://github.com/Urigo/angular-meteor +// Definitions by: Peter Grman +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module angular.meteor { + interface IRootScopeService extends angular.IRootScopeService { + /** + * The current logged in user and it's data. it is null if the user is not logged in. A reactive data source. + */ + currentUser: Meteor.User; + + /** + * True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress. + * A reactive data source. Can be use to display animation while user is logging in. + */ + loggingIn: boolean; + } + + interface IScope extends angular.IScope, IRootScopeService { + /** + * A method to get a $scope variable and watch it reactivly + * + * @param scopeVariableName - The name of the scope's variable to bind to + * @param [objectEquality=false] - Watch the object equality using angular.equals instead of comparing for reference equality, deeper watch but also slower + */ + getReactively(scopeVariableName: string, objectEquality?: boolean): ReactiveResult; + + /** + * A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready. + * Calling $scope.subscribe will automatically stop the subscription when the scope is destroyed. + * + * @param name - Name of the subscription. Matches the name of the server's publish() call. + * @param publisherArguments - Optional arguments passed to publisher function on server. + * + * @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle. + */ + subscribe(name: string, ...publisherArguments: any[]): angular.IPromise; + } + + /** + * $meteor in angularjs + */ + interface IMeteorService { + /** + * A service that wraps the Meteor collections to enable reactivity within AngularJS. + * + * @param collection - A Meteor Collection or a reactive function to bind to. + * - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor. + * @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection. + * - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection. + */ + collection(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection; + + /** + * A service that wraps the Meteor collections to enable reactivity within AngularJS. + * + * @param collection - A Meteor Collection or a reactive function to bind to. + * - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor. + * @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection. + * - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection. + * @param [updateCollection] - A collection object which will be used for updates (insert, update, delete). + */ + collection(collection: Mongo.Collection|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection): AngularMeteorCollection2; + + /** + * A service that wraps a Meteor object to enable reactivity within AngularJS. + * Finds the first document that matches the selector, as ordered by sort and skip options. Wraps collection.findOne + * + * @param collection - A Meteor Collection to bind to. + * @param selector - A query describing the documents to find or just the ID of the document. + * - $meteor.object will find the first document that matches the selector, + * - as ordered by sort and skip options, exactly like Meteor's collection.findOne + * @param [autoClientSave=true] - By default, changes in the Angular object will automatically update the Meteor object. + * - However if set to false, changes in the client won't be automatically propagated back to the Meteor object. + */ + object(collection: Mongo.Collection, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject; + + /** + * A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready. + * + * @param name - Name of the subscription. Matches the name of the server's publish() call. + * @param publisherArguments - Optional arguments passed to publisher function on server. + * + * @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle. + */ + subscribe(name: string, ...publisherArguments: any[]): angular.IPromise; + + /** + * A service service which wraps up Meteor.methods with AngularJS promises. + * + * @param name - Name of method to invoke + * @param methodArguments - Optional method arguments + * + * @return The promise solves successfully with the return value of the method or return reject with the error from the method. + */ + call(name: string, ...methodArguments: any[]): angular.IPromise; + + // User Authentication BEGIN -> + + /** + * Returns a promise fulfilled with the currentUser when the user subscription is ready. + * This is useful when you want to grab the current user before the route is rendered. + * If there is no logged in user, it will return null. + * See the “Authentication with Routers” section of our tutorial for more information and a full example. + */ + waitForUser(): angular.IPromise; + + /** + * Resolves the promise successfully if a user is authenticated and rejects otherwise. + * This is useful in cases where you want to require a route to have an authenticated user. + * You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page. + * See the “Authentication with Routers” section of our tutorial for more information and a full example. + */ + requireUser(): angular.IPromise; + + /** + * Resolves the promise successfully if a user is authenticated and the validatorFn returns true; rejects otherwise. + * This is useful in cases where you want to require a route to have an authenticated user and do extra validation like the user's role or group. + * You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page. + * See the “Authentication with Routers” section of our tutorial for more information and a full example. + * + * The mandatory validator function will be called with the authenticated user as the single param and it's expected to return true in order to resolve. + * If it returns a string, the promise will be rejected using said string as the reason. + * Any other return (false, null, undefined) will be rejected with the default "FORBIDDEN" reason. + */ + requireValidUser(validatorFn: (user: Meteor.User) => boolean|string): angular.IPromise; + + /** + * Log the user in with a password. + * + * @param user - Either a string interpreted as a username or an email; or an object with a single key: email, username or id. + * @param password - The user's password. + */ + loginWithPassword(user: string|{email: string}|{username: string}|{id: string}, password: string): angular.IPromise; + + /** + * Create a new user. More information: http://docs.meteor.com/#/full/accounts_createuser + * + * @param options.username - A unique name for this user. Either this, or email is required. + * @param options.email - The user's email address. Either this, or username is required. + * @param options.password - The user's password. This is not sent in plain text over the wire. + * @param options.profile - The user's profile, typically including the name field. + */ + createUser(options: {username?: string; email?: string; password: string; profile?: Object}): angular.IPromise; + + /** + * Change the current user's password. Must be logged in. + * + * @param oldPassword - The user's current password. This is not sent in plain text over the wire. + * @param newPassword - A new password for the user. This is not sent in plain text over the wire. + */ + changePassword(oldPassword: string, newPassword: string): angular.IPromise; + + /** + * Request a forgot password email. + * + * @param options.email - The email address to send a password reset link. + */ + forgotPassword(options: {email: string}): angular.IPromise; + + /** + * Reset the password for a user using a token received in email. Logs the user in afterwards. + * + * @param token - The token retrieved from the reset password URL. + * @param newPassword - A new password for the user. This is not sent in plain text over the wire. + */ + resetPassword(token: string, newPassword: string): angular.IPromise; + + /** + * Marks the user's email address as verified. Logs the user in afterwards. + * + * @param token - The token retrieved from the reset password URL. + */ + verifyEmail(token: string): angular.IPromise; + + loginWithFacebook: ILoginWithExternalService; + loginWithTwitter: ILoginWithExternalService; + loginWithGoogle: ILoginWithExternalService; + loginWithGithub: ILoginWithExternalService; + loginWithMeetup: ILoginWithExternalService; + loginWithWeibo: ILoginWithExternalService; + + /** + * Log the user out. + * + * @return Resolves with no arguments on success, or reject with a Error argument on failure. + */ + logout(): angular.IPromise; + + /** + * Log out other clients logged in as the current user, but does not log out the client that calls this function. + * For example, when called in a user's browser, connections in that browser remain logged in, + * but any other browsers or DDP clients logged in as that user will be logged out. + * + * @return Resolves with no arguments on success, or reject with a Error argument on failure. + */ + logoutOtherClients(): angular.IPromise; + + // <- User Authentication END + // $meteorUtils BEGIN -> + + /** + * @param scope - The AngularJS scope you use the autorun on. + * @param fn - The function that will re-run every time a reactive variable changes inside it. + */ + autorun(scope: angular.IScope, fn: Function): void; + + /** + * @param collectionName - The name of the collection you want to get back + */ + getCollectionByName(collectionName: string): Mongo.Collection; + + // <- $meteorUtils END + // $meteorCamera BEGIN -> + + /** + * A helper service for taking pictures across platforms. + * Must add mdg:camera package to use! (meteor add mdg:camera) + * + * @param [options] - options is an optional argument that is an Object with the following possible keys: + * @param options.width - An integer that specifies the minimum width of the returned photo. + * @param options.height - An integer that specifies the minimum height of the returned photo. + * @param options.quality - A number from 0 to 100 specifying the desired quality of JPEG encoding. + * + * @return The promise solved successfully when the picture is taken with the data as a parameter or rejected with an error as a parameter in case of error. + */ + getPicture(options?: {width?: number; height?: number; quality?: number}): angular.IPromise; + + // <- $meteorCamera END + + /** + * A service that binds a scope variable to a Meteor Session variable. + * + * @param sessionKey - The name of the session variable + * @return An object with a single function bind - to bind to that variable. + */ + session(sessionKey: string): { + /** + * @param scope - The scope the document will be bound to. + * @param model - The name of the scope's model variable that the document will be bound to. + */ + bind: (scope: IScope, model: string) => void; + }; + } + + /** + * An object that connects a Meteor Object to an AngularJS scope variable. + * + * The object contains also all the properties from the generic type T, + * unfortunately TypeScript doesn't at the moment allow to extend a generic type (see https://github.com/Microsoft/TypeScript/issues/2225 for details and updates). + * For a workaround, you'll need to implement an interface which will merge AngularMeteorObject together with T and cast it, like this: + * + * interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject { } + * var todo = $meteor.object(TodoCollection, 'TodoID'); + */ + interface AngularMeteorObject { + /** + * @param [doc] - The doc to save to the Meteor Object. If nothing is passed, the method saves everything in the AngularMeteorObject as is. + * - Unchanged properties will be overridden with their existing values, which may trigger hooks. + * - If doc is passed, the method only updates the Meteor Object with the properties passed, and no other changes will be saved. + * + * @return Returns a promise with an error in case for an error or a number of successful docs changed in case of success. + */ + save(doc?: T): angular.IPromise; + + /** + * Reset the current value of the object to the one in the server. + */ + reset(): void; + + /** + * Returns a copy of the AngularMeteorObject with all the AngularMeteor-specific internal properties removed. + * The returned object is then safe to use as a parameter for method calls, or anywhere else where the data needs to be converted to JSON. + */ + getRawObject(): T; + + /** + * A shorten (Syntactic sugar) function for the $meteor.subscribe function. + * Takes only one parameter and not returns a promise like $meteor.subscribe does. + * + * @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service. + */ + subscribe(subscriptionName:string): AngularMeteorObject; + } + + /** + * An object that connects a Meteor Collection to an AngularJS scope variable + */ + interface AngularMeteorCollection extends AngularMeteorCollection2 { } + + /** + * An object that connects a Meteor Collection to an AngularJS scope variable, + * but can use a differen type for updates. + */ + interface AngularMeteorCollection2 extends Array { + /** + * @param [docs] - The docs to save to the Meteor Collection. + * - If the docs parameter is empty, the method saves everything in the AngularMeteorCollection as is. + * - If an object is passed, the method pushes that object into the AngularMeteorCollection. + * - If an array is passed, the method pushes all objects in the array into the AngularMeteorCollection. + */ + save(docs?: U|U[]): void; + + /** + * @param [keys] - The keys of the object to remove from the Meteor Collection. + * - If nothing is passed, the method removes all the documents from the AngularMeteorCollection. + * - If an object is passed, the method removes the object with that key from the AngularMeteorCollection. + * - If an array is passed, the method removes all objects that matches the keys in the array from the AngularMeteorCollection. + */ + remove(keys?: U|string|number|string[]|number[]): void; + + /** + * A shorten (Syntactic sugar) function for the $meteor.subscribe function. + * Takes only one parameter and not returns a promise like $meteor.subscribe does. + * + * @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service. + */ + subscribe(subscriptionName:string): AngularMeteorCollection2; + } + + interface ILoginWithExternalService { + (options: Meteor.LoginWithExternalServiceOptions): angular.IPromise; + } + + interface ReactiveResult { } +} diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index bfc573dcc..87a75439b 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -6,13 +6,7 @@ /// declare module angular.translate { - - interface ITranslatePartialLoaderService { - addPart(name: string): ITranslatePartialLoaderService; - deletePart(name: string, removeData?: boolean): ITranslatePartialLoaderService; - isPartAvailable(name: string): boolean; - } - + interface ITranslationTable { [key: string]: string; } @@ -26,12 +20,27 @@ declare module angular.translate { set(name: string, value: string): void; } - interface ISTaticFilesLoaderOptions { + interface IStaticFilesLoaderOptions { prefix: string; suffix: string; key?: string; } + interface IPartialLoader { + addPart(name : string, priority? : number) : T; + deletePart(name : string) : T; + isPartAvailable(name : string) : boolean; + } + + interface ITranslatePartialLoaderService extends IPartialLoader { + getRegisteredParts() : Array; + isPartLoaded(name : string, lang : string) : boolean; + } + + interface ITranslatePartialLoaderProvider extends angular.IServiceProvider, IPartialLoader { + setPart(lang : string, part : string, table : ITranslationTable) : ITranslatePartialLoaderProvider; + } + interface ITranslateService { (translationId: string, interpolateParams?: any, interpolationId?: string): angular.IPromise; (translationId: string[], interpolateParams?: any, interpolationId?: string): angular.IPromise<{ [key: string]: string }>; @@ -78,7 +87,7 @@ declare module angular.translate { storageKey(): string; storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here useUrlLoader(url: string): ITranslateProvider; - useStaticFilesLoader(options: ISTaticFilesLoaderOptions): ITranslateProvider; + useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider; useLoader(loaderFactory: string, options: any): ITranslateProvider; useLocalStorage(): ITranslateProvider; useCookieStorage(): ITranslateProvider; diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 8d42fee7d..bfec95156 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -64,7 +64,7 @@ declare module angular.ui { reloadOnSearch?: boolean; } - interface IStateProvider extends ng.IServiceProvider { + interface IStateProvider extends angular.IServiceProvider { state(name:string, config:IState): IStateProvider; state(config:IState): IStateProvider; decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; @@ -83,7 +83,7 @@ declare module angular.ui { type(name: string, definition: any, definitionFn?: any): any; } - interface IUrlRouterProvider extends ng.IServiceProvider { + interface IUrlRouterProvider extends angular.IServiceProvider { when(whenPath: RegExp, handler: Function): IUrlRouterProvider; when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; when(whenPath: RegExp, toPath: string): IUrlRouterProvider; @@ -145,7 +145,7 @@ declare module angular.ui { * * @param options Options object. */ - go(to: string, params?: {}, options?: IStateOptions): ng.IPromise; + go(to: string, params?: {}, options?: IStateOptions): angular.IPromise; transitionTo(state: string, params?: {}, updateLocation?: boolean): void; transitionTo(state: string, params?: {}, options?: IStateOptions): void; includes(state: string, params?: {}): boolean; diff --git a/angular2/angular2-tests.ts b/angular2/angular2-tests.ts new file mode 100644 index 000000000..bdd2628e5 --- /dev/null +++ b/angular2/angular2-tests.ts @@ -0,0 +1,28 @@ +/// + +// Use Typescript 1.4 style imports +import ng = require("angular2/angular2"); +import di = require("angular2/di"); + +class Service { + +} +class Service2 { + +} + +class Cmp { + static annotations: any[]; +} +Cmp.annotations = [ + ng.Component({ + selector: 'cmp', + injectables: [Service, di.bind(Service2).toValue(null)] + }), + ng.View({ + template: '{{greeting}} world!', + directives: [ng.For, ng.If] + }) +]; + +ng.bootstrap(Cmp); diff --git a/angular2/angular2.d.ts b/angular2/angular2.d.ts new file mode 100644 index 000000000..fa3cc7788 --- /dev/null +++ b/angular2/angular2.d.ts @@ -0,0 +1,622 @@ +// Type definitions for Angular v2.0.0-alpha.22 +// Project: http://angular.io/ +// Definitions by: angular team +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/****************** + * This is a minimal type definition for the Angular2 quickstart. + * We plan to publish a complete definition soon. + ******************/ + +interface List extends Array {} +interface Type {} + +interface _ComponentArg { + /** + * The CSS selector that triggers the instantiation of a directive. + * + * Angular only allows directives to trigger on CSS selectors that do not cross element boundaries. + * + * `selector` may be declared as one of the following: + * + * - `element-name`: select by element name. + * - `.class`: select by class name. + * - `[attribute]`: select by attribute name. + * - `[attribute=value]`: select by attribute name and value. + * - `:not(sub_selector)`: select only if the element does not match the `sub_selector`. + * - `selector1, selector2`: select if either `selector1` or `selector2` matches. + * + * + * ## Example + * + * Suppose we have a directive with an `input[type=text]` selector. + * + * And the following HTML: + * + * ```html + *
+ * + * + * + * ``` + * + * The directive would only be instantiated on the `` element. + * + */ + selector: string; + + /** + * Enumerates the set of properties that accept data binding for a directive. + * + * The `properties` property defines a set of `directiveProperty` to `bindingProperty` + * key-value pairs: + * + * - `directiveProperty` specifies the component property where the value is written. + * - `bindingProperty` specifies the DOM property where the value is read from. + * + * You can include a {@link Pipe} when specifying a `bindingProperty` to allow for data transformation and structural + * change detection of the value. These pipes will be evaluated in the context of this component. + * + * + * ## Syntax + * + * ``` + * @Directive({ + * properties: { + * 'directiveProperty1': 'bindingProperty1', + * 'directiveProperty2': 'bindingProperty2 | pipe1 | ...', + * ... + * } + * } + * ``` + * + * + * ## Basic Property Binding + * + * We can easily build a simple `Tooltip` directive that exposes a `tooltip` property, which can be used in templates + * with standard Angular syntax. For example: + * + * ``` + * @Directive({ + * selector: '[tooltip]', + * properties: { + * 'text': 'tooltip' + * } + * }) + * class Tooltip { + * set text(text) { + * // This will get called every time the 'tooltip' binding changes with the new value. + * } + * } + * ``` + * + * We can then bind to the `tooltip' property as either an expression (`someExpression`) or as a string literal, as + * shown in the HTML template below: + * + * ```html + *
...
+ *
...
+ * ``` + * + * Whenever the `someExpression` expression changes, the `properties` declaration instructs + * Angular to update the `Tooltip`'s `text` property. + * + * + * + * ## Bindings With Pipes + * + * You can also use pipes when writing binding definitions for a directive. + * + * For example, we could write a binding that updates the directive on structural changes, rather than on reference + * changes, as normally occurs in change detection. + * + * See {@link Pipe} and {@link keyValDiff} documentation for more details. + * + * ``` + * @Directive({ + * selector: '[class-set]', + * properties: { + * 'classChanges': 'classSet | keyValDiff' + * } + * }) + * class ClassSet { + * set classChanges(changes:KeyValueChanges) { + * // This will get called every time the `class-set` expressions changes its structure. + * } + * } + * ``` + * + * The template that this directive is used in may also contain its own pipes. For example: + * + * ```html + *
+ * ``` + * + * In this case, the two pipes compose as if they were inlined: `someExpression | somePipe | keyValDiff`. + * + */ + properties?: Object; + + /** + * Specifies which DOM hostListeners a directive listens to. + * + * The `hostListeners` property defines a set of `event` to `method` key-value pairs: + * + * - `event1`: the DOM event that the directive listens to. + * - `statement`: the statement to execute when the event occurs. + * If the evalutation of the statement returns `false`, then `preventDefault`is applied on the DOM event. + * + * To listen to global events, a target must be added to the event name. + * The target can be `window`, `document` or `body`. + * + * When writing a directive event binding, you can also refer to the following local variables: + * - `$event`: Current event object which triggered the event. + * - `$target`: The source of the event. This will be either a DOM element or an Angular directive. + * (will be implemented in later release) + * + * + * ## Syntax + * + * ``` + * @Directive({ + * hostListeners: { + * 'event1': 'onMethod1(arguments)', + * 'target:event2': 'onMethod2(arguments)', + * ... + * } + * } + * ``` + * + * ## Basic Event Binding: + * + * Suppose you want to write a directive that triggers on `change` events in the DOM and on `resize` events in window. + * You would define the event binding as follows: + * + * ``` + * @Directive({ + * selector: 'input', + * hostListeners: { + * 'change': 'onChange($event)', + * 'window:resize': 'onResize($event)' + * } + * }) + * class InputDirective { + * onChange(event:Event) { + * } + * onResize(event:Event) { + * } + * } + * ``` + * + * Here the `onChange` method of `InputDirective` is invoked whenever the DOM element fires the 'change' event. + * + */ + hostListeners?: Object; + + /** + * Defines the set of injectable objects that are visible to a Component and its children. + * + * The `injectables` defined in the Component annotation allow you to configure a set of bindings for the component's + * injector. + * + * When a component is instantiated, Angular creates a new child Injector, which is configured with the bindings in + * the Component `injectables` annotation. The injectable objects then become available for injection to the component + * itself and any of the directives in the component's template, i.e. they are not available to the directives which + * are children in the component's light DOM. + * + * + * The syntax for configuring the `injectables` injectable is identical to {@link Injector} injectable configuration. + * See {@link Injector} for additional detail. + * + * + * ## Simple Example + * + * Here is an example of a class that can be injected: + * + * ``` + * class Greeter { + * greet(name:string) { + * return 'Hello ' + name + '!'; + * } + * } + * + * @Component({ + * selector: 'greet', + * injectables: [ + * Greeter + * ] + * }) + * @View({ + * template: `{{greeter.greet('world')}}!`, + * directives: Child + * }) + * class HelloWorld { + * greeter:Greeter; + * + * constructor(greeter:Greeter) { + * this.greeter = greeter; + * } + * } + * ``` + */ + injectables?: List; + + /** + * Specifies a set of lifecycle hostListeners in which the directive participates. + * + * See {@link onChange}, {@link onDestroy}, {@link onAllChangesDone} for details. + */ + lifecycle?: List; + + /** + * Defines the used change detection strategy. + * + * When a component is instantiated, Angular creates a change detector, which is responsible for propagating + * the component's bindings. + * + * The `changeDetection` property defines, whether the change detection will be checked every time or only when the component + * tells it to do so. + */ + changeDetection?: string; +} + +interface _ViewArg { + /** + * Specifies a template URL for an angular component. + * + * NOTE: either `templateUrl` or `template` should be used, but not both. + */ + templateUrl?: string; + + /** + * Specifies an inline template for an angular component. + * + * NOTE: either `templateUrl` or `template` should be used, but not both. + */ + template?: string; + + /** + * Specifies a list of directives that can be used within a template. + * + * Directives must be listed explicitly to provide proper component encapsulation. + */ + directives?: List; +} + +declare module "angular2/angular2" { + /** + * Bootstrapping for Angular applications. + * + * You instantiate an Angular application by explicitly specifying a component to use as the root component for your + * application via the `bootstrap()` method. + * + * ## Simple Example + * + * Assuming this `index.html`: + * + * ```html + * + * + * + * loading... + * + * + * ``` + * + * An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike Angular 1, Angular 2 + * does not compile/process bindings in `index.html`. This is mainly for security reasons, as well as architectural + * changes in Angular 2. This means that `index.html` can safely be processed using server-side technologies such as + * bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2 component double-curly + * `{{ syntax }}`. + * + * We can use this script code: + * + * ``` + * @Component({ + * selector: 'my-app' + * }) + * @View({ + * template: 'Hello {{ name }}!' + * }) + * class MyApp { + * name:string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * + * main() { + * return bootstrap(MyApp); + * } + * ``` + * + * When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument, Angular performs the + * following tasks: + * + * 1. It uses the component's `selector` property to locate the DOM element which needs to be upgraded into + * the angular component. + * 2. It creates a new child injector (from the platform injector) and configures the injector with the component's + * `injectables`. Optionally, you can also override the injector configuration for an app by invoking + * `bootstrap` with the `componentInjectableBindings` argument. + * 3. It creates a new `Zone` and connects it to the angular application's change detection domain instance. + * 4. It creates a shadow DOM on the selected component's host element and loads the template into it. + * 5. It instantiates the specified component. + * 6. Finally, Angular performs change detection to apply the initial data bindings for the application. + * + * + * ## Instantiating Multiple Applications on a Single Page + * + * There are two ways to do this. + * + * + * ### Isolated Applications + * + * Angular creates a new application each time that the `bootstrap()` method is invoked. When multiple applications + * are created for a page, Angular treats each application as independent within an isolated change detection and + * `Zone` domain. If you need to share data between applications, use the strategy described in the next + * section, "Applications That Share Change Detection." + * + * + * ### Applications That Share Change Detection + * + * If you need to bootstrap multiple applications that share common data, the applications must share a common + * change detection and zone. To do that, create a meta-component that lists the application components in its template. + * By only invoking the `bootstrap()` method once, with the meta-component as its argument, you ensure that only a + * single change detection zone is created and therefore data can be shared across the applications. + * + * + * ## Platform Injector + * + * When working within a browser window, there are many singleton resources: cookies, title, location, and others. + * Angular services that represent these resources must likewise be shared across all Angular applications that + * occupy the same browser window. For this reason, Angular creates exactly one global platform injector which stores + * all shared services, and each angular application injector has the platform injector as its parent. + * + * Each application has its own private injector as well. When there are multiple applications on a page, Angular treats + * each application injector's services as private to that application. + * + * + * # API + * - `appComponentType`: The root component which should act as the application. This is a reference to a `Type` + * which is annotated with `@Component(...)`. + * - `componentInjectableBindings`: An additional set of bindings that can be added to `injectables` for the + * {@link Component} to override default injection behavior. + * - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter for unhandled exceptions. + * + * Returns a `Promise` with the application`s private {@link Injector}. + * + */ + function bootstrap(appComponentType: any): void; + + /** + * Declare reusable UI building blocks for an application. + * + * Each Angular component requires a single `@Component` and at least one `@View` annotation. The `@Component` + * annotation specifies when a component is instantiated, and which properties and hostListeners it binds to. + * + * When a component is instantiated, Angular + * - creates a shadow DOM for the component. + * - loads the selected template into the shadow DOM. + * - creates a child {@link Injector} which is configured with the `injectables` for the {@link Component}. + * + * All template expressions and statements are then evaluated against the component instance. + * + * For details on the `@View` annotation, see {@link View}. + * + * ## Example + * + * ``` + * @Component({ + * selector: 'greet' + * }) + * @View({ + * template: 'Hello {{name}}!' + * }) + * class Greet { + * name: string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * ``` + * + * + * Dynamically loading a component at runtime: + * + * Regular Angular components are statically resolved. Dynamic components allows to resolve a component at runtime + * instead by providing a placeholder into which a regular Angular component can be dynamically loaded. Once loaded, + * the dynamically-loaded component becomes permanent and cannot be changed. + * Dynamic components are declared just like components, but without a `@View` annotation. + * + * + * ## Example + * + * Here we have `DynamicComp` which acts as the placeholder for `HelloCmp`. At runtime, the dynamic component + * `DynamicComp` requests loading of the `HelloCmp` component. + * + * There is nothing special about `HelloCmp`, which is a regular Angular component. It can also be used in other static + * locations. + * + * ``` + * @Component({ + * selector: 'dynamic-comp' + * }) + * class DynamicComp { + * helloCmp:HelloCmp; + * constructor(loader:DynamicComponentLoader, location:ElementRef) { + * loader.load(HelloCmp, location).then((helloCmp) => { + * this.helloCmp = helloCmp; + * }); + * } + * } + * + * @Component({ + * selector: 'hello-cmp' + * }) + * @View({ + * template: "{{greeting}}" + * }) + * class HelloCmp { + * greeting:string; + * constructor() { + * this.greeting = "hello"; + * } + * } + * ``` + * + */ + function Component(arg: _ComponentArg): (target: any) => any; + + /** + * Declares the available HTML templates for an application. + * + * Each angular component requires a single `@Component` and at least one `@View` annotation. The @View + * annotation specifies the HTML template to use, and lists the directives that are active within the template. + * + * When a component is instantiated, the template is loaded into the component's shadow root, and the + * expressions and statements in the template are evaluated against the component. + * + * For details on the `@Component` annotation, see {@link Component}. + * + * ## Example + * + * ``` + * @Component({ + * selector: 'greet' + * }) + * @View({ + * template: 'Hello {{name}}!', + * directives: [GreetUser, Bold] + * }) + * class Greet { + * name: string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * ``` + * + */ + function View(arg: _ViewArg): (target: any) => any; + + /** + * The `For` directive instantiates a template once per item from an iterable. The context for each + * instantiated template inherits from the outer context with the given loop variable set to the + * current item from the iterable. + * + * It is possible to alias the `index` to a local variable that will be set to the current loop + * iteration in the template context. + * + * When the contents of the iterator changes, `For` makes the corresponding changes to the DOM: + * + * * When an item is added, a new instance of the template is added to the DOM. + * * When an item is removed, its template instance is removed from the DOM. + * * When items are reordered, their respective templates are reordered in the DOM. + * + * # Example + * + * ``` + *
    + *
  • + * Error {{i}} of {{errors.length}}: {{error.message}} + *
  • + *
+ * ``` + * + * # Syntax + * + * - `
  • ...
  • ` + * - `
  • ...
  • ` + * - `` + * + */ + function For(): void; + + /** + * Removes or recreates a portion of the DOM tree based on an {expression}. + * + * If the expression assigned to `if` evaluates to a false value then the element is removed from the + * DOM, otherwise a clone of the element is reinserted into the DOM. + * + * # Example: + * + * ``` + *
    + * + * {{errorCount}} errors detected + *
    + * ``` + * + * # Syntax + * + * - `
    ...
    ` + * - `
    ...
    ` + * - `` + * + */ + function If(): void; + + /** + * The `NonBindable` 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. + * + * Example: + * + * ``` + *
    Normal: {{1 + 2}}
    // output "Normal: 3" + *
    Ignored: {{1 + 2}}
    // output "Ignored: {{1 + 2}}" + * ``` + * + */ + function NonBindable(): void; + + /** + * The `Switch` directive is used to conditionally swap DOM structure on your template based on a + * scope expression. + * Elements within `Switch` but without `SwitchWhen` or `SwitchDefault` directives will be + * preserved at the location as specified in the template. + * + * `Switch` simply chooses nested elements and makes them 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 **`[switch]="..."` attribute**), + * define any inner elements inside of the directive and place a `[switch-when]` attribute per + * element. + * The when attribute is used to inform Switch which element to display when the expression is + * evaluated. If a matching expression is not found via a when attribute then an element with the + * default attribute is displayed. + * + * # Example: + * + * ``` + * + * + * + * + * + * ``` + * + */ + function Switch(): void; +} + +declare module "angular2/di" { + /** + * Provides an API for imperatively constructing {@link Binding}s. + * + * This is only relevant for JavaScript. See {@link BindingBuilder}. + * + * ## Example + * + * ```javascript + * bind(MyInterface).toClass(MyClass) + * + * ``` + * + */ + function bind(token: any): any; +} diff --git a/angularfire/angularfire-tests.ts b/angularfire/angularfire-tests.ts index 7d39e4181..d636c88e6 100644 --- a/angularfire/angularfire-tests.ts +++ b/angularfire/angularfire-tests.ts @@ -62,8 +62,8 @@ myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$Fi obj.$save(); }); - // $inst() - if (obj.$inst() !== sync) throw "error"; + // $ref() + if (obj.$ref() !== sync) throw "error"; // $bindTo() obj.$bindTo($scope, "data").then(function () { @@ -81,8 +81,8 @@ myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$Fi // $destroy() obj.$destroy(); - // $extendFactory() - var NewFactory = $FirebaseObject.$extendFactory({ + // $extend() + var NewFactory = $FirebaseObject.$extend({ getMyFavoriteColor: function () { return this.favoriteColor + ", no green!"; // obscure Monty Python reference } @@ -94,8 +94,8 @@ myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$Fi { var list = sync.$asArray(); - // $inst() - if (list.$inst() !== sync) throw "error"; + // $ref() + if (list.$ref() !== sync) throw "error"; // $add() list.$add({ foo: "foo value" }); @@ -145,8 +145,8 @@ myapp.controller("MyController", ["$scope", "$firebase", '$FirebaseObject', '$Fi // $destroy() list.$destroy(); - // $extendFactory() - var ArrayWithSum = $FirebaseArray.$extendFactory({ + // $extend() + var ArrayWithSum = $FirebaseArray.$extend({ sum: function () { var total = 0; angular.forEach(this.$list, function (rec) { @@ -167,30 +167,43 @@ interface AngularFireAuthScope extends ng.IScope { loginObj: AngularFireAuth; } -myapp.controller("MyAuthController", ["$scope", "$firebaseSimpleLogin", - function($scope: AngularFireAuthScope, $firebaseSimpleLogin: AngularFireAuthService) { +myapp.controller("MyAuthController", ["$scope", "$firebaseAuth", + function($scope: AngularFireAuthScope, $firebaseAuth: AngularFireAuthService) { var dataRef = new Firebase(url); - $scope.loginObj = $firebaseSimpleLogin(dataRef); - $scope.loginObj.$getCurrentUser().then(_ => { - }); - var email = 'my@email.com'; - var password = 'mypassword'; - $scope.loginObj.$login('password', { - email: email, - password: password - }).then(function(user) { - console.log('Logged in as: ', user.uid); - }, function(error) { - console.error('Login failed: ', error); - }); - $scope.loginObj.$logout(); - $scope.loginObj.$createUser(email, password).then(_ => { - }); - $scope.loginObj.$changePassword(email, password, password).then(_ => { - }); - $scope.loginObj.$removeUser(email, password).then(_ => { - }); - $scope.loginObj.$sendPasswordResetEmail(email).then(_ => { - }); + $scope.loginObj = $firebaseAuth(dataRef); + $scope.loginObj.$getAuth(); + var credentials = { + email: 'my@email.com', + password: 'mypassword' + }; + var resetPasswordCredentials = { + email: 'my@email.com' + }; + var changePasswordCredentials = { + email: 'my@email.com', + oldPassword: 'mypassword', + newPassword: 'mypassword' + }; + var changeUserCredentials = { + oldEmail: 'my@email.com', + newEmail: 'my@email.com', + password: 'mypassword' + }; + $scope.loginObj.$authWithCustomToken("token").then(_ => {}); + $scope.loginObj.$authAnonymously().then(_ => {}); + $scope.loginObj.$authWithPassword(credentials).then(_ => {}); + $scope.loginObj.$authWithOAuthPopup("github").then(_ => {}); + $scope.loginObj.$authWithOAuthRedirect("google").then(_ => {}); + $scope.loginObj.$authWithOAuthToken("twitter", "token").then(_ => {}); + $scope.loginObj.$getAuth(); + $scope.loginObj.$onAuth(() => {}); + $scope.loginObj.$unauth(); + $scope.loginObj.$waitForAuth(); + $scope.loginObj.$requireAuth(); + $scope.loginObj.$createUser(credentials).then(_ => {}); + $scope.loginObj.$removeUser(credentials).then(_ => {}); + $scope.loginObj.$changeEmail(changeUserCredentials).then(_ => {}); + $scope.loginObj.$changePassword(changePasswordCredentials).then(_ => {}); + $scope.loginObj.$resetPassword(resetPasswordCredentials).then(_ => {}); } -]); \ No newline at end of file +]); diff --git a/angularfire/angularfire.d.ts b/angularfire/angularfire.d.ts index e4129e4ba..46d95750c 100644 --- a/angularfire/angularfire.d.ts +++ b/angularfire/angularfire.d.ts @@ -28,17 +28,19 @@ interface AngularFireObject extends AngularFireSimpleObject { $id: string; $priority: number; $value: any; + $remove(): ng.IPromise; $save(): ng.IPromise; $loaded(resolve?: (x: AngularFireObject) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise; $loaded(resolve?: (x: AngularFireObject) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise; $loaded(resolve?: (x: AngularFireObject) => void, reject?: (err: any) => any): ng.IPromise; - $inst(): AngularFire; + $ref(): AngularFire; $bindTo(scope: ng.IScope, varName: string): ng.IPromise; $watch(callback: Function, context?: any): Function; $destroy(): void; } interface AngularFireObjectService { - $extendFactory(ChildClass: Object, methods?: Object): Object; + (firebase: Firebase): AngularFireObject; + $extend(ChildClass: Object, methods?: Object): Object; } interface AngularFireArray extends Array { @@ -51,12 +53,13 @@ interface AngularFireArray extends Array { $loaded(resolve?: (x: AngularFireArray) => ng.IHttpPromise<{}>, reject?: (err: any) => any): ng.IPromise; $loaded(resolve?: (x: AngularFireArray) => ng.IPromise<{}>, reject?: (err: any) => any): ng.IPromise; $loaded(resolve?: (x: AngularFireArray) => void, reject?: (err: any) => any): ng.IPromise; - $inst(): AngularFire; + $ref(): AngularFire; $watch(cb: (event: string, key: string, prevChild: string) => void, context?: any): Function; $destroy(): void; } interface AngularFireArrayService { - $extendFactory(ChildClass: Object, methods?: Object): Object; + (firebase: Firebase): AngularFireArray; + $extend(ChildClass: Object, methods?: Object): Object; } interface AngularFireSimpleObject { @@ -72,11 +75,20 @@ interface AngularFireAuthService { } interface AngularFireAuth { - $getCurrentUser(): ng.IPromise; - $login(provider: string, options?: Object): ng.IPromise; - $logout(): void; - $createUser(email: string, password: string): ng.IPromise; - $changePassword(email: string, oldPassword: string, newPassword: string): ng.IPromise; - $removeUser(email: string, password: string): ng.IPromise; - $sendPasswordResetEmail(email: string): ng.IPromise; + $authWithCustomToken(authToken: string, options?: Object): ng.IPromise; + $authAnonymously(options?: Object): ng.IPromise; + $authWithPassword(credentials: FirebaseCredentials, options?: Object): ng.IPromise; + $authWithOAuthPopup(provider: string, options?: Object): ng.IPromise; + $authWithOAuthRedirect(provider: string, options?: Object): ng.IPromise; + $authWithOAuthToken(provider: string, credentials: Object|string, options?: Object): ng.IPromise; + $getAuth(): FirebaseAuthData; + $onAuth(callback: Function, context?: any): Function; + $unauth(): void; + $waitForAuth(): ng.IPromise; + $requireAuth(): ng.IPromise; + $createUser(credentials: FirebaseCredentials): ng.IPromise; + $removeUser(credentials: FirebaseCredentials): ng.IPromise; + $changeEmail(credentials: FirebaseChangeEmailCredentials): ng.IPromise; + $changePassword(credentials: FirebaseChangePasswordCredentials): ng.IPromise; + $resetPassword(credentials: FirebaseResetPasswordCredentials): ng.IPromise; } diff --git a/angularjs-toaster/angularjs-toaster-tests.ts b/angularjs-toaster/angularjs-toaster-tests.ts new file mode 100644 index 000000000..ffff32159 --- /dev/null +++ b/angularjs-toaster/angularjs-toaster-tests.ts @@ -0,0 +1,42 @@ +/// +class NgToasterTestController { + constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public toaster: ngtoaster.IToasterService) { + this.bar = 'Hi'; + } + bar: string; + + pop(): void { + this.toaster.success({ title: "title", body: "text1" }); + this.toaster.error("title", "text2"); + this.toaster.pop({ type: 'wait', title: "title", body: "text" }); + this.toaster.pop('success', "title", '
    • Render html
    ', 5000, 'trustedHtml'); + this.toaster.pop('error', "title", '
    • Render html
    ', null, 'trustedHtml'); + this.toaster.pop('wait', "title", null, null, 'template'); + this.toaster.pop('warning', "title", "myTemplate.html", null, 'template'); + this.toaster.pop('note', "title", "text"); + this.toaster.pop('success', "title", 'Its address is https://google.com.', 5000, 'trustedHtml', (toaster: ngtoaster.IToast): boolean => { + var match = toaster.body.match(/http[s]?:\/\/[^\s]+/); + if (match) { + this.$window.open(match[0]); + } + return true; + }); + this.toaster.pop('warning', "Hi ", "{template: 'myTemplateWithData.html', data: 'MyData'}", 15000, 'templateWithData'); + } + + goToLink(toaster: ngtoaster.IToast): boolean { + var match = toaster.body.match(/http[s]?:\/\/[^\s]+/); + if (match) { + this.$window.open(match[0]); + } + return true; + } + + clear(): void { + this.toaster.clear(); + } +} + +angular + .module('main', ['ngAnimate', 'toaster']) + .controller('myController', NgToasterTestController); \ No newline at end of file diff --git a/angularjs-toaster/angularjs-toaster.d.ts b/angularjs-toaster/angularjs-toaster.d.ts new file mode 100644 index 000000000..398704514 --- /dev/null +++ b/angularjs-toaster/angularjs-toaster.d.ts @@ -0,0 +1,109 @@ +// Type definitions for angularjs-toaster v0.4.13 +// Project: https://github.com/jirikavi/AngularJS-Toaster +// Definitions by: Ben Tesser +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ngtoaster { + interface IToasterService { + pop(params:IPopParams): void + /** + * @param {string} type Type of toaster -- 'error', 'info', 'wait', 'success', and 'warning' + */ + pop(type?:string, title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, + toasterId?:number, showCloseButton?:boolean): void + error(params: IPopParams): void + error(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, + toasterId?:number): void + into(params: IPopParams): void + info(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, + toasterId?:number): void + wait(params: IPopParams): void + wait(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, + toasterId?:number): void + success(params: IPopParams): void + success(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, + toasterId?:number): void + warning(params: IPopParams): void + warning(title?:string, body?:string, timeout?:number, bodyOutputType?:string, clickHandler?:EventListener, + toasterId?:number): void + clear(): void + toast:IToast; + } + + interface IToasterEventRegistry { + setup(): void + subscribeToNewToastEvent(onNewToast:IToastEventListener): void + subscribeToClearToastsEvent(onClearToasts:IToastEventListener): void + unsubscribeToNewToastEvent(onNewToast:IToastEventListener): void + unsubscribeToClearToastsEvent(onClearToasts:IToastEventListener): void + } + + interface IPopParams extends IToast{ + toasterId?: number; + } + + interface IToastEventListener { + (event:Event, toasterId: number): void; + } + + interface IToast { + /** + * Acceptable types are: + * 'error', 'info', 'wait', 'success', and 'warning' + */ + type?: string; + title?: string; + body?: string; + timeout?: number; + bodyOutputType?: string; + clickHandler?: EventListener; + showCloseButton?: boolean; + } + + interface IToasterConfig { + /** + * limits max number of toasts + */ + limit?: number; + 'tap-to-dismiss'?: boolean; + 'close-button'?: boolean; + 'newest-on-top'?: boolean; + 'time-out'?: number; + 'icon-classes'?: IIconClasses; + /** + * Options include: + * '', 'trustedHtml', 'template', 'templateWithData' + */ + 'body-output-type'?: string; + 'body-template'?: string; + 'icon-class'?: string; + /** + * Options include: + * 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center', + * 'toast-top-left', 'toast-top-center', 'toast-top-rigt', + * 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-rigt', + */ + 'position-class'?: string; + 'title-class'?: string; + 'message-class'?: string; + 'prevent-duplicates'?: boolean; + /** + * stop timeout on mouseover and restart timer on mouseout + */ + 'mouseover-timer-stop'?: boolean; + } + + interface IIconClasses { + error: string; + info: string; + wait: string; + success: string; + warning: string; + } +} + +declare module "ngtoaster" { + export = ngtoaster +} diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index e78b85c3e..3ecc95b5b 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -19,7 +19,7 @@ declare module angular.animate { // AnimateService // see http://docs.angularjs.org/api/ngAnimate/service/$animate /////////////////////////////////////////////////////////////////////////// - interface IAnimateService extends ng.IAnimateService { + interface IAnimateService extends angular.IAnimateService { /** * Globally enables / disables animations. * @@ -39,7 +39,7 @@ declare module angular.animate { * @param options an optional collection of styles that will be picked up by the CSS transition/animation * @returns the animation callback promise */ - animate(element: JQuery, from: any, to: any, className?: string, options?: IAnimationOptions): ng.IPromise; + animate(element: JQuery, from: any, to: any, className?: string, options?: IAnimationOptions): IPromise; /** * Appends the element to the parentElement element that resides in the document and then runs the enter animation. @@ -50,7 +50,7 @@ declare module angular.animate { * @param options an optional collection of styles that will be picked up by the CSS transition/animation * @returns the animation callback promise */ - enter(element: JQuery, parentElement: JQuery, afterElement?: JQuery, options?: IAnimationOptions): ng.IPromise; + enter(element: JQuery, parentElement: JQuery, afterElement?: JQuery, options?: IAnimationOptions): IPromise; /** * Runs the leave animation operation and, upon completion, removes the element from the DOM. @@ -59,7 +59,7 @@ declare module angular.animate { * @param options an optional collection of styles that will be picked up by the CSS transition/animation * @returns the animation callback promise */ - leave(element: JQuery, options?: IAnimationOptions): ng.IPromise; + leave(element: JQuery, options?: IAnimationOptions): IPromise; /** * Fires the move DOM operation. Just before the animation starts, the animate service will either append @@ -71,7 +71,7 @@ declare module angular.animate { * @param afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation * @returns the animation callback promise */ - move(element: JQuery, parentElement: JQuery, afterElement?: JQuery): ng.IPromise; + move(element: JQuery, parentElement: JQuery, afterElement?: JQuery): IPromise; /** * Triggers a custom animation event based off the className variable and then attaches the className @@ -82,7 +82,7 @@ declare module angular.animate { * @param options an optional collection of styles that will be picked up by the CSS transition/animation * @returns the animation callback promise */ - addClass(element: JQuery, className: string, options?: IAnimationOptions): ng.IPromise; + addClass(element: JQuery, className: string, options?: IAnimationOptions): IPromise; /** * Triggers a custom animation event based off the className variable and then removes the CSS class @@ -93,7 +93,7 @@ declare module angular.animate { * @param options an optional collection of styles that will be picked up by the CSS transition/animation * @returns the animation callback promise */ - removeClass(element: JQuery, className: string, options?: IAnimationOptions): ng.IPromise; + removeClass(element: JQuery, className: string, options?: IAnimationOptions): IPromise; /** * Adds and/or removes the given CSS classes to and from the element. Once complete, the done() callback @@ -105,12 +105,12 @@ declare module angular.animate { * @param options an optional collection of styles that will be picked up by the CSS transition/animation * @returns the animation callback promise */ - setClass(element: JQuery, add: string, remove: string, options?: IAnimationOptions): ng.IPromise; + setClass(element: JQuery, add: string, remove: string, options?: IAnimationOptions): IPromise; /** * Cancels the provided animation. */ - cancel(animationPromise: ng.IPromise): void; + cancel(animationPromise: IPromise): void; } /////////////////////////////////////////////////////////////////////////// @@ -124,7 +124,7 @@ declare module angular.animate { * @param name The name of the animation. * @param factory The factory function that will be executed to return the animation object. */ - register(name: string, factory: () => ng.IAnimateCallbackObject): void; + register(name: string, factory: () => IAnimateCallbackObject): void; /** * Gets and/or sets the CSS class expression that is checked when performing an animation. diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 1e62aa5f2..92784af38 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -539,9 +539,29 @@ declare module angular { $applyAsync(exp: string): any; $applyAsync(exp: (scope: IScope) => any): any; + /** + * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to broadcast. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ $broadcast(name: string, ...args: any[]): IAngularEvent; $destroy(): void; $digest(): void; + /** + * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $emit was called. All 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 listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to emit. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ $emit(name: string, ...args: any[]): IAngularEvent; $eval(): any; @@ -1012,37 +1032,98 @@ declare module angular { disableAutoScrolling(): void; } - /////////////////////////////////////////////////////////////////////////// - // CacheFactoryService - // see http://docs.angularjs.org/api/ng.$cacheFactory - /////////////////////////////////////////////////////////////////////////// + /** + * $cacheFactory - service in module ng + * + * Factory that constructs Cache objects and gives access to them. + * + * see https://docs.angularjs.org/api/ng/service/$cacheFactory + */ interface ICacheFactoryService { - // Lets not foce the optionsMap to have the capacity member. Even though - // it's the ONLY option considered by the implementation today, a consumer - // might find it useful to associate some other options to the cache object. - //(cacheId: string, optionsMap?: { capacity: number; }): CacheObject; - (cacheId: string, optionsMap?: { capacity: number; }): ICacheObject; + /** + * Factory that constructs Cache objects and gives access to them. + * + * @param cacheId Name or id of the newly created cache. + * @param optionsMap Options object that specifies the cache behavior. Properties: + * + * capacity — turns the cache into LRU cache. + */ + (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; - // Methods bellow are not documented + /** + * Get information about all the caches that have been created. + * @returns key-value map of cacheId to the result of calling cache#info + */ info(): any; + + /** + * Get access to a cache object by the cacheId used when it was created. + * + * @param cacheId Name or id of a cache to access. + */ get(cacheId: string): ICacheObject; } + /** + * $cacheFactory.Cache - type in module ng + * + * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. + * + * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache + */ interface ICacheObject { + /** + * Retrieve information regarding a particular Cache. + */ info(): { + /** + * the id of the cache instance + */ id: string; + + /** + * the number of entries kept in the cache instance + */ size: number; - // Not garanteed to have, since it's a non-mandatory option - //capacity: number; + //...: any additional properties from the options object when creating the cache. }; + + /** + * Inserts a named entry into the 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 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. + */ put(key: string, value?: T): T; + + /** + * Retrieves named data stored in the Cache object. + * + * @param key the key of the data to be retrieved + */ get(key: string): any; + + /** + * Removes an entry from the Cache object. + * + * @param key the key of the entry to be removed + */ remove(key: string): void; + + /** + * Clears the cache object of any entries. + */ removeAll(): void; + + /** + * Destroys the Cache object entirely, removing it from the $cacheFactory set. + */ destroy(): void; } - + /////////////////////////////////////////////////////////////////////////// // CompileService // see http://docs.angularjs.org/api/ng.$compile diff --git a/applicationinsights/applicationinsights-tests.ts b/applicationinsights/applicationinsights-tests.ts new file mode 100644 index 000000000..871a029e8 --- /dev/null +++ b/applicationinsights/applicationinsights-tests.ts @@ -0,0 +1,25 @@ +/// +import appInsights = require("applicationinsights"); + +// basic use +appInsights.setup("").start(); + +// basic use with auto-collection configuration +appInsights.setup("") + .setAutoCollectRequests(false) + .setAutoCollectPerformance(false) + .setAutoCollectExceptions(false) + // no telemetry will be sent until .start() is called + // this prevents any of the auto-collectors from initializing + .enableVerboseLogging() + .start(); + +appInsights.client.trackEvent("custom event", {customProperty: "custom property value"}); +appInsights.client.trackException(new Error("handled exceptions can be logged with this method")); +appInsights.client.trackMetric("custom metric", 3); +appInsights.client.trackTrace("trace message"); + +// assign common properties to all telemetry +appInsights.client.commonProperties = { + environment: "dev" +}; diff --git a/applicationinsights/applicationinsights.d.ts b/applicationinsights/applicationinsights.d.ts new file mode 100644 index 000000000..6b80adc2a --- /dev/null +++ b/applicationinsights/applicationinsights.d.ts @@ -0,0 +1,429 @@ +// Type definitions for Application Insights v0.15.1 +// Project: https://github.com/Microsoft/ApplicationInsights-node.js +// Definitions by: Scott Southwood +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface AutoCollectConsole { + enable(isEnabled: boolean): void; + isInitialized(): boolean; +} + +interface AutoCollectExceptions { + isInitialized(): boolean; + enable(isEnabled:boolean): void; +} + +interface AutoCollectPerformance { + enable(isEnabled: boolean): void; + isInitialized(): boolean; +} + +interface AutoCollectRequests { + enable(isEnabled: boolean): void; + isInitialized(): boolean; +} + + +declare module ContractsModule { + enum DataPointType { + Measurement = 0, + Aggregation = 1, + } + enum DependencyKind { + SQL = 0, + Http = 1, + Other = 2, + } + enum DependencySourceType { + Undefined = 0, + Aic = 1, + Apmc = 2, + } + enum SessionState { + Start = 0, + End = 1, + } + enum SeverityLevel { + Verbose = 0, + Information = 1, + Warning = 2, + Error = 3, + Critical = 4, + } + interface ContextTagKeys { + applicationVersion: string; + applicationBuild: string; + deviceId: string; + deviceIp: string; + deviceLanguage: string; + deviceLocale: string; + deviceModel: string; + deviceNetwork: string; + deviceOEMName: string; + deviceOS: string; + deviceOSVersion: string; + deviceRoleInstance: string; + deviceRoleName: string; + deviceScreenResolution: string; + deviceType: string; + deviceMachineName: string; + locationIp: string; + operationId: string; + operationName: string; + operationParentId: string; + operationRootId: string; + operationSyntheticSource: string; + operationIsSynthetic: string; + sessionId: string; + sessionIsFirst: string; + sessionIsNew: string; + userAccountAcquisitionDate: string; + userAccountId: string; + userAgent: string; + userId: string; + userStoreRegion: string; + sampleRate: string; + internalSdkVersion: string; + internalAgentVersion: string; + } + interface Domain { + ver: number; + properties: any; + } + interface Data { + baseType: string; + baseData: TDomain; + } + interface Envelope { + ver: number; + name: string; + time: string; + sampleRate: number; + seq: string; + iKey: string; + flags: number; + deviceId: string; + os: string; + osVer: string; + appId: string; + appVer: string; + userId: string; + tags: { + [key: string]: string; + }; + data: Data; + } + interface EventData extends ContractsModule.Domain { + ver: number; + name: string; + properties: any; + measurements: any; + } + interface MessageData extends ContractsModule.Domain { + ver: number; + message: string; + severityLevel: ContractsModule.SeverityLevel; + properties: any; + } + interface ExceptionData extends ContractsModule.Domain { + ver: number; + handledAt: string; + exceptions: ExceptionDetails[]; + severityLevel: ContractsModule.SeverityLevel; + problemId: string; + crashThreadId: number; + properties: any; + measurements: any; + } + interface StackFrame { + level: number; + method: string; + assembly: string; + fileName: string; + line: number; + } + interface ExceptionDetails { + id: number; + outerId: number; + typeName: string; + message: string; + hasFullStack: boolean; + stack: string; + parsedStack: StackFrame[]; + } + interface DataPoint { + name: string; + kind: ContractsModule.DataPointType; + value: number; + count: number; + min: number; + max: number; + stdDev: number; + } + interface MetricData extends ContractsModule.Domain { + ver: number; + metrics: DataPoint[]; + properties: any; + } + interface PageViewData extends ContractsModule.EventData { + ver: number; + url: string; + name: string; + duration: string; + properties: any; + measurements: any; + } + interface PageViewPerfData extends ContractsModule.PageViewData { + ver: number; + url: string; + perfTotal: string; + name: string; + duration: string; + networkConnect: string; + sentRequest: string; + receivedResponse: string; + domProcessing: string; + properties: any; + measurements: any; + } + interface RemoteDependencyData extends ContractsModule.Domain { + ver: number; + name: string; + kind: ContractsModule.DataPointType; + value: number; + count: number; + min: number; + max: number; + stdDev: number; + dependencyKind: ContractsModule.DependencyKind; + success: boolean; + async: boolean; + dependencySource: ContractsModule.DependencySourceType; + commandName: string; + dependencyTypeName: string; + properties: any; + } + interface AjaxCallData extends ContractsModule.PageViewData { + ver: number; + url: string; + ajaxUrl: string; + name: string; + duration: string; + requestSize: number; + responseSize: number; + timeToFirstByte: string; + timeToLastByte: string; + callbackDuration: string; + responseCode: string; + success: boolean; + properties: any; + measurements: any; + } + interface RequestData extends ContractsModule.Domain { + ver: number; + id: string; + name: string; + startTime: string; + duration: string; + responseCode: string; + success: boolean; + httpMethod: string; + url: string; + properties: any; + measurements: any; + } + interface SessionStateData extends ContractsModule.Domain { + ver: number; + state: ContractsModule.SessionState; + } + interface PerformanceCounterData extends ContractsModule.Domain { + ver: number; + categoryName: string; + counterName: string; + instanceName: string; + kind: DataPointType; + count: number; + min: number; + max: number; + stdDev: number; + value: number; + properties: any; + } +} + + +interface Channel { + constructor(isDisabled: () => boolean, getBatchSize: () => number, getBatchIntervalMs: () => number, sender: Sender): Channel; + /** + * Add a telemetry item to the send buffer + */ + send(envelope: ContractsModule.Envelope): void; + handleCrash(envelope: ContractsModule.Envelope): void; + /** + * Immediately send buffered data + */ + triggerSend(isNodeCrashing?: boolean): void; +} + +interface Client { + config: Config; + context: Context; + commonProperties: { + [key: string]: string; + }; + channel: Channel; + /** + * Constructs a new client of the client + * @param iKey the instrumentation key to use (read from environment variable if not specified) + */ + constructor(iKey?: string): Client; + /** + * Log a user action or other occurrence. + * @param name A string to identify this event in the portal. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + trackEvent(name: string, properties?: { + [key: string]: string; + }, measurements?: { + [key: string]: number; + }): void; + /** + * Log a trace message + * @param message A string to identify this event in the portal. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + */ + trackTrace(message: string, severityLevel?: ContractsModule.SeverityLevel, properties?: { + [key: string]: string; + }): void; + /** + * Log an exception you have caught. + * @param exception An Error from a catch clause, or the string error message. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + trackException(exception: Error, properties?: { + [key: string]: string; + }): void; + /** + * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. + * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the + * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. + * @param name A string that identifies the metric. + * @param value The value of the metric + */ + trackMetric(name: string, value: number): void; + trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: { + [key: string]: string; + }): void; + /** + * Immediately send all queued telemetry. + */ + sendPendingData(): void; + getEnvelope(data: ContractsModule.Data, tagOverrides?: { + [key: string]: string; + }): ContractsModule.Envelope; + /** + * Generic track method for all telemetry types + * @param data the telemetry to send + * @param tagOverrides the context tags to use for this telemetry which overwrite default context values + */ + track(data: ContractsModule.Data, tagOverrides?: { + [key: string]: string; + }): void; +} + +interface Config { + instrumentationKey: string; + sessionRenewalMs: number; + sessionExpirationMs: number; + endpointUrl: string; + maxBatchSize: number; + maxBatchIntervalMs: number; + disableAppInsights: boolean; + constructor(instrumentationKey?: string): Config; +} + +interface Context { + keys: ContractsModule.ContextTagKeys; + tags: { + [key: string]: string; + }; + constructor(packageJsonPath?: string): Context; +} + +interface Sender { + constructor(getUrl: () => string, onSuccess?: (response: string) => void, onError?: (error: Error) => void): Sender; + send(payload: any/* Buffer */): void; + saveOnCrash(payload: string): void; + /** + * enable caching events locally on error + */ + enableCacheOnError(): void; + /** + * disable caching events locally on error + */ + disableCacheOnError(): void; +} + +/** + * The singleton meta interface for the default client of the client. This interface is used to setup/start and configure + * the auto-collection behavior of the application insights module. + */ +declare class ApplicationInsights { + static client: Client; + private static _isConsole; + private static _isExceptions; + private static _isPerformance; + private static _isRequests; + private static _console; + private static _exceptions; + private static _performance; + private static _requests; + private static _isStarted; + /** + * Initializes the default client of the client and sets the default configuration + * @param instrumentationKey the instrumentation key to use. Optional, if this is not specified, the value will be + * read from the environment variable APPINSIGHTS_INSTRUMENTATION_KEY + * @returns {ApplicationInsights} this interface + */ + static setup(instrumentationKey?: string): typeof ApplicationInsights; + /** + * Starts automatic collection of telemetry. Prior to calling start no telemetry will be collected + * @returns {ApplicationInsights} this interface + */ + static start(): typeof ApplicationInsights; + /** + * Sets the state of console tracking (enabled by default) + * @param value if true console activity will be sent to Application Insights + * @returns {ApplicationInsights} this interface + */ + static setAutoCollectConsole(value: boolean): typeof ApplicationInsights; + /** + * Sets the state of exception tracking (enabled by default) + * @param value if true uncaught exceptions will be sent to Application Insights + * @returns {ApplicationInsights} this interface + */ + static setAutoCollectExceptions(value: boolean): typeof ApplicationInsights; + /** + * Sets the state of performance tracking (enabled by default) + * @param value if true performance counters will be collected every second and sent to Application Insights + * @returns {ApplicationInsights} this interface + */ + static setAutoCollectPerformance(value: boolean): typeof ApplicationInsights; + /** + * Sets the state of request tracking (enabled by default) + * @param value if true requests will be sent to Application Insights + * @returns {ApplicationInsights} this interface + */ + static setAutoCollectRequests(value: boolean): typeof ApplicationInsights; + /** + * Enables verbose debug logging + * @returns {ApplicationInsights} this interface + */ + static enableVerboseLogging(): typeof ApplicationInsights; +} + +declare module "applicationinsights" { + export = ApplicationInsights; +} \ No newline at end of file diff --git a/blocks/blocks-tests.ts b/blocks/blocks-tests.ts new file mode 100644 index 000000000..7b83b52a6 --- /dev/null +++ b/blocks/blocks-tests.ts @@ -0,0 +1,322 @@ +/// + +function test_blocks_methods() { + var extended: Object; + blocks.extend(extended, new Object()); + + blocks.each([3, 1, 4], function(value, index, collection) { + // value is the current item (3, 1 and 4) + // index is the current index (0, 1 and 2) + // collection points to the array passed to the function - [3, 1, 4] + }); + + blocks.eachRight([3, 1, 4], function(value, index, collection) { + // value is the current item (4, 1 and 3) + // index is the current index (2, 1 and 0) + // collection points to the array passed to the function - [3, 1, 4] + }); + + blocks.isArray([1, 2, 3]); + // -> true + + function calculate() { + blocks.isArray(arguments); + // -> false + } + + function max(collection: any, callback: any) { + callback = callback || blocks.noop; + } + + blocks.type('a string'); + // -> string + + blocks.type(314); + // -> number + + blocks.type([]); + // -> array + + blocks.type({}); + // -> object + + blocks.type(blocks.noop); + // -> function + + blocks.type(new RegExp('')); + // -> regexp + + blocks.type(undefined); + // -> undefined + + blocks.type(null); + // -> null + + blocks.is([], 'array'); + // -> true + + blocks.is(function() { }, 'object'); + // -> false + + blocks.has({ + price: undefined + }, 'price'); + // -> true + + blocks.has({ + price: 314 + }, 'ratio'); + // -> false + + blocks.unwrap(blocks.observable(314)); + // -> 314 + + blocks.unwrap(blocks([3, 1, 4])); + // -> [3, 1, 4] + + blocks.unwrap('a string or any other value will not be changed'); + // -> 'a string or any other value will not be changed' + + blocks.toArray(3); + // -> [3] + + blocks.toArray([3, 1, 4]); + // -> [3, 1, 4] + + blocks.toUnit(230); + // -> 230px + + blocks.toUnit(230, '%'); + // -> 230% + + blocks.toUnit('60px', '%'); + // -> 60% + + var array = [3, 1, 4]; + var cloned = blocks.clone(array); + // -> [3, 1, 4] + var areEqual = array == cloned; + // -> false + + blocks.isElement(document.body); + // -> true + + blocks.isElement({}); + // -> false + + blocks.isBoolean(true); + // -> true + + blocks.isBoolean(new Boolean(false)); + // -> true + + blocks.isBoolean(1); + // -> false + + blocks.isPlainObject({ property: true }); + // -> true + + blocks.isPlainObject(new Object()); + // -> true + + var car = new Object(); + + blocks.isPlainObject(car); + // -> false + + var alert = blocks.bind(() => { + alert(this); + }, 'Hello bind method!'); + + alert(); + // -> alerts 'Hello bind method' + + var alertAll = blocks.bind((firstName: string, lastName: string) => { + alert('My name is ' + firstName + ' ' + lastName); + }, null, 'John', 'Doe'); + + alertAll(); + // -> alerts 'My name is John Doe' + + blocks.equals([3, 4], [3, 4]); + // -> true + + blocks.equals({ value: 7 }, { value: 7, result: 1 }); + // -> false + + blocks.query({ + message: 'Hello World!' + }); + + blocks.query({ + items: ['John', 'Alf', 'Mega'], + alertIndex: (e: any) => { + alert('Clicked an item with index:' + blocks.context(e.target).$index); + } + }); + + blocks.query({ + items: [1, 2, 3], + alertValue: (e: any) => { + alert('Clicked the value: ' + blocks.dataItem(e.target)); + } + }); + + blocks.isObservable(blocks.observable(3)); + // -> true + + blocks.isObservable(3); + // -> false + + blocks.unwrapObservable(blocks.observable(304)); + // -> 304 + + blocks.unwrapObservable(305); + // -> 305 +} + +function test_observable_array() { + // creates an observable array with [1, 2, 3] as values + var items = blocks.observable([1, 2, 3]); + + // removes the previous values and fills the observable array with [5, 6, 7] values + items.reset([5, 6, 7]) + + // results in observable array with [1, 2, 3, 4] values + items.add(4); + + // results in observable array with [1, 2, 3, 4, 5, 6] values + items.addMany([4, 5, 6]); + + var items = blocks.observable([4, 2, 3, 1]); + + // results in observable array with [1, 2, 3, 4] values + items.swap(0, 3); + + var items = blocks.observable([1, 4, 2, 3, 5]); + + // results in observable array with [1, 2, 3, 4, 5] values + items.move(1, 4); +} + +function test_Property() { + var App = blocks.Application(); + + var User = App.Model({ + username: App.Property({ + defaultValue: 'John Doe' + }) + }); +} + +function test_Model() { + var App = blocks.Application(); + + var User = App.Model({ + firstName: App.Property({ + required: true, + validateOnChange: true + }), + + lastName: App.Property({ + required: true, + validateOnChange: true + }), + + fullName: App.Property({ + value: function() { + return this.firstName() + ' ' + this.lastName(); + } + }) + }); + + App.View('Profile', { + user: User({ + firstName: 'John', + lastName: 'Doe' + }) + }); +} + +function test_Collection() { + var App = blocks.Application(); + + var User = App.Model({ + firstName: App.Property({ + required: true, + validateOnChange: true + }), + + lastName: App.Property({ + required: true, + validateOnChange: true + }), + + fullName: App.Property({ + value: function() { + return this.firstName() + ' ' + this.lastName(); + } + }) + }); + + var Users = App.Collection(User, { + count: App.Property({ + value: () => { + return this().length; + } + }) + }); + + App.View('Profiles', { + users: Users([{ + firstName: 'John', + lastName: 'Doe' + }, { + firstName: 'Johna', + lastName: 'Doa' + }]) + }); +} + +function test_View() { + var App = blocks.Application(); + + App.View('Clicker', { + handleClick: () => { + alert('Clicky! Click!'); + } + }); + + + App.View('Statistics', { + init: () => { + this.loadRemoteData(); + }, + + loadRemoteData: () => { + // ...stuff... + } + }); + + App.View('ContactUs', { + options: { + route: 'contactus' + }, + + routed: () => { + alert('Navigated to ContactUs page!') + } + }); + + App.View('ContactUs', { + options: { + route: 'contactus' + } + }); + + App.View('Navigation', { + navigateToContactUs: () => { + this.route('contactus') + } + }); +} \ No newline at end of file diff --git a/blocks/blocks.d.ts b/blocks/blocks.d.ts new file mode 100644 index 000000000..ad492333e --- /dev/null +++ b/blocks/blocks.d.ts @@ -0,0 +1,731 @@ +// Type definitions for jsblocks v0.3.0 +// Project: http://jsblocks.com/ +// Definitions by: Krzysztof Śmigiel +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +///////////////////////////////////////// +// blocks methods +///////////////////////////////////////// + +interface BlocksStatic { + (obj: any): any; + + /** + * Performs a query operation on the DOM. Executes all data-query attributes + * and renders the html result to the specified HTMLElement if not specified + * uses document.body by default. + * + * @param model The model that will be used to query the DOM. + */ + query(model: any): void; + /** + * @param model The model that will be used to query the DOM. + * @param element Optional element on which to execute the query. + */ + query(model: any, element: HTMLElement): void; + + /** + * Copies properties from all provided objects into the first object parameter + */ + extend(obj: Object, ...objects: any[]): void; + + /** + * Iterates over the collection + * + * @param collection The array or object to iterate over + * @param callback The callback that will be executed for each element in the collection + * @param thisArg Optional this context for the callback + */ + each(collection: any, callback: (value: any, index: any, collection: any) => void, thisArg?: any): void; + + /** + * Iterates over the collection from end to start + * + * @param collection The array or object to iterate over + * @param callback The callback that will be executed for each element in the collection + * @param thisArg Optional this context for the callback + */ + eachRight(collection: any, callback: (value: any, index: any, collection: any) => void, thisArg?: any): void; + + /** + * Determines if a value is an array. + * Returns false for array like objects (for example arguments object). + * + * @param value The value to check if it is an array + */ + isArray(value: any): boolean; + + /** + * Represents a dummy empty function + */ + noop(): Function; + + /** + * Determines the true type of an object. + * Returns the type of the value as a string. + * + * @param value The value for which to determine its type + */ + type(value: any): string; + + /** + * Determines if a specific value is the specified type + * + * @param value The value + * @param type The type + */ + is(value: any, type: string): boolean; + + /** + * Checks if a variable has the specified property. Uses hasOwnProperty internally + * + * @param obj The object to call hasOwnPrototype for + * @param key The key to check if exists in the object + */ + has(obj: any, key: string): boolean; + + /** + * Unwraps a jsblocks value to its raw representation. + * Unwraps blocks.observable() and blocks() values + * + * @param value The value that will be unwrapped + */ + unwrap(value: any): any; + + /** + * Converts a value to an array. Arguments object is converted to array and primitive values + * are wrapped in an array. + * Does nothing when value is already an array + * + * @param value The value to be converted to an array + */ + toArray(value: any): any[]; + + /** + * Converts an integer or string to a unit. If the value could not be parsed to a number it is not converted + * + * @param value The value to be converted to the specified unit + */ + toUnit(value: any): any; + /** + * @param value The value to be converted to the specified unit + * @param unit Optionally provide a unit to convert to. Default value is 'px' + */ + toUnit(value: any, unit: string): any; + + /** + * Clones value. If deepClone is set to true the value will be cloned recursively + * + * @param value Value/object to be cloned + */ + clone(value: any): any; + /** + * @param value Value/object to be cloned + * @param deepClone By default false + */ + clone(value: any, deepClone: boolean): any; + + /** + * Determines if the specified value is a HTML elements collection. + * Returns whether the value is elements collection. + * + * @param value The value to check if it is elements collection + */ + isElements(value: any): boolean; + + /** + * Determines if the specified value is a HTML element. + * Returns whether the value is a HTML element. + * + * @param value The value to check if it is a HTML element + */ + isElement(value: any): boolean; + + /** + * Determines if a the specified value is a boolean. + * Whether the value is a boolean or not. + * + * @param value The value to be checked if it is a boolean + */ + isBoolean(value: any): boolean; + + /** + * Determines if the specified value is an object. + * Returns whether the value is an object. + * + * @param obj The value to check for if it is an object + */ + isObject(obj: any): boolean; + + /** + * Determines if a value is a object created using {} or new Object. + * Whether the value is a plain object or not. + * + * @param obj The value that will be checked + */ + isPlainObject(obj: any): boolean; + + /** + * Changes the this binding to a function and optionally passes additional parameters to the function. + * Returns the newly created function having the new this binding and optional arguments. + * + * @param func The function for which to change the this binding and optionally add arguments + * @param thisArg The new this binding context value + * @param args Optional arguments that will be passed to the function + */ + bind(func: Function, thisArg: any, ...args: any[]): Function; + + /** + * Determines if two values are deeply equal. Set deepEqual to false to stop recusively equality checking + * + * @param a The first object to be campared + * @param b The second object to be compared + */ + equals(a: any, b: any): boolean; + /** + * @param a The first object to be campared + * @param b The second object to be compared + * @param deepEqual Determines if the equality check will recursively check all child properties + */ + equals(a: any, b: any, deepEqual: boolean): boolean; + + /** + * Gets the context for a particular element. Searches all parents until it finds the context. + * + * @param element The element from which to search for a context + * + */ + context(element: any): any; + + /** + * Gets the associated dataItem for a particlar element. Searches all parents until it finds the context + * + * @param element The element from which to search for a dataItem + */ + dataItem(element: any): any; + + /** + * Determines if particular value is an blocks.observable + * + * @param value The value to check if the value is observable + */ + isObservable(value: any): boolean; + + /** + * Gets the raw value of an observable or returns the value if the specified object is not an observable + * + * @param value The value that could be any object observable or not + */ + unwrapObservable(value: any): any; + + route(route: string): BlocksStatic; + + optional(param: string): BlocksStatic; + optional(param: string, defaultValue: any): BlocksStatic; + + range(start: number, end: number): BlocksStatic; + + /** + * Creates the server which will automatically handle server-side rendering. + */ + server(): { express(): any }; + /** + * @param options Overrides default jsblocks options + */ + server(options: Server): { express(): any }; + + /** + * Make observable property. You can specify initial value in parentheses. + */ + observable(): BlocksObservable; + observable(value: any[]): BlocksArray; + observable(value: any): BlocksObservable; + + /** + * Use blocks.Application and its MVC(Model-View-Collection) structure to create better architecture and maintainability for your application. + */ + Application(): App; + Application(options: { history: string }): App; +} + +///////////////////////////////////////// +// blocks observable +///////////////////////////////////////// + +interface BlocksObservable extends Extendable { + (arg: any): BlocksObservable; + + /** + * Updates all elements, expressions and dependencies where the observable is used + */ + update(): BlocksObservable; + + /** + * If event in prototype is not defined use this function instead. + * + * @param event Name of the event to raise + * @param trigger Function to be called when event is fired + */ + on(event: string, trigger: Function): BlocksObservable; +} + +///////////////////////////////////////// +// blocks array +///////////////////////////////////////// + +interface BlocksArray extends BlocksObservable { + + /** + * Updates all elements, expressions and dependencies where the observable is used + */ + update(): BlocksArray; + + /** + * Extends the current observable with particular functionality depending on the parameters specified. + * If the method is called without arguments and jsvalue framework is included the observable will be + * extended with the methods available in jsvalue for the current type. + * + * @param options Optional options + */ + extend(...options: any[]): BlocksArray; + /** + * @param name Name of the extender + * @param options Optional options + */ + extend(name: string, ...options: any[]): BlocksArray; + + /** + * Removes all items from the collection and replaces them with the new value provided. + * The value could be Array, observable array or jsvalue.Array + * + * @param value The new value that will be populated + */ + reset(value: any[]): BlocksArray; + + /** + * Adds values to the end of the observable array + * + * @param value The values that will be added to the end of the array + */ + add(value: any): BlocksArray; + /** + * @param value The values that will be added to the end of the array + * @param index Optional index specifying where to insert the value + */ + add(value: any, index: number): BlocksArray; + + /** + * Adds the values from the provided array(s) to the end of the collection + * + * @param value The array that will be added to the end of the array + */ + addMany(value: any[]): BlocksArray; + /** + * @param value The array that will be added to the end of the array + * @param index Optional position where the array of values to be inserted + */ + addMany(value: any[], index: number): BlocksArray; + + /** + * Swaps two values in the observable array. Note: Faster than removing the items and adding them at the locations + * + * @param indexA The first index that points to the index in the array that will be swapped + * @param indexB The second index that points to the index in the array that will be swapped + */ + swap(indexA: number, indexB: number): BlocksArray; + + /** + * Moves an item from one location to another in the array. Note: Faster than removing the item and adding it at the location + * + * @param sourceIndex The index pointing to the item that will be moved + * @param targetIndex The index where the item will be moved to + */ + move(sourceIndex: number, targetIndex: number): BlocksArray; + + /** + * Removes an item from the observable array + * + * @param value The value that will be removed or a callback function which returns true or false to determine if the value should be removed + */ + remove(value: any): BlocksArray; + /** + * @param value The value that will be removed or a callback function which returns true or false to determine if the value should be removed + * @param thisArg Optional this context for the callback + */ + remove(value: any, thisArg: Function): BlocksArray; + + /** + * Removes an item at the specified index + * + * @param index The index location of the item that will be removed + */ + removeAt(index: number): BlocksArray; + /** + * @param index The index location of the item that will be removed + * @param count Optional parameter that if specified will remove the next items starting from the specified index + */ + removeAt(index: number, count: number): BlocksArray; + + /** + * Removes all items from the observable array and optionally filter which items to be removed by providing a callback + */ + removeAll(): BlocksArray; + /** + * @param callback Optional callback function which filters which items to be removed. Returning a truthy value will remove the item and vice versa + */ + removeAll(callback: Function): BlocksArray; + /** + * @param callback Optional callback function which filters which items to be removed. Returning a truthy value will remove the item and vice versa + * @param thisArg Optional this context for the callback function + */ + removeAll(callback: Function, thisArg: any): BlocksArray; + + /** + * The concat() method is used to join two or more arrays + * + * @param arrays The arrays to be joined + */ + concat(...arrays: any[]): any[] + + /** + * The slice() method returns the selected elements in an array, as a new array object + * + * @param start An integer that specifies where to start the selection (The first element has an index of 0) + */ + slice(start: number): any[]; + /** + * @param start An integer that specifies where to start the selection (The first element has an index of 0) + * @param end An integer that specifies where to end the selection. If omitted, all elements from the start position and to the end of the array will be selected. + * Use negative numbers to select from the end of an array + */ + slice(start: number, end: number): any[]; + + /** + * The join() method joins the elements of an array into a string, and returns the string + */ + join(): string; + /** + * @param separator The separator to be used. If omitted, the elements are separated with a comma + */ + join(seperator: string): string; + + /** + * The pop() method removes the last element of a observable array, and returns that element + */ + pop(): any; + + /** + * The push() method adds new items to the end of the observable array, and returns the new length + * + * @param values The item(s) to add to the observable array + */ + push(...values: any[]): number; + + /** + * Reverses the order of the elements in the observable array + */ + reverse(): any[]; + + /** + * Removes the first element of a observable array, and returns that element + */ + shift(): any + + /** + * Sorts the elements of an array + */ + sort(): any[]; + /** + * @param sortfunction A function that defines the sort order + */ + sort(sortfunction: Function): any[]; + + /** + * Adds and/or removes elements from the observable array + * Returns A new array containing the removed items, if any. + * + * @param index An integer that specifies at what position to add/remove items. Use negative values to specify the position from the end of the array. + * @param howMany The number of items to be removed. If set to 0, no items will be removed. + * @param items The new item(s) to be added to the array. + */ + splice(index: number, howMany: number, ...items: any[]): any[]; + + /** + * The unshift() method adds new items to the beginning of an array, and returns the new length. + * + * @param items + */ + unshift(...items: any[]): number; +} + +///////////////////////////////////////// +// blocks MVC App +///////////////////////////////////////// + +interface App extends Extendable { + + /** + * Creates an application property for a Model. + */ + Property(): any; + /** + * @param options Configuration options for property + */ + Property(options: PropertyPrototype): any; + + /** + * Defines a view that will be part of the Application. + * + * @param name The name of the View you are creating + * @param prototype The object that will represent the View + */ + View(name: string, prototype: ViewPrototype): any; + /** + * Defines a view that will be part of the Application. + * + * @param parentViewName Provide this parameter only if you are creating nested views. This is the name of the parent View + * @param name The name of the View you are creating + * @param prototype The object that will represent the View + */ + View(parentViewName: string, name: string, prototype: ViewPrototype): any; + + /** + * Creates a new Model + * + * @param prototype The Model object properties that will be created + */ + Model(prototype: ModelPrototype): Model; + + /** + * Creates a new Collection + * + * @param prototype The Collection object properties that will be created. + */ + Collection(prototype: CollectionPrototype): Collection; + Collection(model: Model, prototype: CollectionPrototype): Collection; +} + +///////////////////////////////////////// +// App.Property +///////////////////////////////////////// + +interface PropertyPrototype { + defaultValue?: any; + isObservable?: boolean; + field?: string; + value?: any; + validateOnChange?: boolean; + maxErrors?: number; + validateInitially?: boolean + + // Validators + required?: Validator; + minlength?: Validator; + maxlength?: Validator; + min?: Validator; + max?: Validator; + email?: Validator; + url?: Validator; + date?: Validator; + creditcard?: Validator; + regexp?: Validator; + number?: Validator; + digits?: Validator; + letters?: Validator; + equals?: Validator; +} + +interface Validator { } + +///////////////////////////////////////// +// App.View +///////////////////////////////////////// + +interface ViewPrototype { + parentView?: any; + + /** + * Routes to a specific URL and actives the appropriate views associated with the URL + * + * @param name Name of the route + */ + route?(name: string): ViewPrototype; + + + /** + * Determines if the view is visible + */ + isActive?(): boolean; + + /** + * Override the init method to perform actions when the View is first created and shown on the page + */ + init?: Function; + + /** + * Override the routed method to perform actions when the View have routing and routing mechanism actives it. + */ + routed?: Function; + + navigateTo?: Function; + + /** + * Override the ready method to perform actions when the DOM is ready and + * all data-query have been executed. + */ + ready?: Function; + + options?: { + route?: any; + url?: string + }; +} + +///////////////////////////////////////// +// App.Model +///////////////////////////////////////// + +interface Model { + (): Model; + (props: Object): Model; + + /** + * Fires a request to the server to populate the Model based on the read URL specified + */ + read(): Model; + /** + * @param params The parameters Object that will be used to populate the Model from the specified options.read URL. If the URL does not contain parameters + */ + read(params: Object): Model; + + /** + * Synchronizes the changes with the server by sending requests to the provided URL's + */ + sync(): Model; +} + +interface ModelPrototype { + + /** + * Override the init method to perform actions on creation for each Model instance + */ + init?: Function; + + /** + * Validates all observable properties that have validation and returns true if all values are valid otherwise returns false + */ + validate?(): boolean; + + /** + * Extracts the raw(non observable) dataItem object values from the Model + */ + dataItem?(): Object; + + /** + * Applies new properties to the Model by providing an Object + * + * @param dataItem The object from which the new values will be applied + */ + reset?(dataItem: ModelPrototype): ModelPrototype; + + /** + * Determines whether the instance is new. If true when syncing the item will send for insertion instead of updating it. + * The check is determined by the idAttr value specified in the options. If idAttr is not specified the item will always be considered new. + * + */ + isNew?(): boolean; + + options?: { + idAttr?: string; + baseUrl?: string; + read?: { url?: string }; + create?: { url?: string }; + destroy?: { url?: string }; + update?: { url?: string }; + }; +} + +///////////////////////////////////////// +// App.Collection +///////////////////////////////////////// + +interface Collection extends Extendable { + (): Collection; + (props: Object[]): Collection; + + /** + * Fires a request to the server to populate the Model based on the read URL specified + */ + read(): Collection; + /** + * @param params The parameters Object that will be used to populate the Collection from the specified options.read URL. If the URL does not contain parameters + */ + read(params: Object): Collection; + + /** + * Clear all changes made to the collection + */ + clearChanges(): Collection; + + /** + * Performs an ajax request for all create, update and delete operations in order to sync them with a database. + */ + sync(): Collection; + + update(id: number, newValues: Object): Collection; +} + +interface CollectionPrototype { + options?: { + read?: { url?: string }; + create?: { url?: string }; + destroy?: { url?: string }; + update?: { url?: string }; + }; +} + +interface Extendable { + + /** + * Extends the current observable with particular functionality depending on the parameters specified. + * If the method is called without arguments and jsvalue framework is included the observable will be + * extended with the methods available in jsvalue for the current type. + * + * @param name Name of the extender + * @param options Optional options + */ + extend(name?: string, ...options: any[]): T; + extend(arg: any): T; +} + +interface Server { + + /** + * The port at which your application will be run + */ + port?: number; + + /** + * The folder where your application files like .html; .js and .css are going to be. + * The value is passed to express.static() middleware. + */ + static?: string; + + /** + * Caches pages result instead of executing them each time. + * Disabling cache could impact performance. + */ + cache?: boolean; + + /** + * Provide an express middleware function or an array of middleware functions. + * Use: [compression(); bodyParser()] + */ + use?: any; +} + +declare var blocks: BlocksStatic; + +declare module "blocks" { + export = blocks; +} \ No newline at end of file diff --git a/browser-sync/browser-sync-tests.ts b/browser-sync/browser-sync-tests.ts index 2f5459c2f..0af5dfc00 100644 --- a/browser-sync/browser-sync-tests.ts +++ b/browser-sync/browser-sync-tests.ts @@ -70,3 +70,13 @@ evt.on("init", function () { }); browserSync(config); + +var bs = browserSync.create(); + +bs.init({ + server: "./app" +}); + +bs.reload(); + + diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 4b0cd72c0..db9f3ad3b 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -3,96 +3,113 @@ // Definitions by: Asana // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// /// declare module "browser-sync" { + import chokidar = require("chokidar"); + import fs = require("fs"); import http = require("http"); - - function BrowserSync(config?: BrowserSync.Options, callback?: (err: Error, bs: Object) => any): void; - - module BrowserSync { - export function reload(): void; - export function reload(file: string): void; - export function reload(files: string[]): void; - export function reload(options: {stream: boolean}): NodeJS.ReadWriteStream; - export function notify(message: string, timeout?: number): void; - - export function exit(): void; - - export var active: boolean; - - export var emitter: NodeJS.EventEmitter; - - interface Options { - files?: string | string[]; - watchOptions?: GazeOptions; - server?: ServerOptions; - proxy?: string | boolean; - port?: number; - https?: boolean; - ghostMode?: GhostOptions | boolean; - logLevel?: string; - logPrefix?: string; - logConnections?: boolean; - logFileChanges?: boolean; - logSnippet?: boolean; - snippetOptions?: SnippetOptions; - tunnel?: string | boolean; - online?: boolean; - open?: string | boolean; - browser?: string | string[]; - xip?: boolean; - notify?: boolean; - scrollProportionally?: boolean; - scrollThrottle?: number; - reloadDelay?: number; - injectChanges?: boolean; - startPath?: string; - minify?: boolean; - host?: string; - codeSync?: boolean; - timestamps?: boolean; - scriptPath?: (path: string) => string; - socket?: SocketOptions; - } - - interface GazeOptions { - interval?: number; - debounceDelay?: number; - mode?: string; - cwd?: string; - } - - interface ServerOptions { - baseDir?: string | string[]; - directory?: boolean; - index?: string; - routes?: {[path: string]: string}; - middleware?: MiddlewareHandler[]; - } - - interface MiddlewareHandler { - (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; - } - - interface GhostOptions { - clicks?: boolean; - scroll?: boolean; - forms?: boolean; - } - - interface SnippetOptions { - ignorePaths?: string; - rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any}; - } - - interface SocketOptions { - path?: string; - clientPath?: string; - namespace?: string; - } + interface Options { + files?: string | string[]; + watchOptions?: GazeOptions; + server?: ServerOptions; + proxy?: string | boolean; + port?: number; + https?: boolean; + ghostMode?: GhostOptions | boolean; + logLevel?: string; + logPrefix?: string; + logConnections?: boolean; + logFileChanges?: boolean; + logSnippet?: boolean; + snippetOptions?: SnippetOptions; + rewriteRules?: boolean | RewriteRules[]; + tunnel?: string | boolean; + online?: boolean; + open?: string | boolean; + browser?: string | string[]; + xip?: boolean; + notify?: boolean; + scrollProportionally?: boolean; + scrollThrottle?: number; + reloadDelay?: number; + reloadDebounce?: number; + plugins?: any[]; + injectChanges?: boolean; + startPath?: string; + minify?: boolean; + host?: string; + codeSync?: boolean; + timestamps?: boolean; + scriptPath?: (path: string) => string; + socket?: SocketOptions; } - export = BrowserSync; + interface GazeOptions { + interval?: number; + debounceDelay?: number; + mode?: string; + cwd?: string; + } + + interface ServerOptions { + baseDir?: string | string[]; + directory?: boolean; + index?: string; + routes?: {[path: string]: string}; + middleware?: MiddlewareHandler[]; + } + + interface MiddlewareHandler { + (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; + } + + interface GhostOptions { + clicks?: boolean; + scroll?: boolean; + forms?: boolean; + } + + interface SnippetOptions { + ignorePaths?: string; + rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any}; + } + + interface SocketOptions { + path?: string; + clientPath?: string; + namespace?: string; + } + + interface RewriteRules { + match: RegExp; + fn: (match: string) => string; + } + + interface BrowserSync { + init(config?: Options, callback?: (err: Error, bs: Object) => any): void; + reload(): void; + reload(file: string): void; + reload(files: string[]): void; + reload(options: {stream: boolean}): NodeJS.ReadWriteStream; + notify(message: string, timeout?: number): void; + exit(): void; + watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any): NodeJS.EventEmitter; + pause(): void; + resume(): void; + emitter: NodeJS.EventEmitter; + active: boolean; + paused: boolean; + } + + interface Exports extends BrowserSync { + create(): BrowserSync; + (config?: Options, callback?: (err: Error, bs: Object) => any): void; + } + + var browserSync: Exports; + + export = browserSync; } diff --git a/chai-as-promised/chai-as-promised-tests.ts b/chai-as-promised/chai-as-promised-tests.ts index 20a773cdd..a2dcb72ed 100644 --- a/chai-as-promised/chai-as-promised-tests.ts +++ b/chai-as-promised/chai-as-promised-tests.ts @@ -1,4 +1,3 @@ -/// /// import chai = require('chai'); @@ -6,6 +5,7 @@ import chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); +// ReSharper disable WrongExpressionStatement var promise: any; chai.expect(promise).to.eventually.equal(3); chai.expect(promise).to.become(3); diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts index 20b697bb5..6ff150eb4 100644 --- a/chai-as-promised/chai-as-promised.d.ts +++ b/chai-as-promised/chai-as-promised.d.ts @@ -6,21 +6,21 @@ /// declare module 'chai-as-promised' { - import chai = require('chai'); - function chaiAsPromised(chai: any, utils: any): void; - export = chaiAsPromised; } -declare module chai { +declare module Chai { + + interface Assertion { + become(expected: any): Assertion; + rejected: Assertion; + rejectedWith(expected: any): Assertion; + notify(fn: Function): Assertion; + } interface LanguageChains { - become(expected: any): Expect; - eventually: Expect; - rejected: Expect; - rejectedWith(expected: any): Expect; - notify(fn: Function): Expect; + eventually: Assertion; } interface Assert { @@ -32,4 +32,4 @@ declare module chai { isRejected(promise: any, expected: any, message?: string): void; isRejected(promise: any, match: RegExp, message?: string): void; } -} \ No newline at end of file +} diff --git a/chai-datetime/chai-datetime-tests.ts b/chai-datetime/chai-datetime-tests.ts index 8f8238b4e..5c15326f4 100644 --- a/chai-datetime/chai-datetime-tests.ts +++ b/chai-datetime/chai-datetime-tests.ts @@ -1,13 +1,16 @@ -/// /// +import chai = require('chai'); +import chaiDateTime = require('chai-datetime'); + +chai.use(chaiDateTime); var expect = chai.expect; var assert = chai.assert; function test_equalTime(){ var date: Date = new Date(2014, 1, 1); - expect(date).to.be.equalTime(date); - date.should.be.equalTime(date); + expect(date).to.equalTime(date); + date.should.equalTime(date); assert.equalTime(date, date); } @@ -34,14 +37,14 @@ function test_equalDate(){ function test_beforeDate(){ var date: Date = new Date(2014, 1, 1); - expect(date).to.beforeDate(date); - date.should.beforeDate(date); + expect(date).to.be.beforeDate(date); + date.should.be.beforeDate(date); assert.beforeDate(date, date); } function test_afterDate(){ var date: Date = new Date(2014, 1, 1); - expect(date).to.afterDate(date); - date.should.afterDate(date); + expect(date).to.be.afterDate(date); + date.should.be.afterDate(date); assert.afterDate(date, date); } diff --git a/chai-datetime/chai-datetime.d.ts b/chai-datetime/chai-datetime.d.ts index bce063443..b6140689c 100644 --- a/chai-datetime/chai-datetime.d.ts +++ b/chai-datetime/chai-datetime.d.ts @@ -5,35 +5,38 @@ /// -declare module chai { +declare module Chai { - interface Expect { - afterDate(date: Date): boolean; - beforeDate(date: Date): boolean; - equalDate(date: Date): boolean; + interface Assertion { + afterDate(date: Date): Assertion; + beforeDate(date: Date): Assertion; + equalDate(date: Date): Assertion; + afterTime(date: Date): Assertion; + beforeTime(date: Date): Assertion; + equalTime(date: Date): Assertion; + } - afterTime(date: Date): boolean; - beforeTime(date: Date): boolean; - equalTime(date: Date): boolean; - } - - interface Assert { - equalTime(val: Date, exp: Date, msg?: string): boolean; - notEqualTime(val: Date, exp: Date, msg?: string): boolean; - beforeTime(val: Date, exp: Date, msg?: string): boolean; - notBeforeTime(val: Date, exp: Date, msg?: string): boolean; - afterTime(val: Date, exp: Date, msg?: string): boolean; - notAfterTime(val: Date, exp: Date, msg?: string): boolean; - - equalDate(val: Date, exp: Date, msg?: string): boolean; - notEqualDate(val: Date, exp: Date, msg?: string): boolean; - beforeDate(val: Date, exp: Date, msg?: string): boolean; - notBeforeDate(val: Date, exp: Date, msg?: string): boolean; - afterDate(val: Date, exp: Date, msg?: string): boolean; - notAfterDate(val: Date, exp: Date, msg?: string): boolean; - } + interface Assert { + equalTime(val: Date, exp: Date, msg?: string): void; + notEqualTime(val: Date, exp: Date, msg?: string): void; + beforeTime(val: Date, exp: Date, msg?: string): void; + notBeforeTime(val: Date, exp: Date, msg?: string): void; + afterTime(val: Date, exp: Date, msg?: string): void; + notAfterTime(val: Date, exp: Date, msg?: string): void; + equalDate(val: Date, exp: Date, msg?: string): void; + notEqualDate(val: Date, exp: Date, msg?: string): void; + beforeDate(val: Date, exp: Date, msg?: string): void; + notBeforeDate(val: Date, exp: Date, msg?: string): void; + afterDate(val: Date, exp: Date, msg?: string): void; + notAfterDate(val: Date, exp: Date, msg?: string): void; + } } interface Date { - should: chai.Expect; + should: Chai.Assertion; +} + +declare module "chai-datetime" { + function chaiDateTime(chai: any, utils: any): void; + export = chaiDateTime; } diff --git a/chai-fuzzy/chai-fuzzy-tests.ts b/chai-fuzzy/chai-fuzzy-tests.ts new file mode 100644 index 000000000..292b25002 --- /dev/null +++ b/chai-fuzzy/chai-fuzzy-tests.ts @@ -0,0 +1,35 @@ +/// + +// tests taken from http://chaijs.com/plugins/chai-fuzzy + +import chai = require('chai'); +import chaiFuzzy = require('chai-fuzzy'); + +chai.use(chaiFuzzy); +var expect = chai.expect; +var assert = chai.assert; + +/** + * compare object attributes and values rather than checking to see if they're the same reference + */ +function like() { + var subject = { a: 'a' }; + + expect(subject).to.be.like({ a: 'a' }); + expect(subject).not.to.be.like({ x: 'x' }); + expect(subject).not.to.be.like({ a: 'a', b: 'b' }); + + assert.like(subject, { a: 'a' }); + assert.notLike(subject, { x: 'x' }); + assert.notLike(subject, { a: 'a', b: 'b' }); + + var subject2 = ['a']; + + expect(subject2).to.be.like(['a']); + expect(subject2).not.to.be.like(['x']); + expect(subject2).not.to.be.like(['a', 'b']); + + assert.like(subject2, ['a']); + assert.notLike(subject2, ['x']); + assert.notLike(subject2, ['a', 'b']); +} diff --git a/chai-fuzzy/chai-fuzzy.d.ts b/chai-fuzzy/chai-fuzzy.d.ts index acfb515f4..90955e1e1 100644 --- a/chai-fuzzy/chai-fuzzy.d.ts +++ b/chai-fuzzy/chai-fuzzy.d.ts @@ -5,13 +5,72 @@ /// -declare module chai { - interface Assert { - like(act:any, exp:any, msg?:string); - notLike(act:any, exp:any, msg?:string); - containOneLike(act:any, exp:any, msg?:string); - notContainOneLike(act:any, exp:any, msg?:string); - jsonOf(act:any, exp:any, msg?:string); - notJsonOf(act:any, exp:any, msg?:string); +declare module Chai { + + interface Assertion { + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + like(expected: any, message?: string): Assertion; + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + notLike(expected: any, message?: string): Assertion; + /** + * Check the first level of the container for a value like the one provided. + */ + containOneLike(expected: any, message?: string): Assertion; + /** + * Check the first level of the container for a value like the one provided. + */ + notContainOneLike(expected: any, message?: string): Assertion; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + jsonOf(expected: any, message?: string): Assertion; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + notJsonOf(expected: any, message?: string): Assertion; + } + + export interface Assert { + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + like(actual: any, expected: any, message?: string): void; + /** + * Compare object attributes and values rather than checking to see if + * they're the same reference. + */ + notLike(actual: any, expected: any, message?: string): void; + /** + * Check the first level of the container for a value like the one provided. + */ + containOneLike(actual: any, expected: any, message?: string): void; + /** + * Check the first level of the container for a value like the one provided. + */ + notContainOneLike(actual: any, expected: any, message?: string): void; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + jsonOf(actual: any, expected: any, message?: string): void; + /** + * Check that the given javascript object is like the JSON-ified expected + * value. Useful for checking stringification and parsing of an object. + */ + notJsonOf(actual: any, expected: any, message?: string): void; } } + +declare module "chai-fuzzy" { + function chaiFuzzy(chai: any, utils: any): void; + export = chaiFuzzy; +} diff --git a/chai-fuzzy/chai-fuzzy.d.ts.tscparams b/chai-fuzzy/chai-fuzzy.d.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/chai-fuzzy/chai-fuzzy.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/chai-http/chai-http-tests.ts b/chai-http/chai-http-tests.ts index e6e471321..078a7799c 100644 --- a/chai-http/chai-http-tests.ts +++ b/chai-http/chai-http-tests.ts @@ -1,20 +1,21 @@ /// -/// +/// import fs = require('fs'); import http = require('http'); import chai = require('chai'); -import chaiHttp = require('chai-http'); +import ChaiHttp = require('chai-http'); import when = require('when'); -chai.use(chaiHttp); +chai.use(ChaiHttp); + +// ReSharper disable WrongExpressionStatement // Add promise support if this does not exist natively. if (!global.Promise) { chai.request.addPromises(when.promise); } - var app: http.Server; chai.request(app).get('/'); @@ -41,13 +42,12 @@ chai.request(app) chai.request(app) .get('/search') - .query('name', 'foo') - .query('limit', '10'); + .query({name: 'foo', limit: 10}); chai.request(app) .put('/user/me') .send({ passsword: '123', confirmPassword: '123' }) - .end((err: any, res: chaiHttp.Response) => { + .end((err: any, res: ChaiHttp.Response) => { chai.expect(err).to.be.null; chai.expect(res).to.have.status(200); }); @@ -55,7 +55,7 @@ chai.request(app) chai.request(app) .put('/user/me') .send({ passsword: '123', confirmPassword: '123' }) - .then((res: chaiHttp.Response) => chai.expect(res).to.have.status(200)) + .then((res: ChaiHttp.Response) => chai.expect(res).to.have.status(200)) .catch((err: any) => { throw err; }); var agent = chai.request.agent(app); @@ -63,17 +63,17 @@ var agent = chai.request.agent(app); agent .post('/session') .send({ username: 'me', password: '123' }) - .then((res: chaiHttp.Response) => { + .then((res: ChaiHttp.Response) => { chai.expect(res).to.have.cookie('sessionid'); // The `agent` now has the sessionid cookie saved, and will send it // back to the server in the next request: return agent.get('/user/me') - .then((res: chaiHttp.Response) => chai.expect(res).to.have.status(200)); + .then((res: ChaiHttp.Response) => chai.expect(res).to.have.status(200)); }); function test1() { var req = chai.request(app).get('/'); - req.then((res: chaiHttp.Response) => { + req.then((res: ChaiHttp.Response) => { chai.expect(res).to.have.status(200); chai.expect(res).to.have.header('content-type', 'text/plain'); chai.expect(res).to.have.header('content-type', /^text/); @@ -99,5 +99,4 @@ function test1() { }); } - when(chai.request(app).get('/')).done(() => console.log('success'), () => console.log('failure')); diff --git a/chai-http/chai-http.d.ts b/chai-http/chai-http.d.ts index fed2a8416..8f009c6ab 100644 --- a/chai-http/chai-http.d.ts +++ b/chai-http/chai-http.d.ts @@ -6,27 +6,38 @@ /// /// -declare module chai { - export function request(server: any): chaiHttp.Agent; +declare module Chai { - export module request { - export function agent(server: any): chaiHttp.Agent; - export function addPromises(promiseConstructor: chaiHttp.PromiseConstructor): void; + interface ChaiStatic { + request: ChaiHttpRequest; } - interface Assertions extends chaiHttp.Assertions { + interface ChaiHttpRequest { + (server: any): ChaiHttp.Agent; + agent(server: any): ChaiHttp.Agent; + addPromises(promiseConstructor: any): void; } - interface TypeComparison extends chaiHttp.TypeComparison { + interface Assertion { + status(code: number): Assertion; + header(key: string, value?: string): Assertion; + header(key: string, value?: RegExp): Assertion; + headers: Assertion; + json: Assertion; + text: Assertion; + html: Assertion; + redirect: Assertion; + redirectTo(location: string): Assertion; + param(key: string, value?: string): Assertion; + cookie(key: string, value?: string): Assertion; + } + + interface TypeComparison { + ip: Assertion; } } -declare function chaiHttp(chai: any, utils: any): void; -declare module chaiHttp { - interface PromiseConstructor { - (resolver: (resolve: (value: T) => void, reject: (reason: any) => void) => void): Promise; - } - +declare module ChaiHttp { interface Promise { then(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U): Promise; } @@ -38,10 +49,9 @@ declare module chaiHttp { } interface Request extends FinishedRequest { - attach(field: string, file: string, filename: string): Request; - attach(field: string, file: Buffer, filename: string): Request; + attach(field: string, file: string|Buffer, filename: string): Request; set(field: string, val: string): Request; - query(key: string, value: string): Request; + query(params: Object): Request; send(data: Object): Request; auth(user: string, name: string): Request; field(name: string, val: string): Request; @@ -63,25 +73,12 @@ declare module chaiHttp { patch(url: string, callback?: (err: any, res: Response) => void): Request; } - interface Assertions { - status(code: number): any; - header(key: string, value?: string): any; - header(key: string, value?: RegExp): any; - headers: any; - json: any; - // text: any; - // html: any; - redirect: any; - redirectTo(location: string): any; - param(key: string, value?: string): any; - cookie(key: string, value?: string): any; - } - interface TypeComparison { ip: any; } } declare module "chai-http" { + function chaiHttp(chai: any, utils: any): void; export = chaiHttp; } diff --git a/chai-jquery/chai-jquery-tests.ts b/chai-jquery/chai-jquery-tests.ts index 45c9981f5..64f6b040b 100644 --- a/chai-jquery/chai-jquery-tests.ts +++ b/chai-jquery/chai-jquery-tests.ts @@ -1,9 +1,9 @@ -/// /// // tests taken from https://github.com/chaijs/chai-jquery -declare var $; +declare var $: ChaiJQueryStatic; +import chai = require('chai'); var expect = chai.expect; function test_attr() { @@ -19,7 +19,7 @@ function test_css() { function test_data() { expect($('#foo')).to.have.data('toggle'); expect($('#foo')).to.have.css('toggle', 'true'); - expect($('body')).to.have.css('font-family').match(/sans-serif/); + expect($('body')).to.have.css('font-family').and.match(/sans-serif/); } function test_class() { @@ -88,4 +88,4 @@ function test_be_selector() { function test_have_selector() { $('body').should.have('h1'); expect($('#foo')).to.have('div'); -} \ No newline at end of file +} diff --git a/chai-jquery/chai-jquery-tests.ts.tscparams b/chai-jquery/chai-jquery-tests.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/chai-jquery/chai-jquery-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/chai-jquery/chai-jquery.d.ts b/chai-jquery/chai-jquery.d.ts index 826e66579..d4eb7465f 100644 --- a/chai-jquery/chai-jquery.d.ts +++ b/chai-jquery/chai-jquery.d.ts @@ -4,34 +4,2577 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// -declare module chai { - interface NameValueRegexMatcher { - match(value: RegExp): boolean; - } +declare module Chai { - interface NameValueMatcher { - (name: string, value?: string): boolean; - } - - interface Have { - attr: NameValueMatcher; - css: NameValueMatcher; - data: NameValueMatcher; - class(className: string): boolean; - id(id: string): boolean; - html(html: string): boolean; - text(text: string): boolean; - value(text: string): boolean; - (selector: string): boolean; - } - - interface Be { - visible: boolean; - hidden: boolean; - selected: boolean; - checked: boolean; - disabled: boolean; - (selector: string): boolean; + interface Assertion { + attr: (name: string, value?: string) => Assertion; + css: (name: string, value?: string) => Assertion; + data: (name: string, value?: string) => Assertion; + class(className: string): Assertion; + id(id: string): Assertion; + html(html: string): Assertion; + text(text: string): Assertion; + value(text: string): Assertion; + (selector: string): Assertion; + visible: Assertion; + hidden: Assertion; + selected: Assertion; + checked: Assertion; + disabled: Assertion; + (selector: string): Assertion; } } + +/** + * Static members of chai-jquery (those on $ and jQuery themselves) + */ +interface ChaiJQueryStatic { + + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(settings: JQueryAjaxSettings): JQueryXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; + + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + + ajaxSettings: JQueryAjaxSettings; + + /** + * Set default values for future Ajax requests. Its use is not recommended. + * + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + */ + ajaxSetup(options: JQueryAjaxSettings): void; + + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + */ + param: JQueryParam; + + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * + * @param flags An optional list of space-separated flags that change how the callback list behaves. + */ + Callbacks(flags?: string): JQueryCallback; + + /** + * Holds or releases the execution of jQuery's ready event. + * + * @param hold Indicates whether the ready hold is being requested or released + */ + holdReady(hold: boolean): void; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + */ + (selector: string, context?: Element|JQuery): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in a jQuery object. + */ + (element: Element): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + */ + (elementArray: Element[]): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object A plain object to wrap in a jQuery object. + */ + (object: {}): ChaiJQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object An existing jQuery object to clone. + */ + (object: JQuery): ChaiJQuery; + /** + * Specify a function to execute when the DOM is fully loaded. + */ + (): ChaiJQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. + * @param ownerDocument A document in which the new elements will be created. + */ + (html: string, ownerDocument?: Document): ChaiJQuery; + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string defining a single, standalone, HTML element (e.g.
    or
    ). + * @param attributes An object of attributes, events, and methods to call on the newly-created element. + */ + (html: string, attributes: Object): ChaiJQuery; + + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + */ + (callback: Function): ChaiJQuery; + + /** + * Relinquish jQuery's control of the $ variable. + * + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + */ + noConflict(removeAll?: boolean): Object; + + /** + * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. + * + * @param deferreds One or more Deferred objects, or plain JavaScript objects. + */ + when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; + + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. + */ + cssHooks: { [key: string]: any; }; + cssNumber: any; + + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value. + */ + data(element: Element, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + */ + data(element: Element, key: string): any; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + */ + data(element: Element): any; + + /** + * Execute the next function on the queue for the matched element. + * + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(element: Element, queueName?: string): void; + + /** + * Determine whether an element has any jQuery data associated with it. + * + * @param element A DOM element to be checked for data. + */ + hasData(element: Element): boolean; + + /** + * Show the queue of functions to be executed on the matched element. + * + * @param element A DOM element to inspect for an attached queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(element: Element, queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(element: Element, queueName: string, newQueue: Function[]): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element on which to add a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue. + */ + queue(element: Element, queueName: string, callback: Function): ChaiJQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + */ + removeData(element: Element, name?: string): ChaiJQuery; + + /** + * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + */ + Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; + + /** + * Effects + */ + fx: { + tick: () => void; + /** + * The rate (in milliseconds) at which animations fire. + */ + interval: number; + stop: () => void; + speeds: { slow: number; fast: number; }; + /** + * Globally disable all animations. + */ + off: boolean; + step: any; + }; + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fnction The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + */ + proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param context The object to which the context (this) of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + */ + proxy(context: Object, name: string, ...additionalArguments: any[]): any; + + Event: JQueryEventConstructor; + + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + */ + error(message: any): ChaiJQuery; + + expr: any; + fn: any; //TODO: Decide how we want to type this + + isReady: boolean; + + // Properties + support: JQuerySupport; + + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + */ + contains(container: Element, contained: Element): boolean; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: T[], + callback: (indexInArray: number, valueOfElement: T) => any + ): any; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: any, + callback: (indexInArray: any, valueOfElement: any) => any + ): any; + + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(target: any, object1?: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; + + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + */ + globalEval(code: string): any; + + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array to search through. + * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. + */ + grep(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[]; + + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. + */ + inArray(value: T, array: T[], fromIndex?: number): number; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + */ + isArray(obj: any): boolean; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + */ + isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a Javascript function object. + * + * @param obj Object to test whether or not it is a function. + */ + isFunction(obj: any): boolean; + /** + * Determines whether its argument is a number. + * + * @param obj The value to be tested. + */ + isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + */ + isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + */ + isWindow(obj: any): boolean; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node he DOM node that will be checked to see if it's in an XML document. + */ + isXMLDoc(node: Node): boolean; + + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + */ + makeArray(obj: any): any[]; + + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + */ + map(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param arrayOrObject The Array or Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + */ + map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any; + + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array to merge, the elements of second added. + * @param second The second array to merge into the first, unaltered. + */ + merge(first: T[], second: T[]): T[]; + + /** + * An empty function. + */ + noop(): any; + + /** + * Return a number representing the current time. + */ + now(): number; + + /** + * Takes a well-formed JSON string and returns the resulting JavaScript object. + * + * @param json The JSON string to parse. + */ + parseJSON(json: string): any; + + /** + * Parses a string into an XML document. + * + * @param data a well-formed XML string to be parsed + */ + parseXML(data: string): XMLDocument; + + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str Remove the whitespace from the beginning and end of a string. + */ + trim(str: string): string; + + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + */ + type(obj: any): string; + + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + */ + unique(array: Element[]): Element[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; +} + +/** + * The chai-jquery instance members + */ +interface ChaiJQuery { + /** + * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + * + * @param handler The function to be invoked. + */ + ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): ChaiJQuery; + /** + * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): ChaiJQuery; + /** + * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): ChaiJQuery; + /** + * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStart(handler: () => any): ChaiJQuery; + /** + * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStop(handler: () => any): ChaiJQuery; + /** + * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): ChaiJQuery; + + /** + * Load data from the server and place the returned HTML into the matched element. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param complete A callback function that is executed when the request completes. + */ + load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): ChaiJQuery; + + /** + * Encode a set of form elements as a string for submission. + */ + serialize(): string; + /** + * Encode a set of form elements as an array of names and values. + */ + serializeArray(): JQuerySerializeArrayElement[]; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + */ + addClass(className: string): ChaiJQuery; + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. + */ + addClass(func: (index: number, className: string) => string): ChaiJQuery; + + /** + * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. + */ + addBack(selector?: string): ChaiJQuery; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + */ + attr(attributeName: string): string; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param value A value to set for the attribute. + */ + attr(attributeName: string, value: string|number): ChaiJQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. + */ + attr(attributeName: string, func: (index: number, attr: string) => string|number): ChaiJQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributes An object of attribute-value pairs to set. + */ + attr(attributes: Object): ChaiJQuery; + + /** + * Determine whether any of the matched elements are assigned the given class. + * + * @param className The class name to search for. + */ + hasClass(className: string): boolean; + + /** + * Get the HTML contents of the first element in the set of matched elements. + */ + html(): string; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + */ + html(htmlString: string): ChaiJQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + html(func: (index: number, oldhtml: string) => string): ChaiJQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + + /** + * Get the value of a property for the first element in the set of matched elements. + * + * @param propertyName The name of the property to get. + */ + prop(propertyName: string): any; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param value A value to set for the property. + */ + prop(propertyName: string, value: string|number|boolean): ChaiJQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + prop(properties: Object): ChaiJQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. + */ + prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): ChaiJQuery; + + /** + * Remove an attribute from each element in the set of matched elements. + * + * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. + */ + removeAttr(attributeName: string): ChaiJQuery; + + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + */ + removeClass(className?: string): ChaiJQuery; + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. + */ + removeClass(func: (index: number, className: string) => string): ChaiJQuery; + + /** + * Remove a property for the set of matched elements. + * + * @param propertyName The name of the property to remove. + */ + removeProp(propertyName: string): ChaiJQuery; + + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. + */ + toggleClass(className: string, swtch?: boolean): ChaiJQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(swtch?: boolean): ChaiJQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): ChaiJQuery; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text or an array of strings corresponding to the value of each matched element to set as selected/checked. + */ + val(value: string|string[]): ChaiJQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string) => string): ChaiJQuery; + + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + */ + css(propertyName: string): string; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + */ + css(propertyName: string, value: string|number): ChaiJQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + css(propertyName: string, value: (index: number, value: string) => string|number): ChaiJQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + css(properties: Object): ChaiJQuery; + + /** + * Get the current computed height for the first element in the set of matched elements. + */ + height(): number; + /** + * Set the CSS height of every matched element. + * + * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). + */ + height(value: number|string): ChaiJQuery; + /** + * Set the CSS height of every matched element. + * + * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. + */ + height(func: (index: number, height: number) => number|string): ChaiJQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding but not border. + */ + innerHeight(): number; + + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: number|string): ChaiJQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding but not border. + */ + innerWidth(): number; + + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: number|string): ChaiJQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the document. + */ + offset(): JQueryCoordinates; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + */ + offset(coordinates: JQueryCoordinates): ChaiJQuery; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. + */ + offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): ChaiJQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerHeight(includeMargin?: boolean): number; + + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number|string): ChaiJQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding and border. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerWidth(includeMargin?: boolean): number; + + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: number|string): ChaiJQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. + */ + position(): JQueryCoordinates; + + /** + * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. + */ + scrollLeft(): number; + /** + * Set the current horizontal position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollLeft(value: number): ChaiJQuery; + + /** + * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. + */ + scrollTop(): number; + /** + * Set the current vertical position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollTop(value: number): ChaiJQuery; + + /** + * Get the current computed width for the first element in the set of matched elements. + */ + width(): number; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + width(value: number|string): ChaiJQuery; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. + */ + width(func: (index: number, width: number) => number|string): ChaiJQuery; + + /** + * Remove from the queue all items that have not yet been run. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + clearQueue(queueName?: string): ChaiJQuery; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + */ + data(key: string, value: any): ChaiJQuery; + /** + * Store arbitrary data associated with the matched elements. + * + * @param obj An object of key-value pairs of data to update. + */ + data(obj: { [key: string]: any; }): ChaiJQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * + * @param key Name of the data stored. + */ + data(key: string): any; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + */ + data(): any; + + /** + * Execute the next function on the queue for the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(queueName?: string): ChaiJQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. + */ + removeData(name: string): ChaiJQuery; + /** + * Remove a previously-stored piece of data. + * + * @param list An array of strings naming the pieces of data to delete. + */ + removeData(list: string[]): ChaiJQuery; + + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * + * @param type The type of queue that needs to be observed. (default: fx) + * @param target Object onto which the promise methods have to be attached + */ + promise(type?: string, target?: Object): JQueryPromise; + + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, complete?: Function): ChaiJQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. (default: swing) + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): ChaiJQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param options A map of additional options to pass to the method. + */ + animate(properties: Object, options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Set a timer to delay execution of subsequent items in the queue. + * + * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + delay(duration: number, queueName?: string): ChaiJQuery; + + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param options A map of additional options to pass to the method. + */ + fadeIn(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param options A map of additional options to pass to the method. + */ + fadeOut(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, complete?: Function): ChaiJQuery; + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): ChaiJQuery; + + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param options A map of additional options to pass to the method. + */ + fadeToggle(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. + * + * @param queue The name of the queue in which to stop animations. + */ + finish(queue?: string): ChaiJQuery; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + hide(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + show(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideDown(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideToggle(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideUp(options: JQueryAnimationOptions): ChaiJQuery; + + /** + * Stop the currently-running animation on the matched elements. + * + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(clearQueue?: boolean, jumpToEnd?: boolean): ChaiJQuery; + /** + * Stop the currently-running animation on the matched elements. + * + * @param queue The name of the queue in which to stop animations. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): ChaiJQuery; + + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, easing?: string, complete?: Function): ChaiJQuery; + /** + * Display or hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + toggle(options: JQueryAnimationOptions): ChaiJQuery; + /** + * Display or hide the matched elements. + * + * @param showOrHide A Boolean indicating whether to show or hide the elements. + */ + toggle(showOrHide: boolean): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, eventData: any, preventBubble: boolean): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, preventBubble: boolean): ChaiJQuery; + /** + * Attach a handler to an event for the elements. + * + * @param events An object containing one or more DOM event types and functions to execute for them. + */ + bind(events: any): ChaiJQuery; + + /** + * Trigger the "blur" event on an element + */ + blur(): ChaiJQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + blur(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "change" event on an element. + */ + change(): ChaiJQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + change(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "click" event on an element. + */ + click(): ChaiJQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + */ + click(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "dblclick" event on an element. + */ + dblclick(): ChaiJQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + dblclick(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "focus" event on an element. + */ + focus(): ChaiJQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focus(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusin(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusout(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * + * @param handlerIn A function to execute when the mouse pointer enters the element. + * @param handlerOut A function to execute when the mouse pointer leaves the element. + */ + hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + */ + hover(handlerInOut: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "keydown" event on an element. + */ + keydown(): ChaiJQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keydown(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + + /** + * Trigger the "keypress" event on an element. + */ + keypress(): ChaiJQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keypress(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + + /** + * Trigger the "keyup" event on an element. + */ + keyup(): ChaiJQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keyup(handler: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): ChaiJQuery; + + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + load(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mousedown" event on an element. + */ + mousedown(): ChaiJQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousedown(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseenter" event on an element. + */ + mouseenter(): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseleave" event on an element. + */ + mouseleave(): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mousemove" event on an element. + */ + mousemove(): ChaiJQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousemove(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseout" event on an element. + */ + mouseout(): ChaiJQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseout(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseover" event on an element. + */ + mouseover(): ChaiJQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseover(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Trigger the "mouseup" event on an element. + */ + mouseup(): ChaiJQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseup(handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): ChaiJQuery; + + /** + * Remove an event handler. + */ + off(): ChaiJQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove an event handler. + * + * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + */ + off(events: { [key: string]: any; }, selector?: string): ChaiJQuery; + + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, selector?: string, data?: any): ChaiJQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, data?: any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param data An object containing data that will be passed to the event handler. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, selector?: string, data?: any): ChaiJQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, data?: any): ChaiJQuery; + + + /** + * Specify a function to execute when the DOM is fully loaded. + * + * @param handler A function to execute after the DOM is ready. + */ + ready(handler: Function): ChaiJQuery; + + /** + * Trigger the "resize" event on an element. + */ + resize(): ChaiJQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + resize(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "scroll" event on an element. + */ + scroll(): ChaiJQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + scroll(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "select" event on an element. + */ + select(): ChaiJQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + select(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Trigger the "submit" event on an element. + */ + submit(): ChaiJQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + submit(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: any[]|Object): ChaiJQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: any[]|Object): ChaiJQuery; + + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(eventType: string, ...extraParameters: any[]): Object; + + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + */ + unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + */ + unbind(eventType: string, fls: boolean): ChaiJQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param evt A JavaScript event object as passed to an event handler. + */ + unbind(evt: any): ChaiJQuery; + + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + */ + undelegate(): ChaiJQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + */ + undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + */ + undelegate(selector: string, events: Object): ChaiJQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param namespace A string containing a namespace to unbind all events from. + */ + undelegate(namespace: string): ChaiJQuery; + + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + unload(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) + */ + context: Element; + + jquery: string; + + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + error(handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + error(eventData: any, handler: (eventObject: JQueryEventObject) => any): ChaiJQuery; + + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + */ + pushStack(elements: any[]): ChaiJQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param arguments The arguments that were passed in to the jQuery method (for serialization). + */ + pushStack(elements: any[], name: string, arguments: any[]): ChaiJQuery; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + after(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + append(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: JQuery|any[]|Element|string): ChaiJQuery; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + before(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Create a deep copy of the set of matched elements. + * + * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. + * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). + */ + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): ChaiJQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * param selector A selector expression that filters the set of matched elements to be removed. + */ + detach(selector?: string): ChaiJQuery; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + */ + empty(): ChaiJQuery; + + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: JQuery|any[]|Element|Text|string): ChaiJQuery; + + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: JQuery|any[]|Element|Text|string): ChaiJQuery; + + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): ChaiJQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + prepend(func: (index: number, html: string) => string|Element|JQuery): ChaiJQuery; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: JQuery|any[]|Element|string): ChaiJQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + */ + remove(selector?: string): ChaiJQuery; + + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: JQuery|any[]|Element|string): ChaiJQuery; + + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: JQuery|any[]|Element|Text|string): ChaiJQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param func A function that returns content with which to replace the set of matched elements. + */ + replaceWith(func: () => Element|JQuery): ChaiJQuery; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + */ + text(): string; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. + */ + text(text: string|number|boolean): ChaiJQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. + */ + text(func: (index: number, text: string) => string): ChaiJQuery; + + /** + * Retrieve all the elements contained in the jQuery set, as an array. + */ + toArray(): any[]; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + */ + unwrap(): ChaiJQuery; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: JQuery|Element|string): ChaiJQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrap(func: (index: number) => string|JQuery): ChaiJQuery; + + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: JQuery|Element|string): ChaiJQuery; + wrapAll(func: (index: number) => string): ChaiJQuery; + + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: JQuery|Element|string): ChaiJQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrapInner(func: (index: number) => string): ChaiJQuery; + + /** + * Iterate over a jQuery object, executing a function for each matched element. + * + * @param func A function to execute for each matched element. + */ + each(func: (index: number, elem: Element) => any): ChaiJQuery; + + /** + * Retrieve one of the elements matched by the jQuery object. + * + * @param index A zero-based integer indicating which element to retrieve. + */ + get(index: number): HTMLElement; + /** + * Retrieve the elements matched by the jQuery object. + */ + get(): any[]; + + /** + * Search for a given element from among the matched elements. + */ + index(): number; + /** + * Search for a given element from among the matched elements. + * + * @param selector A selector representing a jQuery collection in which to look for an element. + */ + index(selector: string|JQuery|Element): number; + + /** + * The number of elements in the jQuery object. + */ + length: number; + /** + * A selector representing selector passed to jQuery(), if any, when creating the original set. + * version deprecated: 1.7, removed: 1.9 + */ + selector: string; + [index: string]: any; + [index: number]: HTMLElement; + + /** + * Add elements to the set of matched elements. + * + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. + */ + add(selector: string, context?: Element): ChaiJQuery; + /** + * Add elements to the set of matched elements. + * + * @param elements One or more elements to add to the set of matched elements. + */ + add(...elements: Element[]): ChaiJQuery; + /** + * Add elements to the set of matched elements. + * + * @param html An HTML fragment to add to the set of matched elements. + */ + add(html: string): ChaiJQuery; + /** + * Add elements to the set of matched elements. + * + * @param obj An existing jQuery object to add to the set of matched elements. + */ + add(obj: JQuery): ChaiJQuery; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + children(selector?: string): ChaiJQuery; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + */ + closest(selector: string): ChaiJQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selector: string, context?: Element): ChaiJQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param obj A jQuery object to match elements against. + */ + closest(obj: JQuery): ChaiJQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param element An element to match elements against. + */ + closest(element: Element): ChaiJQuery; + + /** + * Get an array of all the elements and selectors matched against the current element up through the DOM tree. + * + * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selectors: any, context?: Element): any[]; + + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + */ + contents(): ChaiJQuery; + + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + */ + end(): ChaiJQuery; + + /** + * Reduce the set of matched elements to the one at the specified index. + * + * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. + * + */ + eq(index: number): ChaiJQuery; + + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param selector A string containing a selector expression to match the current set of elements against. + */ + filter(selector: string): ChaiJQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + filter(func: (index: number, element: Element) => any): ChaiJQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param element An element to match the current set of elements against. + */ + filter(element: Element): ChaiJQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + filter(obj: JQuery): ChaiJQuery; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param selector A string containing a selector expression to match elements against. + */ + find(selector: string): ChaiJQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param element An element to match elements against. + */ + find(element: Element): ChaiJQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param obj A jQuery object to match elements against. + */ + find(obj: JQuery): ChaiJQuery; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): ChaiJQuery; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + */ + has(selector: string): ChaiJQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + */ + has(contained: Element): ChaiJQuery; + + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + */ + is(selector: string): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + */ + is(func: (index: number, element: Element) => boolean): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + is(obj: JQuery): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + */ + is(elements: any): boolean; + + /** + * Reduce the set of matched elements to the final one in the set. + */ + last(): ChaiJQuery; + + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * + * @param callback A function object that will be invoked for each element in the current set. + */ + map(callback: (index: number, domElement: Element) => any): ChaiJQuery; + + /** + * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + next(selector?: string): ChaiJQuery; + + /** + * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + nextAll(selector?: string): ChaiJQuery; + + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(selector?: string, filter?: string): ChaiJQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(element?: Element, filter?: string): ChaiJQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(obj?: JQuery, filter?: string): ChaiJQuery; + + /** + * Remove elements from the set of matched elements. + * + * @param selector A string containing a selector expression to match elements against. + */ + not(selector: string): ChaiJQuery; + /** + * Remove elements from the set of matched elements. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + not(func: (index: number, element: Element) => boolean): ChaiJQuery; + /** + * Remove elements from the set of matched elements. + * + * @param elements One or more DOM elements to remove from the matched set. + */ + not(...elements: Element[]): ChaiJQuery; + /** + * Remove elements from the set of matched elements. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + not(obj: JQuery): ChaiJQuery; + + /** + * Get the closest ancestor element that is positioned. + */ + offsetParent(): ChaiJQuery; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parent(selector?: string): ChaiJQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parents(selector?: string): ChaiJQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(selector?: string, filter?: string): ChaiJQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(element?: Element, filter?: string): ChaiJQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(obj?: JQuery, filter?: string): ChaiJQuery; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prev(selector?: string): ChaiJQuery; + + /** + * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prevAll(selector?: string): ChaiJQuery; + + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(selector?: string, filter?: string): ChaiJQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(element?: Element, filter?: string): ChaiJQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(obj?: JQuery, filter?: string): ChaiJQuery; + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + siblings(selector?: string): ChaiJQuery; + + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + */ + slice(start: number, end?: number): ChaiJQuery; + + /** + * Show the queue of functions to be executed on the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(newQueue: Function[]): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(callback: Function): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(queueName: string, newQueue: Function[]): ChaiJQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(queueName: string, callback: Function): ChaiJQuery; + should: Chai.Assertion; +} diff --git a/chai-subset/chai-subset-tests.ts b/chai-subset/chai-subset-tests.ts new file mode 100644 index 000000000..8b88e5c6a --- /dev/null +++ b/chai-subset/chai-subset-tests.ts @@ -0,0 +1,62 @@ +/// + +import chai = require('chai'); +import chaiSubset = require('chai-subset'); + +chai.use(chaiSubset); +var expect = chai.expect; +var assert = chai.assert; + +function test_containSubset() { + var obj: Object = { + a: 'b', + c: 'd', + e: { + foo: 'bar', + baz: { + qux: 'quux' + } + } + }; + + expect(obj).to.containSubset({ + a: 'b', + e: { + baz: { + qux: 'quux' + } + } + }); + + obj.should.containSubset({ a: 'b' }); +} + +function test_notContainSubset() { + var obj: Object = { + a: 'b', + c: 'd', + e: { + foo: 'bar', + baz: { + qux: 'quux' + } + } + }; + + expect(obj).to.not.containSubset({ g: 'whatever' }); + obj.should.not.containSubset({ g: 'whatever' }); +} + +function test_arrayContainSubset() { + var list: Array = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; + + expect(list).to.containSubset([{a:'a', b: 'b'}]); + list.should.containSubset([{a:'a', b: 'b'}]); +} + +function test_arrayNotContainSubset() { + var list: Array = [{a: 'a', b: 'b'}, {v: 'f', d: {z: 'g'}} ]; + + expect(list).not.to.containSubset([{a:'a', b: 'bd'}]); + list.should.not.containSubset([{a:'a', b: 'bd'}]); +} diff --git a/chai-subset/chai-subset.d.ts b/chai-subset/chai-subset.d.ts new file mode 100644 index 000000000..44bbef9cc --- /dev/null +++ b/chai-subset/chai-subset.d.ts @@ -0,0 +1,21 @@ +// Type definitions for chai-subset 1.0.0 +// Project: https://github.com/e-conomic/chai-subset +// Definitions by: Sam Noedel +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Chai { + interface Assertion { + containSubset(obj: Object): Assertion; + } +} + +interface Object { + should: Chai.Assertion; +} + +declare module "chai-subset" { + function chaiSubset(chai: any, utils: any): void; + export = chaiSubset; +} diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index ddaa84ee2..c3f6fe06a 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1,4 +1,7 @@ /// +import chai = require('chai'); + +// ReSharper disable WrongExpressionStatement var expect = chai.expect; var assert = chai.assert; @@ -13,6 +16,7 @@ function assertion() { expect('foo').to.equal('foo'); } +// ReSharper disable once InconsistentNaming function _true() { expect(true).to.be.true; expect(false).to.not.be.true; @@ -20,7 +24,7 @@ function _true() { err(() => { expect('test').to.be.true; - }, "expected 'test' to be true") + }, 'expected \'test\' to be true'); } function ok() { @@ -31,11 +35,11 @@ function ok() { err(() => { expect('').to.be.ok; - }, "expected '' to be truthy"); + }, 'expected \'\' to be truthy'); err(() => { expect('test').to.not.be.ok; - }, "expected 'test' to be falsy"); + }, 'expected \'test\' to be falsy'); } function _false() { @@ -45,7 +49,7 @@ function _false() { err(() => { expect('').to.be.false; - }, "expected '' to be false") + }, 'expected \'\' to be false'); } function _null() { @@ -54,7 +58,7 @@ function _null() { err(() => { expect('').to.be.null; - }, "expected '' to be null") + }, 'expected \'\' to be null'); } function _undefined() { @@ -63,14 +67,13 @@ function _undefined() { err(() => { expect('').to.be.undefined; - }, "expected '' to be undefined") + }, 'expected \'\' to be undefined'); } function exist() { - var foo = 'bar' - , bar; + var foo = 'bar'; expect(foo).to.exist; - expect(bar).to.not.exist; + expect(void(0)).to.not.exist; } function arguments() { @@ -82,8 +85,7 @@ function arguments() { } function equal() { - var foo; - expect(undefined).to.equal(foo); + expect(undefined).to.equal(void(0)); } function _typeof() { @@ -91,7 +93,7 @@ function _typeof() { err(() => { expect('test').to.not.be.a('string'); - }, "expected 'test' not to be a string"); + }, 'expected \'test\' not to be a string'); expect(arguments).to.be.an('arguments'); @@ -103,24 +105,24 @@ function _typeof() { expect(new Object()).to.be.a('object'); expect({}).to.be.a('object'); expect([]).to.be.a('array'); - expect(function () { }).to.be.a('function'); + expect(() => { }).to.be.a('function'); expect(null).to.be.a('null'); err(() => { expect(5).to.not.be.a('number', 'blah'); - }, "blah: expected 5 not to be a number"); + }, 'blah: expected 5 not to be a number'); } +class Foo { } function _instanceof() { - function Foo() { } expect(new Foo()).to.be.an.instanceof(Foo); err(() => { expect(3).to.an.instanceof(Foo, 'blah'); - }, "blah: expected 3 to be an instance of Foo"); + }, 'blah: expected 3 to be an instance of Foo'); } -function within(start, finish) { +function within() { expect(5).to.be.within(5, 10); expect(5).to.be.within(3, 6); expect(5).to.be.within(3, 5); @@ -130,22 +132,22 @@ function within(start, finish) { err(() => { expect(5).to.not.be.within(4, 6, 'blah'); - }, "blah: expected 5 to not be within 4..6", 'blah'); + }, 'blah: expected 5 to not be within 4..6', 'blah'); err(() => { expect(10).to.be.within(50, 100, 'blah'); - }, "blah: expected 10 to be within 50..100"); + }, 'blah: expected 10 to be within 50..100'); err(() => { expect('foo').to.have.length.within(5, 7, 'blah'); - }, "blah: expected \'foo\' to have a length within 5..7"); + }, 'blah: expected \'foo\' to have a length within 5..7'); err(() => { expect([1, 2, 3]).to.have.length.within(5, 7, 'blah'); - }, "blah: expected [ 1, 2, 3 ] to have a length within 5..7"); + }, 'blah: expected [ 1, 2, 3 ] to have a length within 5..7'); } -function above(n) { +function above() { expect(5).to.be.above(2); expect(5).to.be.greaterThan(2); expect(5).to.not.be.above(5); @@ -155,22 +157,22 @@ function above(n) { err(() => { expect(5).to.be.above(6, 'blah'); - }, "blah: expected 5 to be above 6", 'blah'); + }, 'blah: expected 5 to be above 6', 'blah'); err(() => { expect(10).to.not.be.above(6, 'blah'); - }, "blah: expected 10 to be at most 6"); + }, 'blah: expected 10 to be at most 6'); err(() => { expect('foo').to.have.length.above(4, 'blah'); - }, "blah: expected \'foo\' to have a length above 4 but got 3"); + }, 'blah: expected \'foo\' to have a length above 4 but got 3'); err(() => { expect([1, 2, 3]).to.have.length.above(4, 'blah'); - }, "blah: expected [ 1, 2, 3 ] to have a length above 4 but got 3"); + }, 'blah: expected [ 1, 2, 3 ] to have a length above 4 but got 3'); } -function least(n) { +function least() { expect(5).to.be.at.least(2); expect(5).to.be.at.least(5); expect(5).to.not.be.at.least(6); @@ -179,26 +181,26 @@ function least(n) { err(() => { expect(5).to.be.at.least(6, 'blah'); - }, "blah: expected 5 to be at least 6", 'blah'); + }, 'blah: expected 5 to be at least 6', 'blah'); err(() => { expect(10).to.not.be.at.least(6, 'blah'); - }, "blah: expected 10 to be below 6"); + }, 'blah: expected 10 to be below 6'); err(() => { expect('foo').to.have.length.of.at.least(4, 'blah'); - }, "blah: expected \'foo\' to have a length at least 4 but got 3"); + }, 'blah: expected \'foo\' to have a length at least 4 but got 3'); err(() => { expect([1, 2, 3]).to.have.length.of.at.least(4, 'blah'); - }, "blah: expected [ 1, 2, 3 ] to have a length at least 4 but got 3"); + }, 'blah: expected [ 1, 2, 3 ] to have a length at least 4 but got 3'); err(() => { expect([1, 2, 3, 4]).to.not.have.length.of.at.least(4, 'blah'); - }, "blah: expected [ 1, 2, 3, 4 ] to have a length below 4"); + }, 'blah: expected [ 1, 2, 3, 4 ] to have a length below 4'); } -function below(n) { +function below() { expect(2).to.be.below(5); expect(2).to.be.lessThan(5); expect(2).to.not.be.below(2); @@ -208,22 +210,22 @@ function below(n) { err(() => { expect(6).to.be.below(5, 'blah'); - }, "blah: expected 6 to be below 5"); + }, 'blah: expected 6 to be below 5'); err(() => { expect(6).to.not.be.below(10, 'blah'); - }, "blah: expected 6 to be at least 10"); + }, 'blah: expected 6 to be at least 10'); err(() => { expect('foo').to.have.length.below(2, 'blah'); - }, "blah: expected \'foo\' to have a length below 2 but got 3"); + }, 'blah: expected \'foo\' to have a length below 2 but got 3'); err(() => { expect([1, 2, 3]).to.have.length.below(2, 'blah'); - }, "blah: expected [ 1, 2, 3 ] to have a length below 2 but got 3"); + }, 'blah: expected [ 1, 2, 3 ] to have a length below 2 but got 3'); } -function most(n) { +function most() { expect(2).to.be.at.most(5); expect(2).to.be.at.most(2); expect(2).to.not.be.at.most(1); @@ -233,39 +235,39 @@ function most(n) { err(() => { expect(6).to.be.at.most(5, 'blah'); - }, "blah: expected 6 to be at most 5"); + }, 'blah: expected 6 to be at most 5'); err(() => { expect(6).to.not.be.at.most(10, 'blah'); - }, "blah: expected 6 to be above 10"); + }, 'blah: expected 6 to be above 10'); err(() => { expect('foo').to.have.length.of.at.most(2, 'blah'); - }, "blah: expected \'foo\' to have a length at most 2 but got 3"); + }, 'blah: expected \'foo\' to have a length at most 2 but got 3'); err(() => { expect([1, 2, 3]).to.have.length.of.at.most(2, 'blah'); - }, "blah: expected [ 1, 2, 3 ] to have a length at most 2 but got 3"); + }, 'blah: expected [ 1, 2, 3 ] to have a length at most 2 but got 3'); err(() => { expect([1, 2]).to.not.have.length.of.at.most(2, 'blah'); - }, "blah: expected [ 1, 2 ] to have a length above 2"); + }, 'blah: expected [ 1, 2 ] to have a length above 2'); } -function match(regexp) { +function match() { expect('foobar').to.match(/^foo/); expect('foobar').to.not.match(/^bar/); err(() => { - expect('foobar').to.match(/^bar/i, 'blah') -}, "blah: expected 'foobar' to match /^bar/i"); + expect('foobar').to.match(/^bar/i, 'blah'); + }, 'blah: expected \'foobar\' to match /^bar/i'); err(() => { - expect('foobar').to.not.match(/^foo/i, 'blah') -}, "blah: expected 'foobar' not to match /^foo/i"); + expect('foobar').to.not.match(/^foo/i, 'blah'); + }, 'blah: expected \'foobar\' not to match /^foo/i'); } -function length2(n) { +function length2() { expect('test').to.have.length(4); expect('test').to.not.have.length(3); expect([1, 2, 3]).to.have.length(3); @@ -276,10 +278,10 @@ function length2(n) { err(() => { expect('asd').to.not.have.length(3, 'blah'); - }, "blah: expected 'asd' to not have a length of 3"); + }, 'blah: expected \'asd\' to not have a length of 3'); } -function eql(val) { +function eql() { expect('test').to.eql('test'); expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); expect(1).to.eql(1); @@ -290,8 +292,11 @@ function eql(val) { }, 'blah: expected 4 to deeply equal 3'); } +class Buffer { + constructor(arr: number[]) { + } +} function buffer() { - var Buffer; expect(new Buffer([1])).to.eql(new Buffer([1])); err(() => { @@ -299,7 +304,7 @@ function buffer() { }, 'expected to deeply equal '); } -function equal2(val) { +function equal2() { expect('test').to.equal('test'); expect(1).to.equal(1); @@ -309,10 +314,10 @@ function equal2(val) { err(() => { expect('4').to.equal(4, 'blah'); - }, "blah: expected '4' to equal 4"); + }, 'blah: expected \'4\' to equal 4'); } -function deepEqual(val) { +function deepEqual() { expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); expect({ foo: 'bar' }).not.to.deep.equal({ foo: 'baz' }); } @@ -329,21 +334,25 @@ function deepEqual2() { expect(/a/m).not.to.deep.equal(/b/m); } -function deepEqual3(Date) { - var a = new Date(1, 2, 3) - , b = new Date(4, 5, 6); +// ReSharper disable once InconsistentNaming +function deepEqual3() { + var a = new Date(1, 2, 3); + var b = new Date(4, 5, 6); expect(a).to.deep.equal(a); expect(a).not.to.deep.equal(b); expect(a).not.to.deep.equal({}); } -function deepInclude(val) { +function deepInclude() { expect(['foo', 'bar']).to.deep.include(['bar', 'foo']); expect(['foo', 'bar']).not.to.deep.equal(['foo', 'baz' ]); } +class FakeArgs { + length: number; +} + function empty() { - function FakeArgs() { }; FakeArgs.prototype.length = 0; expect('').to.be.empty; @@ -357,38 +366,38 @@ function empty() { err(() => { expect('').not.to.be.empty; - }, "expected \'\' not to be empty"); + }, 'expected \'\' not to be empty'); err(() => { expect('foo').to.be.empty; - }, "expected \'foo\' to be empty"); + }, 'expected \'foo\' to be empty'); err(() => { expect([]).not.to.be.empty; - }, "expected [] not to be empty"); + }, 'expected [] not to be empty'); err(() => { expect(['foo']).to.be.empty; - }, "expected [ \'foo\' ] to be empty"); + }, 'expected [ \'foo\' ] to be empty'); err(() => { expect(new FakeArgs).not.to.be.empty; - }, "expected { length: 0 } not to be empty"); + }, 'expected { length: 0 } not to be empty'); err(() => { expect({ arguments: 0 }).to.be.empty; - }, "expected { arguments: 0 } to be empty"); + }, 'expected { arguments: 0 } to be empty'); err(() => { expect({}).not.to.be.empty; - }, "expected {} not to be empty"); + }, 'expected {} not to be empty'); err(() => { expect({ foo: 'bar' }).to.be.empty; - }, "expected { foo: \'bar\' } to be empty"); + }, 'expected { foo: \'bar\' } to be empty'); } -function property(name) { +function property() { expect('test').to.have.property('length'); expect(4).to.not.have.property('length'); @@ -399,14 +408,14 @@ function property(name) { err(() => { expect('asd').to.have.property('foo'); - }, "expected 'asd' to have a property 'foo'"); + }, 'expected \'asd\' to have a property \'foo\''); err(() => { expect({ foo: { bar: 'baz' } }) .to.have.property('foo.bar'); - }, "expected { foo: { bar: 'baz' } } to have a property 'foo.bar'"); + }, 'expected { foo: { bar: \'baz\' } } to have a property \'foo.bar\''); } -function deepProperty(name) { +function deepProperty() { expect({ 'foo.bar': 'baz' }) .to.not.have.deep.property('foo.bar'); expect({ foo: { bar: 'baz' } }) @@ -415,56 +424,56 @@ function deepProperty(name) { err(() => { expect({ 'foo.bar': 'baz' }) .to.have.deep.property('foo.bar'); - }, "expected { 'foo.bar': 'baz' } to have a deep property 'foo.bar'"); + }, 'expected { \'foo.bar\': \'baz\' } to have a deep property \'foo.bar\''); } -function property2(name, val) { +function property2() { expect('test').to.have.property('length', 4); expect('asd').to.have.property('constructor', String); err(() => { expect('asd').to.have.property('length', 4, 'blah'); - }, "blah: expected 'asd' to have a property 'length' of 4, but got 3"); + }, 'blah: expected \'asd\' to have a property \'length\' of 4, but got 3'); err(() => { expect('asd').to.not.have.property('length', 3, 'blah'); - }, "blah: expected 'asd' to not have a property 'length' of 3"); + }, 'blah: expected \'asd\' to not have a property \'length\' of 3'); err(() => { expect('asd').to.not.have.property('foo', 3, 'blah'); - }, "blah: 'asd' has no property 'foo'"); + }, 'blah: \'asd\' has no property \'foo\''); err(() => { expect('asd').to.have.property('constructor', Number, 'blah'); - }, "blah: expected 'asd' to have a property 'constructor' of [Function: Number], but got [Function: String]"); + }, 'blah: expected \'asd\' to have a property \'constructor\' of [Function: Number], but got [Function: String]'); } -function deepProperty2(name, val) { +function deepProperty2() { expect({ foo: { bar: 'baz' } }) .to.have.deep.property('foo.bar', 'baz'); err(() => { expect({ foo: { bar: 'baz' } }) .to.have.deep.property('foo.bar', 'quux', 'blah'); - }, "blah: expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'quux', but got 'baz'"); + }, 'blah: expected { foo: { bar: \'baz\' } } to have a deep property \'foo.bar\' of \'quux\', but got \'baz\''); err(() => { expect({ foo: { bar: 'baz' } }) .to.not.have.deep.property('foo.bar', 'baz', 'blah'); - }, "blah: expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); + }, 'blah: expected { foo: { bar: \'baz\' } } to not have a deep property \'foo.bar\' of \'baz\''); err(() => { expect({ foo: 5 }) .to.not.have.deep.property('foo.bar', 'baz', 'blah'); - }, "blah: { foo: 5 } has no deep property 'foo.bar'"); + }, 'blah: { foo: 5 } has no deep property \'foo.bar\''); } -function ownProperty(name) { +function ownProperty() { expect('test').to.have.ownProperty('length'); expect('test').to.haveOwnProperty('length'); expect({ length: 12 }).to.have.ownProperty('length'); err(() => { expect({ length: 12 }).to.not.have.ownProperty('length', 'blah'); - }, "blah: expected { length: 12 } to not have own property 'length'"); + }, 'blah: expected { length: 12 } to not have own property \'length\''); } function string() { @@ -474,15 +483,15 @@ function string() { err(() => { expect(3).to.have.string('baz'); - }, "expected 3 to be a string"); + }, 'expected 3 to be a string'); err(() => { expect('foobar').to.have.string('baz', 'blah'); - }, "blah: expected 'foobar' to contain 'baz'"); + }, 'blah: expected \'foobar\' to contain \'baz\''); err(() => { expect('foobar').to.not.have.string('bar', 'blah'); - }, "blah: expected 'foobar' to not contain 'bar'"); + }, 'blah: expected \'foobar\' to not contain \'bar\''); } function include() { @@ -495,14 +504,14 @@ function include() { err(() => { expect(['foo']).to.include('bar', 'blah'); - }, "blah: expected [ 'foo' ] to include 'bar'"); + }, 'blah: expected [ \'foo\' ] to include \'bar\''); err(() => { expect(['bar', 'foo']).to.not.include('foo', 'blah'); - }, "blah: expected [ 'bar', 'foo' ] to not include 'foo'"); + }, 'blah: expected [ \'bar\', \'foo\' ] to not include \'foo\''); } -function keys(array) { +function keys() { expect({ foo: 1 }).to.have.keys(['foo']); expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']); expect({ foo: 1, bar: 2 }).to.have.keys('foo', 'bar'); @@ -524,51 +533,51 @@ function keys(array) { err(() => { expect({ foo: 1 }).to.have.keys(); - }, "keys required"); + }, 'keys required'); err(() => { expect({ foo: 1 }).to.have.keys([]); - }, "keys required"); + }, 'keys required'); err(() => { expect({ foo: 1 }).to.not.have.keys([]); - }, "keys required"); + }, 'keys required'); err(() => { expect({ foo: 1 }).to.contain.keys([]); - }, "keys required"); + }, 'keys required'); err(() => { expect({ foo: 1 }).to.have.keys(['bar']); - }, "expected { foo: 1 } to have key 'bar'"); + }, 'expected { foo: 1 } to have key \'bar\''); err(() => { expect({ foo: 1 }).to.have.keys(['bar', 'baz']); - }, "expected { foo: 1 } to have keys 'bar', and 'baz'"); + }, 'expected { foo: 1 } to have keys \'bar\', and \'baz\''); err(() => { expect({ foo: 1 }).to.have.keys(['foo', 'bar', 'baz']); - }, "expected { foo: 1 } to have keys 'foo', 'bar', and 'baz'"); + }, 'expected { foo: 1 } to have keys \'foo\', \'bar\', and \'baz\''); err(() => { expect({ foo: 1 }).to.not.have.keys(['foo']); - }, "expected { foo: 1 } to not have key 'foo'"); + }, 'expected { foo: 1 } to not have key \'foo\''); err(() => { expect({ foo: 1 }).to.not.have.keys(['foo']); - }, "expected { foo: 1 } to not have key 'foo'"); + }, 'expected { foo: 1 } to not have key \'foo\''); err(() => { expect({ foo: 1, bar: 2 }).to.not.have.keys(['foo', 'bar']); - }, "expected { foo: 1, bar: 2 } to not have keys 'foo', and 'bar'"); + }, 'expected { foo: 1, bar: 2 } to not have keys \'foo\', and \'bar\''); err(() => { expect({ foo: 1 }).to.not.contain.keys(['foo']); - }, "expected { foo: 1 } to not contain key 'foo'"); + }, 'expected { foo: 1 } to not contain key \'foo\''); err(() => { expect({ foo: 1 }).to.contain.keys('foo', 'bar'); - }, "expected { foo: 1 } to contain keys 'foo', and 'bar'"); + }, 'expected { foo: 1 } to contain keys \'foo\', and \'bar\''); } function chaining() { @@ -577,23 +586,21 @@ function chaining() { err(() => { expect(tea).to.have.property('extras').with.lengthOf(4); - }, "expected [ 'milk', 'sugar', 'smile' ] to have a length of 4 but got 3"); + }, 'expected [ \'milk\', \'sugar\', \'smile\' ] to have a length of 4 but got 3'); expect(tea).to.be.a('object').and.have.property('name', 'chai'); } +class PoorlyConstructedError {} function _throw() { // See GH-45: some poorly-constructed custom errors don't have useful names // on either their constructor or their constructor prototype, but instead // only set the name inside the constructor itself. - var PoorlyConstructedError = () => { - this.name = 'PoorlyConstructedError'; - }; PoorlyConstructedError.prototype = Object.create(Error.prototype); var specificError = new RangeError('boo'); - var goodFn = () => { 1 == 1; } + var goodFn = () => { } , badFn = () => { throw new Error('testing'); } , refErrFn = () => { throw new ReferenceError('hello'); } , ickyErrFn = () => { throw new PoorlyConstructedError(); } @@ -627,39 +634,39 @@ function _throw() { err(() => { expect(goodFn).to.throw(); - }, "expected [Function] to throw an error"); + }, 'expected [Function] to throw an error'); err(() => { expect(goodFn).to.throw(ReferenceError); - }, "expected [Function] to throw ReferenceError"); + }, 'expected [Function] to throw ReferenceError'); err(() => { expect(goodFn).to.throw(specificError); - }, "expected [Function] to throw [RangeError: boo]"); + }, 'expected [Function] to throw [RangeError: boo]'); err(() => { expect(badFn).to.not.throw(); - }, "expected [Function] to not throw an error but [Error: testing] was thrown"); + }, 'expected [Function] to not throw an error but [Error: testing] was thrown'); err(() => { expect(badFn).to.throw(ReferenceError); - }, "expected [Function] to throw 'ReferenceError' but [Error: testing] was thrown"); + }, 'expected [Function] to throw \'ReferenceError\' but [Error: testing] was thrown'); err(() => { expect(badFn).to.throw(specificError); - }, "expected [Function] to throw [RangeError: boo] but [Error: testing] was thrown"); + }, 'expected [Function] to throw [RangeError: boo] but [Error: testing] was thrown'); err(() => { expect(badFn).to.not.throw(Error); - }, "expected [Function] to not throw 'Error' but [Error: testing] was thrown"); + }, 'expected [Function] to not throw \'Error\' but [Error: testing] was thrown'); err(() => { expect(refErrFn).to.not.throw(ReferenceError); - }, "expected [Function] to not throw 'ReferenceError' but [ReferenceError: hello] was thrown"); + }, 'expected [Function] to not throw \'ReferenceError\' but [ReferenceError: hello] was thrown'); err(() => { expect(badFn).to.throw(PoorlyConstructedError); - }, "expected [Function] to throw 'PoorlyConstructedError' but [Error: testing] was thrown"); + }, 'expected [Function] to throw \'PoorlyConstructedError\' but [Error: testing] was thrown'); err(() => { expect(ickyErrFn).to.not.throw(PoorlyConstructedError); @@ -671,37 +678,37 @@ function _throw() { err(() => { expect(specificErrFn).to.throw(new ReferenceError('eek')); - }, "expected [Function] to throw [ReferenceError: eek] but [RangeError: boo] was thrown"); + }, 'expected [Function] to throw [ReferenceError: eek] but [RangeError: boo] was thrown'); err(() => { expect(specificErrFn).to.not.throw(specificError); - }, "expected [Function] to not throw [RangeError: boo]"); + }, 'expected [Function] to not throw [RangeError: boo]'); err(() => { expect(badFn).to.not.throw(/testing/); - }, "expected [Function] to throw error not matching /testing/"); + }, 'expected [Function] to throw error not matching /testing/'); err(() => { expect(badFn).to.throw(/hello/); - }, "expected [Function] to throw error matching /hello/ but got 'testing'"); + }, 'expected [Function] to throw error matching /hello/ but got \'testing\''); err(() => { expect(badFn).to.throw(Error, /hello/, 'blah'); - }, "blah: expected [Function] to throw error matching /hello/ but got 'testing'"); + }, 'blah: expected [Function] to throw error matching /hello/ but got \'testing\''); err(() => { expect(badFn).to.throw(Error, 'hello', 'blah'); - }, "blah: expected [Function] to throw error including 'hello' but got 'testing'"); + }, 'blah: expected [Function] to throw error including \'hello\' but got \'testing\''); } function use(){ - chai.use(function (_chai, utils) { + // ReSharper disable once InconsistentNaming + chai.use((_chai) => { _chai.can.use.any(); }); } function respondTo() { - function Foo() {}; var bar = {}; expect(Foo).to.respondTo('bar'); @@ -721,15 +728,15 @@ function respondTo() { } function satisfy() { - function matcher(num) { + function matcher(num: number) { return num === 1; - }; + } expect(1).to.satisfy(matcher); err(() => { expect(2).to.satisfy(matcher, 'blah'); - }, "blah: expected 2 to satisfy [Function: matcher]"); + }, 'blah: expected 2 to satisfy [Function: matcher]'); } function closeTo() { @@ -739,11 +746,11 @@ function closeTo() { err(() => { expect(2).to.be.closeTo(1.0, 0.5, 'blah'); - }, "blah: expected 2 to be close to 1 +/- 0.5"); + }, 'blah: expected 2 to be close to 1 +/- 0.5'); err(() => { expect(-10).to.be.closeTo(20, 29, 'blah'); - }, "blah: expected -10 to be close to 20 +/- 29"); + }, 'blah: expected -10 to be close to 20 +/- 29'); } function includeMembers() { @@ -779,617 +786,611 @@ declare function suite(description: string, action: Function):void; declare function test(description: string, action: Function):void; interface FieldObj { - field: any; -} -class Foo { - constructor() { - - } + field: any; } class CrashyObject { - inspect (): void { - throw new Error("Arg's inspect() called even though the test passed"); - } + inspect (): void { + throw new Error('Arg\'s inspect() called even though the test passed'); + } } -suite('assert', function () { +suite('assert', () => { - test('assert', function () { - var foo = 'bar'; - assert(foo == 'bar', "expected foo to equal `bar`"); + test('assert', () => { + var foo = 'bar'; + assert(foo === 'bar', 'expected foo to equal `bar`'); - err(function () { - assert(foo == 'baz', "expected foo to equal `bar`"); - }, "expected foo to equal `bar`"); - }); + err(() => { + assert(foo === 'baz', 'expected foo to equal `bar`'); + }, 'expected foo to equal `bar`'); + }); - test('isTrue', function () { - assert.isTrue(true); - - err(function () { - assert.isTrue(false); - }, "expected false to be true"); + test('isTrue', () => { + assert.isTrue(true); - err(function () { - assert.isTrue(1); - }, "expected 1 to be true"); - - err(function () { - assert.isTrue('test'); - }, "expected 'test' to be true"); - }); + err(() => { + assert.isTrue(false); + }, 'expected false to be true'); - test('ok', function () { - assert.ok(true); - assert.ok(1); - assert.ok('test'); - - err(function () { - assert.ok(false); - }, "expected false to be truthy"); - - err(function () { - assert.ok(0); - }, "expected 0 to be truthy"); - - err(function () { - assert.ok(''); - }, "expected '' to be truthy"); - }); - - test('isFalse', function () { - assert.isFalse(false); - - err(function () { - assert.isFalse(true); - }, "expected true to be false"); - - err(function () { - assert.isFalse(0); - }, "expected 0 to be false"); - }); + err(() => { + assert.isTrue(1); + }, 'expected 1 to be true'); - test('equal', function () { - var foo: any; - assert.equal(foo, undefined); - }); + err(() => { + assert.isTrue('test'); + }, 'expected \'test\' to be true'); + }); - test('typeof / notTypeOf', function () { - assert.typeOf('test', 'string'); - assert.typeOf(true, 'boolean'); - assert.typeOf(5, 'number'); + test('ok', () => { + assert.ok(true); + assert.ok(1); + assert.ok('test'); + + err(() => { + assert.ok(false); + }, 'expected false to be truthy'); + + err(() => { + assert.ok(0); + }, 'expected 0 to be truthy'); + + err(() => { + assert.ok(''); + }, 'expected \'\' to be truthy'); + }); + + test('isFalse', () => { + assert.isFalse(false); + + err(() => { + assert.isFalse(true); + }, 'expected true to be false'); + + err(() => { + assert.isFalse(0); + }, 'expected 0 to be false'); + }); - err(function () { - assert.typeOf(5, 'string'); - }, "expected 5 to be a string"); + test('equal', () => { + assert.equal(void(0), undefined); + }); - }); + test('typeof / notTypeOf', () => { + assert.typeOf('test', 'string'); + assert.typeOf(true, 'boolean'); + assert.typeOf(5, 'number'); - test('notTypeOf', function () { - assert.notTypeOf('test', 'number'); - - err(function () { - assert.notTypeOf(5, 'number'); - }, "expected 5 not to be a number"); - }); + err(() => { + assert.typeOf(5, 'string'); + }, 'expected 5 to be a string'); - test('instanceOf', function () { - assert.instanceOf(new Foo(), Foo); - - err(function () { - assert.instanceOf(5, Foo); - }, "expected 5 to be an instance of Foo"); - assert.instanceOf(new CrashyObject(), CrashyObject); - }); - - test('notInstanceOf', function () { - assert.notInstanceOf(new Foo(), String); - - err(function () { - assert.notInstanceOf(new Foo(), Foo); - }, "expected {} to not be an instance of Foo"); - }); - - test('isObject', function () { - assert.isObject({}); - assert.isObject(new Foo()); - - err(function () { - assert.isObject(true); - }, "expected true to be an object"); - - err(function () { - assert.isObject(Foo); - }, "expected [Function: Foo] to be an object"); - - err(function () { - assert.isObject('foo'); - }, "expected 'foo' to be an object"); - }); - - test('isNotObject', function () { - assert.isNotObject(5); - - err(function () { - assert.isNotObject({}); - }, "expected {} not to be an object"); - }); - - test('notEqual', function () { - assert.notEqual(3, 4); - - err(function () { - assert.notEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('strictEqual', function () { - assert.strictEqual('foo', 'foo'); - - err(function () { - assert.strictEqual('5', 5); - }, "expected \'5\' to equal 5"); - }); - - test('notStrictEqual', function () { - assert.notStrictEqual(5, '5'); - - err(function () { - assert.notStrictEqual(5, 5); - }, "expected 5 to not equal 5"); - }); - - test('deepEqual', function () { - assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); - - err(function () { - assert.deepEqual({tea: 'chai'}, {tea: 'black'}); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - - var obja = Object.create({ tea: 'chai' }) - , objb = Object.create({ tea: 'chai' }); - - assert.deepEqual(obja, objb); - - var obj1 = Object.create({tea: 'chai'}) - , obj2 = Object.create({tea: 'black'}); - - err(function () { - assert.deepEqual(obj1, obj2); - }, "expected { tea: \'chai\' } to deeply equal { tea: \'black\' }"); - }); - - test('deepEqual (ordering)', function () { - var a = { a: 'b', c: 'd' } - , b = { c: 'd', a: 'b' }; - assert.deepEqual(a, b); - }); - - test('deepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = {}; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.deepEqual(circularObject, secondCircularObject); - - err(function () { - secondCircularObject.field2 = secondCircularObject; - assert.deepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to deeply equal { Object (field, field2) }"); - }); - - test('notDeepEqual', function () { - assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); - err(function () { - assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); - }, "expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }"); - }); - - test('notDeepEqual (circular)', function () { - var circularObject:any = {} - , secondCircularObject:any = { tea: 'jasmine' }; - circularObject.field = circularObject; - secondCircularObject.field = secondCircularObject; - - assert.notDeepEqual(circularObject, secondCircularObject); - - err(function () { - delete secondCircularObject.tea; - assert.notDeepEqual(circularObject, secondCircularObject); - }, "expected { field: [Circular] } to not deeply equal { field: [Circular] }"); - }); - - test('isNull', function () { - assert.isNull(null); - - err(function () { - assert.isNull(undefined); - }, "expected undefined to equal null"); - }); - - test('isNotNull', function () { - assert.isNotNull(undefined); - - err(function () { - assert.isNotNull(null); - }, "expected null to not equal null"); - }); - - test('isUndefined', function () { - assert.isUndefined(undefined); - - err(function () { - assert.isUndefined(null); - }, "expected null to equal undefined"); - }); - - test('isDefined', function () { - assert.isDefined(null); - - err(function () { - assert.isDefined(undefined); - }, "expected undefined to not equal undefined"); - }); - - test('isFunction', function () { - var func = function () { - }; - assert.isFunction(func); - - err(function () { - assert.isFunction({}); - }, "expected {} to be a function"); - }); - - test('isNotFunction', function () { - assert.isNotFunction(5); - - err(function () { - assert.isNotFunction(function () { - }); - }, "expected [Function] not to be a function"); - }); - - test('isArray', function () { - assert.isArray([]); - assert.isArray(new Array()); - - err(function () { - assert.isArray({}); - }, "expected {} to be an array"); - }); - - test('isNotArray', function () { - assert.isNotArray(3); - - err(function () { - assert.isNotArray([]); - }, "expected [] not to be an array"); - - err(function () { - assert.isNotArray(new Array()); - }, "expected [] not to be an array"); - }); - - test('isString', function () { - assert.isString('Foo'); - assert.isString(new String('foo')); - - err(function () { - assert.isString(1); - }, "expected 1 to be a string"); - }); - - test('isNotString', function () { - assert.isNotString(3); - assert.isNotString([ 'hello' ]); - - err(function () { - assert.isNotString('hello'); - }, "expected 'hello' not to be a string"); - }); - - test('isNumber', function () { - assert.isNumber(1); - assert.isNumber(Number('3')); - - err(function () { - assert.isNumber('1'); - }, "expected \'1\' to be a number"); - }); - - test('isNotNumber', function () { - assert.isNotNumber('hello'); - assert.isNotNumber([ 5 ]); - - err(function () { - assert.isNotNumber(4); - }, "expected 4 not to be a number"); - }); - - test('isBoolean', function () { - assert.isBoolean(true); - assert.isBoolean(false); - - err(function () { - assert.isBoolean('1'); - }, "expected \'1\' to be a boolean"); - }); - - test('isNotBoolean', function () { - assert.isNotBoolean('true'); - - err(function () { - assert.isNotBoolean(true); - }, "expected true not to be a boolean"); - - err(function () { - assert.isNotBoolean(false); - }, "expected false not to be a boolean"); - }); - - test('include', function () { - assert.include('foobar', 'bar'); - assert.include([ 1, 2, 3], 3); - - err(function () { - assert.include('foobar', 'baz'); - }, "expected \'foobar\' to contain \'baz\'"); - - err(function () { - assert.include(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('notInclude', function () { - assert.notInclude('foobar', 'baz'); - assert.notInclude([ 1, 2, 3 ], 4); - - err(function () { - assert.notInclude('foobar', 'bar'); - }, "expected \'foobar\' to not contain \'bar\'"); - - err(function () { - assert.notInclude(undefined, 'bar'); - }, "expected an array or string"); - }); - - test('lengthOf', function () { - assert.lengthOf([1, 2, 3], 3); - assert.lengthOf('foobar', 6); - - err(function () { - assert.lengthOf('foobar', 5); - }, "expected 'foobar' to have a length of 5 but got 6"); - - err(function () { - assert.lengthOf(1, 5); - }, "expected 1 to have a property \'length\'"); - }); - - test('match', function () { - assert.match('foobar', /^foo/); - assert.notMatch('foobar', /^bar/); - - err(function () { - assert.match('foobar', /^bar/i); - }, "expected 'foobar' to match /^bar/i"); - - err(function () { - assert.notMatch('foobar', /^foo/i); - }, "expected 'foobar' not to match /^foo/i"); - }); - - test('property', function () { - var obj = { foo: { bar: 'baz' } }; - var simpleObj = { foo: 'bar' }; - assert.property(obj, 'foo'); - assert.deepProperty(obj, 'foo.bar'); - assert.notProperty(obj, 'baz'); - assert.notProperty(obj, 'foo.bar'); - assert.notDeepProperty(obj, 'foo.baz'); - assert.deepPropertyVal(obj, 'foo.bar', 'baz'); - assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); - - err(function () { - assert.property(obj, 'baz'); - }, "expected { foo: { bar: 'baz' } } to have a property 'baz'"); - - err(function () { - assert.deepProperty(obj, 'foo.baz'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.baz'"); - - err(function () { - assert.notProperty(obj, 'foo'); - }, "expected { foo: { bar: 'baz' } } to not have property 'foo'"); - - err(function () { - assert.notDeepProperty(obj, 'foo.bar'); - }, "expected { foo: { bar: 'baz' } } to not have deep property 'foo.bar'"); - - err(function () { - assert.propertyVal(simpleObj, 'foo', 'ball'); - }, "expected { foo: 'bar' } to have a property 'foo' of 'ball', but got 'bar'"); - - err(function () { - assert.deepPropertyVal(obj, 'foo.bar', 'ball'); - }, "expected { foo: { bar: 'baz' } } to have a deep property 'foo.bar' of 'ball', but got 'baz'"); - - err(function () { - assert.propertyNotVal(simpleObj, 'foo', 'bar'); - }, "expected { foo: 'bar' } to not have a property 'foo' of 'bar'"); - - err(function () { - assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); - }, "expected { foo: { bar: 'baz' } } to not have a deep property 'foo.bar' of 'baz'"); - }); - - test('throws', function () { - assert.throws(function () { - throw new Error('foo'); - }); - assert.throws(function () { - throw new Error('bar'); - }, 'bar'); - assert.throws(function () { - throw new Error('bar'); - }, /bar/); - assert.throws(function () { - throw new Error('bar'); - }, Error); - assert.throws(function () { - throw new Error('bar'); - }, Error, 'bar'); - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, Error, 'bar'); - }, "expected [Function] to throw error including 'bar' but got 'foo'") - - err(function () { - assert.throws(function () { - throw new Error('foo') - }, TypeError, 'bar'); - }, "expected [Function] to throw 'TypeError' but [Error: foo] was thrown") - - err(function () { - assert.throws(function () { - }); - }, "expected [Function] to throw an error"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, 'bar'); - }, "expected [Function] to throw error including 'bar' but got ''"); - - err(function () { - assert.throws(function () { - throw new Error('') - }, /bar/); - }, "expected [Function] to throw error matching /bar/ but got ''"); - }); - - test('doesNotThrow', function () { - assert.doesNotThrow(function () { - }); - assert.doesNotThrow(function () { - }, 'foo'); - - err(function () { - assert.doesNotThrow(function () { - throw new Error('foo'); - }); - }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); - }); - - test('ifError', function () { - assert.ifError(false); - assert.ifError(null); - assert.ifError(undefined); - - err(function () { - assert.ifError('foo'); - }, "expected \'foo\' to be falsy"); - }); - - test('operator', function () { - assert.operator(1, '<', 2); - assert.operator(2, '>', 1); - assert.operator(1, '==', 1); - assert.operator(1, '<=', 1); - assert.operator(1, '>=', 1); - assert.operator(1, '!=', 2); - assert.operator(1, '!==', 2); - - err(function () { - assert.operator(1, '=', 2); - }, 'Invalid operator "="'); - - err(function () { - assert.operator(2, '<', 1); - }, "expected 2 to be < 1"); - - err(function () { - assert.operator(1, '>', 2); - }, "expected 1 to be > 2"); - - err(function () { - assert.operator(1, '==', 2); - }, "expected 1 to be == 2"); - - err(function () { - assert.operator(2, '<=', 1); - }, "expected 2 to be <= 1"); - - err(function () { - assert.operator(1, '>=', 2); - }, "expected 1 to be >= 2"); - - err(function () { - assert.operator(1, '!=', 1); - }, "expected 1 to be != 1"); - - err(function () { - assert.operator(1, '!==', '1'); - }, "expected 1 to be !== \'1\'"); - }); - - test('closeTo', function () { - assert.closeTo(1.5, 1.0, 0.5); - assert.closeTo(10, 20, 20); - assert.closeTo(-10, 20, 30); - - err(function () { - assert.closeTo(2, 1.0, 0.5); - }, "expected 2 to be close to 1 +/- 0.5"); - - err(function () { - assert.closeTo(-10, 20, 29); - }, "expected -10 to be close to 20 +/- 29"); - }); - - test('members', function () { - assert.includeMembers([1, 2, 3], [2, 3]); - assert.includeMembers([1, 2, 3], []); - assert.includeMembers([1, 2, 3], [3]); - - err(function () { - assert.includeMembers([5, 6], [7, 8]); - }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); - - err(function () { - assert.includeMembers([5, 6], [5, 6, 0]); - }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); - }); - - test('memberEquals', function () { - assert.sameMembers([], []); - assert.sameMembers([1, 2, 3], [3, 2, 1]); - assert.sameMembers([4, 2], [4, 2]); - - err(function () { - assert.sameMembers([], [1, 2]); - }, 'expected [] to have the same members as [ 1, 2 ]'); - - err(function () { - assert.sameMembers([1, 54], [6, 1, 54]); - }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); - }); + }); + + test('notTypeOf', () => { + assert.notTypeOf('test', 'number'); + + err(() => { + assert.notTypeOf(5, 'number'); + }, 'expected 5 not to be a number'); + }); + + test('instanceOf', () => { + assert.instanceOf(new Foo(), Foo); + + err(() => { + assert.instanceOf(5, Foo); + }, 'expected 5 to be an instance of Foo'); + assert.instanceOf(new CrashyObject(), CrashyObject); + }); + + test('notInstanceOf', () => { + assert.notInstanceOf(new Foo(), String); + + err(() => { + assert.notInstanceOf(new Foo(), Foo); + }, 'expected {} to not be an instance of Foo'); + }); + + test('isObject', () => { + assert.isObject({}); + assert.isObject(new Foo()); + + err(() => { + assert.isObject(true); + }, 'expected true to be an object'); + + err(() => { + assert.isObject(Foo); + }, 'expected [Function: Foo] to be an object'); + + err(() => { + assert.isObject('foo'); + }, 'expected \'foo\' to be an object'); + }); + + test('isNotObject', () => { + assert.isNotObject(5); + + err(() => { + assert.isNotObject({}); + }, 'expected {} not to be an object'); + }); + + test('notEqual', () => { + assert.notEqual(3, 4); + + err(() => { + assert.notEqual(5, 5); + }, 'expected 5 to not equal 5'); + }); + + test('strictEqual', () => { + assert.strictEqual('foo', 'foo'); + + err(() => { + assert.strictEqual('5', 5); + }, 'expected \'5\' to equal 5'); + }); + + test('notStrictEqual', () => { + assert.notStrictEqual(5, '5'); + + err(() => { + assert.notStrictEqual(5, 5); + }, 'expected 5 to not equal 5'); + }); + + test('deepEqual', () => { + assert.deepEqual({tea: 'chai'}, {tea: 'chai'}); + + err(() => { + assert.deepEqual({tea: 'chai'}, {tea: 'black'}); + }, 'expected { tea: \'chai\' } to deeply equal { tea: \'black\' }'); + + var obja = Object.create({ tea: 'chai' }) + , objb = Object.create({ tea: 'chai' }); + + assert.deepEqual(obja, objb); + + var obj1 = Object.create({tea: 'chai'}) + , obj2 = Object.create({tea: 'black'}); + + err(() => { + assert.deepEqual(obj1, obj2); + }, 'expected { tea: \'chai\' } to deeply equal { tea: \'black\' }'); + }); + + test('deepEqual (ordering)', () => { + var a = { a: 'b', c: 'd' } + , b = { c: 'd', a: 'b' }; + assert.deepEqual(a, b); + }); + + test('deepEqual (circular)', () => { + var circularObject:any = {} + , secondCircularObject:any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepEqual(circularObject, secondCircularObject); + + err(() => { + secondCircularObject.field2 = secondCircularObject; + assert.deepEqual(circularObject, secondCircularObject); + }, 'expected { field: [Circular] } to deeply equal { Object (field, field2) }'); + }); + + test('notDeepEqual', () => { + assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'}); + err(() => { + assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'}); + }, 'expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }'); + }); + + test('notDeepEqual (circular)', () => { + var circularObject:any = {} + , secondCircularObject:any = { tea: 'jasmine' }; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.notDeepEqual(circularObject, secondCircularObject); + + err(() => { + delete secondCircularObject.tea; + assert.notDeepEqual(circularObject, secondCircularObject); + }, 'expected { field: [Circular] } to not deeply equal { field: [Circular] }'); + }); + + test('isNull', () => { + assert.isNull(null); + + err(() => { + assert.isNull(undefined); + }, 'expected undefined to equal null'); + }); + + test('isNotNull', () => { + assert.isNotNull(undefined); + + err(() => { + assert.isNotNull(null); + }, 'expected null to not equal null'); + }); + + test('isUndefined', () => { + assert.isUndefined(undefined); + + err(() => { + assert.isUndefined(null); + }, 'expected null to equal undefined'); + }); + + test('isDefined', () => { + assert.isDefined(null); + + err(() => { + assert.isDefined(undefined); + }, 'expected undefined to not equal undefined'); + }); + + test('isFunction', () => { + var func = () => { + }; + assert.isFunction(func); + + err(() => { + assert.isFunction({}); + }, 'expected {} to be a function'); + }); + + test('isNotFunction', () => { + assert.isNotFunction(5); + + err(() => { + assert.isNotFunction(() => { + }); + }, 'expected [Function] not to be a function'); + }); + + test('isArray', () => { + assert.isArray([]); + assert.isArray(new Array()); + + err(() => { + assert.isArray({}); + }, 'expected {} to be an array'); + }); + + test('isNotArray', () => { + assert.isNotArray(3); + + err(() => { + assert.isNotArray([]); + }, 'expected [] not to be an array'); + + err(() => { + assert.isNotArray(new Array()); + }, 'expected [] not to be an array'); + }); + + test('isString', () => { + assert.isString('Foo'); + assert.isString(new String('foo')); + + err(() => { + assert.isString(1); + }, 'expected 1 to be a string'); + }); + + test('isNotString', () => { + assert.isNotString(3); + assert.isNotString([ 'hello' ]); + + err(() => { + assert.isNotString('hello'); + }, 'expected \'hello\' not to be a string'); + }); + + test('isNumber', () => { + assert.isNumber(1); + assert.isNumber(Number('3')); + + err(() => { + assert.isNumber('1'); + }, 'expected \'1\' to be a number'); + }); + + test('isNotNumber', () => { + assert.isNotNumber('hello'); + assert.isNotNumber([ 5 ]); + + err(() => { + assert.isNotNumber(4); + }, 'expected 4 not to be a number'); + }); + + test('isBoolean', () => { + assert.isBoolean(true); + assert.isBoolean(false); + + err(() => { + assert.isBoolean('1'); + }, 'expected \'1\' to be a boolean'); + }); + + test('isNotBoolean', () => { + assert.isNotBoolean('true'); + + err(() => { + assert.isNotBoolean(true); + }, 'expected true not to be a boolean'); + + err(() => { + assert.isNotBoolean(false); + }, 'expected false not to be a boolean'); + }); + + test('include', () => { + assert.include('foobar', 'bar'); + assert.include([ 1, 2, 3], 3); + + err(() => { + assert.include('foobar', 'baz'); + }, 'expected \'foobar\' to contain \'baz\''); + + err(() => { + assert.include(undefined, 'bar'); + }, 'expected an array or string'); + }); + + test('notInclude', () => { + assert.notInclude('foobar', 'baz'); + assert.notInclude([ 1, 2, 3 ], 4); + + err(() => { + assert.notInclude('foobar', 'bar'); + }, 'expected \'foobar\' to not contain \'bar\''); + + err(() => { + assert.notInclude(undefined, 'bar'); + }, 'expected an array or string'); + }); + + test('lengthOf', () => { + assert.lengthOf([1, 2, 3], 3); + assert.lengthOf('foobar', 6); + + err(() => { + assert.lengthOf('foobar', 5); + }, 'expected \'foobar\' to have a length of 5 but got 6'); + + err(() => { + assert.lengthOf(1, 5); + }, 'expected 1 to have a property \'length\''); + }); + + test('match', () => { + assert.match('foobar', /^foo/); + assert.notMatch('foobar', /^bar/); + + err(() => { + assert.match('foobar', /^bar/i); + }, 'expected \'foobar\' to match /^bar/i'); + + err(() => { + assert.notMatch('foobar', /^foo/i); + }, 'expected \'foobar\' not to match /^foo/i'); + }); + + test('property', () => { + var obj = { foo: { bar: 'baz' } }; + var simpleObj = { foo: 'bar' }; + assert.property(obj, 'foo'); + assert.deepProperty(obj, 'foo.bar'); + assert.notProperty(obj, 'baz'); + assert.notProperty(obj, 'foo.bar'); + assert.notDeepProperty(obj, 'foo.baz'); + assert.deepPropertyVal(obj, 'foo.bar', 'baz'); + assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); + + err(() => { + assert.property(obj, 'baz'); + }, 'expected { foo: { bar: \'baz\' } } to have a property \'baz\''); + + err(() => { + assert.deepProperty(obj, 'foo.baz'); + }, 'expected { foo: { bar: \'baz\' } } to have a deep property \'foo.baz\''); + + err(() => { + assert.notProperty(obj, 'foo'); + }, 'expected { foo: { bar: \'baz\' } } to not have property \'foo\''); + + err(() => { + assert.notDeepProperty(obj, 'foo.bar'); + }, 'expected { foo: { bar: \'baz\' } } to not have deep property \'foo.bar\''); + + err(() => { + assert.propertyVal(simpleObj, 'foo', 'ball'); + }, 'expected { foo: \'bar\' } to have a property \'foo\' of \'ball\', but got \'bar\''); + + err(() => { + assert.deepPropertyVal(obj, 'foo.bar', 'ball'); + }, 'expected { foo: { bar: \'baz\' } } to have a deep property \'foo.bar\' of \'ball\', but got \'baz\''); + + err(() => { + assert.propertyNotVal(simpleObj, 'foo', 'bar'); + }, 'expected { foo: \'bar\' } to not have a property \'foo\' of \'bar\''); + + err(() => { + assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); + }, 'expected { foo: { bar: \'baz\' } } to not have a deep property \'foo.bar\' of \'baz\''); + }); + + test('throws', () => { + assert.throws(() => { + throw new Error('foo'); + }); + assert.throws(() => { + throw new Error('bar'); + }, 'bar'); + assert.throws(() => { + throw new Error('bar'); + }, /bar/); + assert.throws(() => { + throw new Error('bar'); + }, Error); + assert.throws(() => { + throw new Error('bar'); + }, Error, 'bar'); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, TypeError); + }, 'expected [Function] to throw \'TypeError\' but [Error: foo] was thrown'); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, 'bar'); + }, 'expected [Function] to throw error including \'bar\' but got \'foo\''); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, Error, 'bar'); + }, 'expected [Function] to throw error including \'bar\' but got \'foo\''); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, TypeError, 'bar'); + }, 'expected [Function] to throw \'TypeError\' but [Error: foo] was thrown'); + + err(() => { + assert.throws(() => { + }); + }, 'expected [Function] to throw an error'); + + err(() => { + assert.throws(() => { + throw new Error(''); + }, 'bar'); + }, 'expected [Function] to throw error including \'bar\' but got \'\''); + + err(() => { + assert.throws(() => { + throw new Error(''); + }, /bar/); + }, 'expected [Function] to throw error matching /bar/ but got \'\''); + }); + + test('doesNotThrow', () => { + assert.doesNotThrow(() => { + }); + assert.doesNotThrow(() => { + }, 'foo'); + + err(() => { + assert.doesNotThrow(() => { + throw new Error('foo'); + }); + }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); + }); + + test('ifError', () => { + assert.ifError(false); + assert.ifError(null); + assert.ifError(undefined); + + err(() => { + assert.ifError('foo'); + }, 'expected \'foo\' to be falsy'); + }); + + test('operator', () => { + assert.operator(1, '<', 2); + assert.operator(2, '>', 1); + assert.operator(1, '==', 1); + assert.operator(1, '<=', 1); + assert.operator(1, '>=', 1); + assert.operator(1, '!=', 2); + assert.operator(1, '!==', 2); + + err(() => { + assert.operator(1, '=', 2); + }, 'Invalid operator "="'); + + err(() => { + assert.operator(2, '<', 1); + }, 'expected 2 to be < 1'); + + err(() => { + assert.operator(1, '>', 2); + }, 'expected 1 to be > 2'); + + err(() => { + assert.operator(1, '==', 2); + }, 'expected 1 to be == 2'); + + err(() => { + assert.operator(2, '<=', 1); + }, 'expected 2 to be <= 1'); + + err(() => { + assert.operator(1, '>=', 2); + }, 'expected 1 to be >= 2'); + + err(() => { + assert.operator(1, '!=', 1); + }, 'expected 1 to be != 1'); + + err(() => { + assert.operator(1, '!==', '1'); + }, 'expected 1 to be !== \'1\''); + }); + + test('closeTo', () => { + assert.closeTo(1.5, 1.0, 0.5); + assert.closeTo(10, 20, 20); + assert.closeTo(-10, 20, 30); + + err(() => { + assert.closeTo(2, 1.0, 0.5); + }, 'expected 2 to be close to 1 +/- 0.5'); + + err(() => { + assert.closeTo(-10, 20, 29); + }, 'expected -10 to be close to 20 +/- 29'); + }); + + test('members', () => { + assert.includeMembers([1, 2, 3], [2, 3]); + assert.includeMembers([1, 2, 3], []); + assert.includeMembers([1, 2, 3], [3]); + + err(() => { + assert.includeMembers([5, 6], [7, 8]); + }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); + + err(() => { + assert.includeMembers([5, 6], [5, 6, 0]); + }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); + }); + + test('memberEquals', () => { + assert.sameMembers([], []); + assert.sameMembers([1, 2, 3], [3, 2, 1]); + assert.sameMembers([4, 2], [4, 2]); + + err(() => { + assert.sameMembers([], [1, 2]); + }, 'expected [] to have the same members as [ 1, 2 ]'); + + err(() => { + assert.sameMembers([1, 54], [6, 1, 54]); + }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); + }); }); diff --git a/chai/chai-tests.ts.tscparams b/chai/chai-tests.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/chai/chai-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/chai/chai.d.ts b/chai/chai.d.ts index dd0adf974..1134b137d 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,67 +1,46 @@ // Type definitions for chai 2.0.0 // Project: http://chaijs.com/ -// Definitions by: Jed Hunsaker , Bart van der Schoor +// Definitions by: Jed Mao , Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module chai { - export class AssertionError { - constructor(message: string, _props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; +declare module Chai { + + interface ChaiStatic { + expect: ExpectStatic; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: (chai: any, utils: any) => void): any; + assert: AssertStatic; + config: Config; } - export function expect(target: any, message?: string): Expect; - - export var assert: Assert; - export var config: Config; - - export interface Config { - includeStack: boolean; + export interface ExpectStatic extends AssertionStatic { } - // Provides a way to extend the internals of Chai - function use(fn: (chai: any, utils: any) => void): any; - - interface ExpectStatic { - (target: any): Expect; + export interface AssertStatic extends Assert { } - interface Assertions { - attr(name: string, value?: string): any; - css(name: string, value?: string): any; - data(name: string, value?: string): any; - class(className: string): any; - id(id: string): any; - html(html: string): any; - text(text: string): any; - value(value: string): any; - visible: any; - hidden: any; - selected: any; - checked: any; - disabled: any; - empty: any; - exist: any; + export interface AssertionStatic { + (target: any, message?: string): Assertion; } - interface Expect extends LanguageChains, NumericComparison, TypeComparison, Assertions { - not: Expect; + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; deep: Deep; a: TypeComparison; an: TypeComparison; include: Include; contain: Include; - ok: Expect; - true: Expect; - false: Expect; - null: Expect; - undefined: Expect; - exist: Expect; - empty: Expect; - arguments: Expect; - Arguments: Expect; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; equal: Equal; equals: Equal; eq: Equal; @@ -72,34 +51,34 @@ declare module chai { haveOwnProperty: OwnProperty; length: Length; lengthOf: Length; - match(RegularExpression: RegExp, message?: string): Expect; - string(string: string, message?: string): Expect; + match(regexp: RegExp|string, message?: string): Assertion; + string(string: string, message?: string): Assertion; keys: Keys; - key(string: string): Expect; + key(string: string): Assertion; throw: Throw; throws: Throw; Throw: Throw; - respondTo(method: string, message?: string): Expect; - itself: Expect; - satisfy(matcher: Function, message?: string): Expect; - closeTo(expected: number, delta: number, message?: string): Expect; + respondTo(method: string, message?: string): Assertion; + itself: Assertion; + satisfy(matcher: Function, message?: string): Assertion; + closeTo(expected: number, delta: number, message?: string): Assertion; members: Members; } interface LanguageChains { - to: Expect; - be: Expect; - been: Expect; - is: Expect; - that: Expect; - which: Expect; - and: Expect; - have: Expect; - has: Expect; - with: Expect; - at: Expect; - of: Expect; - same: Expect; + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; } interface NumericComparison { @@ -113,21 +92,21 @@ declare module chai { lessThan: NumberComparer; most: NumberComparer; lte: NumberComparer; - within(start: number, finish: number, message?: string): Expect; + within(start: number, finish: number, message?: string): Assertion; } interface NumberComparer { - (value: number, message?: string): Expect; + (value: number, message?: string): Assertion; } interface TypeComparison { - (type: string, message?: string): Expect; + (type: string, message?: string): Assertion; instanceof: InstanceOf; instanceOf: InstanceOf; } interface InstanceOf { - (constructor: Object, message?: string): Expect; + (constructor: Object, message?: string): Assertion; } interface Deep { @@ -137,150 +116,168 @@ declare module chai { } interface Equal { - (value: any, message?: string): Expect; + (value: any, message?: string): Assertion; } interface Property { - (name: string, value?: any, message?: string): Expect; + (name: string, value?: any, message?: string): Assertion; } interface OwnProperty { - (name: string, message?: string): Expect; + (name: string, message?: string): Assertion; } interface Length extends LanguageChains, NumericComparison { - (length: number, message?: string): Expect; + (length: number, message?: string): Assertion; } interface Include { - (value: Object, message?: string): Expect; - (value: string, message?: string): Expect; - (value: number, message?: string): Expect; + (value: Object, message?: string): Assertion; + (value: string, message?: string): Assertion; + (value: number, message?: string): Assertion; keys: Keys; members: Members; } interface Keys { - (...keys: string[]): Expect; - (keys: any[]): Expect; - } - - interface Members { - (set: any[], message?: string): Expect; + (...keys: string[]): Assertion; + (keys: any[]): Assertion; } interface Throw { - (): Expect; - (expected: string, message?: string): Expect; - (expected: RegExp, message?: string): Expect; - (constructor: Error, expected?: string, message?: string): Expect; - (constructor: Error, expected?: RegExp, message?: string): Expect; - (constructor: Function, expected?: string, message?: string): Expect; - (constructor: Function, expected?: RegExp, message?: string): Expect; + (): Assertion; + (expected: string, message?: string): Assertion; + (expected: RegExp, message?: string): Assertion; + (constructor: Error, expected?: string, message?: string): Assertion; + (constructor: Error, expected?: RegExp, message?: string): Assertion; + (constructor: Function, expected?: string, message?: string): Assertion; + (constructor: Function, expected?: RegExp, message?: string): Assertion; + } + + interface Members { + (set: any[], message?: string): Assertion; } export interface Assert { - (express: any, msg?: string):void; + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): void; - fail(actual?: any, expected?: any, msg?: string, operator?: string):void; + fail(actual?: any, expected?: any, msg?: string, operator?: string): void; - ok(val: any, msg?: string):void; - notOk(val: any, msg?: string):void; + ok(val: any, msg?: string): void; + notOk(val: any, msg?: string): void; - equal(act: any, exp: any, msg?: string):void; - notEqual(act: any, exp: any, msg?: string):void; + equal(act: any, exp: any, msg?: string): void; + notEqual(act: any, exp: any, msg?: string): void; - strictEqual(act: any, exp: any, msg?: string):void; - notStrictEqual(act: any, exp: any, msg?: string):void; + strictEqual(act: any, exp: any, msg?: string): void; + notStrictEqual(act: any, exp: any, msg?: string): void; - deepEqual(act: any, exp: any, msg?: string):void; - notDeepEqual(act: any, exp: any, msg?: string):void; + deepEqual(act: any, exp: any, msg?: string): void; + notDeepEqual(act: any, exp: any, msg?: string): void; - isTrue(val: any, msg?: string):void; - isFalse(val: any, msg?: string):void; + isTrue(val: any, msg?: string): void; + isFalse(val: any, msg?: string): void; - isNull(val: any, msg?: string):void; - isNotNull(val: any, msg?: string):void; + isNull(val: any, msg?: string): void; + isNotNull(val: any, msg?: string): void; - isUndefined(val: any, msg?: string):void; - isDefined(val: any, msg?: string):void; + isUndefined(val: any, msg?: string): void; + isDefined(val: any, msg?: string): void; - isFunction(val: any, msg?: string):void; - isNotFunction(val: any, msg?: string):void; + isFunction(val: any, msg?: string): void; + isNotFunction(val: any, msg?: string): void; - isObject(val: any, msg?: string):void; - isNotObject(val: any, msg?: string):void; + isObject(val: any, msg?: string): void; + isNotObject(val: any, msg?: string): void; - isArray(val: any, msg?: string):void; - isNotArray(val: any, msg?: string):void; + isArray(val: any, msg?: string): void; + isNotArray(val: any, msg?: string): void; - isString(val: any, msg?: string):void; - isNotString(val: any, msg?: string):void; + isString(val: any, msg?: string): void; + isNotString(val: any, msg?: string): void; - isNumber(val: any, msg?: string):void; - isNotNumber(val: any, msg?: string):void; + isNumber(val: any, msg?: string): void; + isNotNumber(val: any, msg?: string): void; - isBoolean(val: any, msg?: string):void; - isNotBoolean(val: any, msg?: string):void; + isBoolean(val: any, msg?: string): void; + isNotBoolean(val: any, msg?: string): void; - typeOf(val: any, type: string, msg?: string):void; - notTypeOf(val: any, type: string, msg?: string):void; + typeOf(val: any, type: string, msg?: string): void; + notTypeOf(val: any, type: string, msg?: string): void; - instanceOf(val: any, type: Function, msg?: string):void; - notInstanceOf(val: any, type: Function, msg?: string):void; + instanceOf(val: any, type: Function, msg?: string): void; + notInstanceOf(val: any, type: Function, msg?: string): void; - include(exp: string, inc: any, msg?: string):void; - include(exp: any[], inc: any, msg?: string):void; + include(exp: string, inc: any, msg?: string): void; + include(exp: any[], inc: any, msg?: string): void; - notInclude(exp: string, inc: any, msg?: string):void; - notInclude(exp: any[], inc: any, msg?: string):void; + notInclude(exp: string, inc: any, msg?: string): void; + notInclude(exp: any[], inc: any, msg?: string): void; - match(exp: any, re: RegExp, msg?: string):void; - notMatch(exp: any, re: RegExp, msg?: string):void; + match(exp: any, re: RegExp, msg?: string): void; + notMatch(exp: any, re: RegExp, msg?: string): void; - property(obj: Object, prop: string, msg?: string):void; - notProperty(obj: Object, prop: string, msg?: string):void; - deepProperty(obj: Object, prop: string, msg?: string):void; - notDeepProperty(obj: Object, prop: string, msg?: string):void; + property(obj: Object, prop: string, msg?: string): void; + notProperty(obj: Object, prop: string, msg?: string): void; + deepProperty(obj: Object, prop: string, msg?: string): void; + notDeepProperty(obj: Object, prop: string, msg?: string): void; - propertyVal(obj: Object, prop: string, val: any, msg?: string):void; - propertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + propertyVal(obj: Object, prop: string, val: any, msg?: string): void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - deepPropertyVal(obj: Object, prop: string, val: any, msg?: string):void; - deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string):void; + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; - lengthOf(exp: any, len: number, msg?: string):void; + lengthOf(exp: any, len: number, msg?: string): void; //alias frenzy - throw(fn: Function, msg?: string):void; - throw(fn: Function, regExp: RegExp):void; - throw(fn: Function, errType: Function, msg?: string):void; - throw(fn: Function, errType: Function, regExp: RegExp):void; + throw(fn: Function, msg?: string): void; + throw(fn: Function, regExp: RegExp): void; + throw(fn: Function, errType: Function, msg?: string): void; + throw(fn: Function, errType: Function, regExp: RegExp): void; - throws(fn: Function, msg?: string):void; - throws(fn: Function, regExp: RegExp):void; - throws(fn: Function, errType: Function, msg?: string):void; - throws(fn: Function, errType: Function, regExp: RegExp):void; + throws(fn: Function, msg?: string): void; + throws(fn: Function, regExp: RegExp): void; + throws(fn: Function, errType: Function, msg?: string): void; + throws(fn: Function, errType: Function, regExp: RegExp): void; - Throw(fn: Function, msg?: string):void; - Throw(fn: Function, regExp: RegExp):void; - Throw(fn: Function, errType: Function, msg?: string):void; - Throw(fn: Function, errType: Function, regExp: RegExp):void; + Throw(fn: Function, msg?: string): void; + Throw(fn: Function, regExp: RegExp): void; + Throw(fn: Function, errType: Function, msg?: string): void; + Throw(fn: Function, errType: Function, regExp: RegExp): void; - doesNotThrow(fn: Function, msg?: string):void; - doesNotThrow(fn: Function, regExp: RegExp):void; - doesNotThrow(fn: Function, errType: Function, msg?: string):void; - doesNotThrow(fn: Function, errType: Function, regExp: RegExp):void; + doesNotThrow(fn: Function, msg?: string): void; + doesNotThrow(fn: Function, regExp: RegExp): void; + doesNotThrow(fn: Function, errType: Function, msg?: string): void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; - operator(val: any, operator: string, val2: any, msg?: string):void; - closeTo(act: number, exp: number, delta: number, msg?: string):void; + operator(val: any, operator: string, val2: any, msg?: string): void; + closeTo(act: number, exp: number, delta: number, msg?: string): void; - sameMembers(set1: any[], set2: any[], msg?: string):void; - includeMembers(set1: any[], set2: any[], msg?: string):void; + sameMembers(set1: any[], set2: any[], msg?: string): void; + includeMembers(set1: any[], set2: any[], msg?: string): void; - ifError(val: any, msg?: string):void; + ifError(val: any, msg?: string): void; + } + + export interface Config { + includeStack: boolean; + } + + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; } } +declare var chai: Chai.ChaiStatic; + declare module "chai" { export = chai; } diff --git a/chrome/chrome-app-tests.ts b/chrome/chrome-app-tests.ts index de56bbac8..970e03517 100644 --- a/chrome/chrome-app-tests.ts +++ b/chrome/chrome-app-tests.ts @@ -28,6 +28,14 @@ var currentWindow: cwindow.AppWindow = chrome.app.window.current(); var otherWindow: cwindow.AppWindow = chrome.app.window.get('some-string'); var allWindows: cwindow.AppWindow[] = chrome.app.window.getAll(); +// listening to window events +currentWindow.onBoundsChanged.addListener(function () { return; }); +currentWindow.onClosed.addListener(function () { return; }); +currentWindow.onFullscreened.addListener(function () { return; }); +currentWindow.onMaximized.addListener(function () { return; }); +currentWindow.onMinimized.addListener(function () { return; }); +currentWindow.onRestored.addListener(function () { return; }); + // check platform capabilities var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(); diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index 2f498ed28..5cfa0fbce 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -122,6 +122,12 @@ declare module chrome.app.window { id: string; innerBounds: Bounds; outerBounds: Bounds; + onBoundsChanged: WindowEvent; + onClosed: WindowEvent; + onFullscreened: WindowEvent; + onMaximized: WindowEvent; + onMinimized: WindowEvent; + onRestored: WindowEvent; } export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; diff --git a/d3/d3.d.ts b/d3/d3.d.ts index f3dbee63d..0bf3d599d 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -60,6 +60,7 @@ declare module D3 { altKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; + shiftKey?: boolean; type: string; } @@ -786,8 +787,18 @@ declare module D3 { (valueFunction: (data: T, index: number) => any): _Selection; }; - append: (name: string) => _Selection; - insert: (name: string, before: string) => _Selection; + append: { + (name: string): _Selection; + (elementFunction: (data: T, index: number) => any): _Selection; + } + + insert: { + (name: string, before: string): _Selection; + (insertElementFunction: (data: T, index: number) => any, before: string): _Selection; + (name: string, beforeElementFunction: (data: T, index: number) => any): _Selection; + (insertElementFunction: (data: T, index: number) => any, beforeElementFunction: (data: T, index: number) => any): _Selection; + } + remove: () => _Selection; empty: () => boolean; @@ -873,8 +884,18 @@ declare module D3 { export interface Selection extends _Selection { } export interface _EnterSelection { - append: (name: string) => _Selection; - insert: (name: string, before?: string) => _Selection; + append: { + (name: string): _Selection; + (elementFunction: (data: T, index: number) => any): _Selection; + } + + insert: { + (name: string, before?: string): _Selection; + (insertElementFunction: (data: T, index: number) => any, before?: string): _Selection; + (name: string, beforeElementFunction?: (data: T, index: number) => any): _Selection; + (insertElementFunction: (data: T, index: number) => any, beforeElementFunction?: (data: T, index: number) => any): _Selection; + } + select: (selector: string) => _Selection; empty: () => boolean; node: () => Element; diff --git a/dojo/dijit.d.ts b/dojo/dijit.d.ts index 33144b9da..0bb2ab67d 100644 --- a/dojo/dijit.d.ts +++ b/dojo/dijit.d.ts @@ -34291,7 +34291,7 @@ declare module dijit { * * @param id */ - byId(id: String): any; + byId(id: String): dijit._WidgetBase; /** * A synthetic clone of array.every acting explicitly on this WidgetSet * @@ -105714,14 +105714,14 @@ declare module dijit { * * @param id */ - byId(id: String): String; + byId(id: String): dijit._WidgetBase; /** * Find a widget by it's id. * If passed a widget then just returns the widget. * * @param id */ - byId(id: dijit._WidgetBase): String; + byId(id: dijit._WidgetBase): dijit._WidgetBase; /** * Returns the widget corresponding to the given DOMNode * @@ -105956,14 +105956,14 @@ declare module dijit { * * @param id */ - byId(id: String): String; + byId(id: String): dijit._WidgetBase; /** * Find a widget by it's id. * If passed a widget then just returns the widget. * * @param id */ - byId(id: dijit._WidgetBase): String; + byId(id: dijit._WidgetBase): dijit._WidgetBase; /** * Returns the widget corresponding to the given DOMNode * diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index bda5c3494..7b95efdfa 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -3098,7 +3098,7 @@ declare module dojo { */ class Stateful { constructor(); - inherited: {(arguments: IArguments): any}; + inherited: {(args: IArguments): any}; /** * Get a property on a Stateful instance. * Get a named property on a Stateful object. The property may diff --git a/dymo-label-framework/dymo-label-framework-tests.ts b/dymo-label-framework/dymo-label-framework-tests.ts new file mode 100644 index 000000000..b64625eaa --- /dev/null +++ b/dymo-label-framework/dymo-label-framework-tests.ts @@ -0,0 +1,115 @@ +/// + +var f = dymo.label.framework; + +// Test checkEnvironment +var env = f.checkEnvironment(); + +env.errorDetails = ""; +env.isBrowserSupported = true; +env.isFrameworkInstalled = true; + +// Test getPrinters +var printers = f.getPrinters(); + +// Test PrinterInfo properties +printers.forEach((value) =>{ + value.isAutoCutSupported = true; + value.isConnected = true; + value.isLocal = true; + value.isTwinTurbo = true; + value.modelName = ""; + value.name = ""; +}); + +var testcolor:dymo.label.framework.Color = { alpha: 255, red: 0, green: 0, blue: 0}; + +// Test createLabelRenderParamsXml +var renderParamsXml: string = f.createLabelRenderParamsXml({ + flowDirection: f.FlowDirection.LeftToRight, + labelColor: testcolor, + pngUseDisplayResolution: true, + shadowColor: testcolor, + shadowDepth: 0 +}); +f.createLabelRenderParamsXml({}).charAt(0); // string, all optional params + +// Test renderLabel +f.renderLabel("", renderParamsXml, printers[0].name); + +// Test openLabelXml +var label = f.openLabelXml(""); + +// Test ILabel methods +label.getAddressBarcodePosition(0) == f.AddressBarcodePosition.AboveAddress; // enum +label.getAddressObjectCount().toFixed(); // number +label.getAddressText(0).charAt(0); // string +label.getLabelXml().charAt(0); // string +label.getObjectNames()[0].charAt(0); // string[] +label.getObjectText("").charAt(0); // string +label.print("", "", ""); +label.printAndPollStatus("", "", "", (printJob, printJobStatusInfo) => { + // Test PrintJob + printJob.getStatus((printJobStatusInfoA) => { + // Test PrintJobStatusInfo + printJobStatusInfoA.status.toFixed(); // number + printJobStatusInfoA.statusMessage.charAt(0); // string + }); + // Test callback (must return boolean) + return true; +}, 0); +label.render("", "").charAt(0); // string +// Test chainable "set" methods +label.setAddressBarcodePosition(0, dymo.label.framework.AddressBarcodePosition.AboveAddress) + .setAddressText(0, "") + .setObjectText("", "") + .setAddressText(1, ""); + +// Test LabelSetBuilder +var lsb = new f.LabelSetBuilder(); +var lsbRec = lsb.addRecord(); +lsb.toString().charAt(0); // string +lsb.getRecords().pop(); // array +lsb.getRecords()[0].setText("", ""); // array of ILabelSetRecord + +// Test chainable ILabelSetRecord methods. +lsbRec.setBase64Image("", "").setText("", "").setTextMarkup("", "").setText("", ""); + +// Test static toXml +f.LabelSetBuilder.toXml(lsb.getRecords()); + +// Test printLabel +f.printLabel("", "", "", ""); + +// Test printLabel2 +f.printLabel2("", "", "", "").getStatus((pjsi) => { + pjsi.status.toFixed(); + pjsi.statusMessage.charAt(0); +}); + + + +// Test createLabelWriterPrintParamsXml +var clwppxp: dymo.label.framework.CreateLabelWriterPrintParamsXmlParams = { + copies: 0, // number + flowDirection: dymo.label.framework.FlowDirection.LeftToRight, // enum + jobTitle: "", // string + printQuality: dymo.label.framework.LabelWriterPrintQuality.BarcodeAndGraphics, // enum + twinTurboRoll: dymo.label.framework.TwinTurboRoll.Left // enum +} +f.createLabelWriterPrintParamsXml(clwppxp).charAt(0); // string +f.createLabelWriterPrintParamsXml({}).charAt(0) // all optional params + +// Test createTapePrintParamsXml +var ctppxp: dymo.label.framework.CreateTapePrintParamsXmlParams = { + copies: 0, // number + flowDirection: dymo.label.framework.FlowDirection.RightToLeft, // enum + alignment: dymo.label.framework.TapeAlignment.Left, // enum + cutMode: dymo.label.framework.TapeCutMode.ChainMarks, // enum + jobTitle: "" // string +} +f.createTapePrintParamsXml(ctppxp).charAt(0); // string +f.createTapePrintParamsXml({}).charAt(0); // all optional params + +// Test VERSION +f.VERSION.charAt(0); // string diff --git a/dymo-label-framework/dymo-label-framework.d.ts b/dymo-label-framework/dymo-label-framework.d.ts new file mode 100644 index 000000000..b3209e15c --- /dev/null +++ b/dymo-label-framework/dymo-label-framework.d.ts @@ -0,0 +1,596 @@ +// Type definitions for DYMO Label Framework v1.2.6 +// Project: http://www.labelwriter.com/software/dls/sdk/docs/DYMOLabelFrameworkJavaScriptHelp/index.html +// Definitions by: Thijs Kuipers +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * Top namespace for DYMO Label Framework JavaScript library. + * Latest library available at http://labelwriter.com/software/dls/sdk/js/DYMO.Label.Framework.latest.js + * + * Based on information from http://www.labelwriter.com/software/dls/sdk/docs/DYMOLabelFrameworkJavaScriptHelp/index.html + * which is Copyright (c), 2010, Sanford, L.P. All Rights Reserved. + * + * Based on information from http://developers.dymo.com/2010/06/02/dymo-label-framework-overview/ + * which is © 2013 DYMO Label Inside Out + */ +declare module dymo.label.framework { + + /** Enumeration that specifies where to draw the Intellegent Mail barcode for an Address object. */ + enum AddressBarcodePosition { + /** Indicates to print the barcode above the address. */ + AboveAddress, + /** Indicates to print the barcode below the address. */ + BelowAddress, + /** Indicates to not print the barcode at all. */ + Suppress + } + + /** + * Emuneration that specifies the direction in which objects and object text are laid out on the label. + * For Middle East labels/content specify "RightToLeft", otherwise specify "LeftToRight" (default). + */ + enum FlowDirection { + /** Indicates that the content flows from left to right. */ + LeftToRight, + /** Indicates that the content flows from right to left. */ + RightToLeft + } + + /** + * Enumeration that specifies the print quality when printing to a LabelWriter printer. + */ + enum LabelWriterPrintQuality { + /** Indicates that text print quality (fast) is used. */ + Text, + /** Indicates that barcode and images print quality (slow) is used. */ + BarcodeAndGraphics, + /** Indicates that the print quality is automatically determined based on the types of objects on the label. */ + Auto + } + + /** Print Job Status */ + enum PrintJobStatus { + Error, + Finished, + InQueue, + InvalidJobId, + NotSpooled, + PaperOut, + PrinterBusy, + Printing, + ProcessingError, + Unknown + } + + /** Enumeration that specifies the leader and trailer for a tape label when printing to a Tape printer. */ + enum TapeAlignment { + /** Indicates a 10mm leader and a 10mm trailer. */ + Center, + /** Indicates a 6mm leader and a 10mm trailer. */ + Left, + /** Indicates a 10mm leader and a 6mm trailer. */ + Right + } + + /** Enumeration that specifies the tape cut mode when printing multiple labels to a Tape printer. Note: This enumeration affects multiple page print jobs only. If a one page job is printed, the tape is always cut. */ + enum TapeCutMode { + /** Indicates to cut the tape between labels. */ + AutoCut, + /** Indicates to print cut marks between labels. */ + ChainMarks + } + + /** Enumeration that specifies which roll to print to when printing to a Twin Turbo printer. */ + enum TwinTurboRoll { + /** Indicates to print to the left roll only. */ + Left, + /** Indicates to print to the right roll only. */ + Right, + /** Indicates to continue printing to the other roll when the current roll is out of paper. Note: This does not indicate which roll to print to first; printing may start on either roll. */ + Auto + } + + /** Returns the library version number, e.g. "1.2.6" */ + var VERSION: string; + + /** Checks that the browser enviroment is suitable for the Framework. */ + function checkEnvironment(): { + /** Indicates whether the browser is supported or not. */ + isBrowserSupported: boolean; + /** Indicates whether the Framework is installed or not. */ + isFrameworkInstalled: boolean; + /** An empty string if no error is detected; an error message if an error is detected. */ + errorDetails: string; + }; + + /** + * Object with properties 'a' or 'alpha' to specify color's alpha channel, + * r/red, g/green, b/blue for red, green, blue channels. + * The valid range for a/r/g/b fields is [0..255]. + */ + interface Color { + /** alpha channel [0..255] default: 255 */ + alpha?: number; + /** red channel [0..255] default: 0 */ + red?: number; + /** green channel [0..255] default: 0 */ + green?: number; + /** blue channel [0..255] default: 0 */ + blue?: number; + } + + interface CreateLabelRenderParamsXmlParams { + /** The color of the label. */ + labelColor?: Color; + /** The color of label shadow. */ + shadowColor?: Color; + /** The shadow width in TWIPS. If '0' is specified, no shadow is rendered. */ + shadowDepth?: number; + /** The direction of the label content on the label (left-to-right or right-to-left). Use the dymo.label.framework.FlowDirection enumeration to specify the value. */ + flowDirection?: FlowDirection; + /** + * If true, the PNG will be generated using the display resolution. + * If false, the PNG will be generated using the printer resolution. + * If the display resolution is used, the resulting PNG will be smaller. + * Use the printer resolution if the resulting image will be zoomed. This will give the zoomed preview better quality. + */ + pngUseDisplayResolution?: boolean; + } + + /** + * Creates an XML string suitable to pass to the dymo.label.framework.renderLabel function + * as renderParamsXml parameter. Returns an XML string. + * + * @param params A JavaScript object with the following properties + * (not all properties must be defined; if a property is not defined, a default value is used) + */ + function createLabelRenderParamsXml(params: CreateLabelRenderParamsXmlParams): string; + + interface CreateLabelWriterPrintParamsXmlParams { + /** The number of copies to print. */ + copies?: number; + /** The print job title/description. */ + jobTitle?: string; + /** The direction of the label content on the label (left-to-right or right-to-left). Use the dymo.label.framework.FlowDirection enumeration to specify the value. */ + flowDirection?: FlowDirection; + /** The print quality. Use the dymo.label.framework.LabelWriterPrintQuality enumeration to specify the value. */ + printQuality?: LabelWriterPrintQuality; + /** The roll to print to if the printer is a TwinTurbo printer. Use the dymo.label.framework.TwinTurboRoll enumeration to specify the value. */ + twinTurboRoll?: TwinTurboRoll; + } + + /** + * Creates an XML string suitable to to pass to the dymo.label.framework.printLabel function + * as printParamsXml parameter. Created print parameters are for printing to LabelWriter printers. + * Returns an XML string. + * + * @param params A JavaScript object with the following properties + * (not all properties must be defined; if a property is not defined, a default value is used) + */ + function createLabelWriterPrintParamsXml(params: CreateLabelWriterPrintParamsXmlParams): string; + + interface CreateTapePrintParamsXmlParams { + /** The number of copies to print. */ + copies?: number; + /** The print job title/description. */ + jobTitle?: string; + /** The direction of the label content on the label (left-to-right or right-to-left). Use the dymo.label.framework.FlowDirection enumeration to specify the value. */ + flowDirection?: FlowDirection; + /** The label alignment on the tape. Use the dymo.label.framework.TapeAlignment enumeration to specify the value. */ + alignment?: TapeAlignment; + /** The cut mode (if auto-cut is supported by the printer). Use the dymo.label.framework.TapeCutMode enumeration to specify the value. */ + cutMode?: TapeCutMode; + } + + /** + * Creates an XML string suitable to pass to the dymo.label.framework.printLabel function as printParamsXml parameter. Created print parameters are for printing to Tape printers. + * Returns an XML string. + * + * @param params A JavaScript object with the following properties + * (not all properties must be defined; if a property is not defined, a default value is used) + */ + function createTapePrintParamsXml(params: CreateTapePrintParamsXmlParams): string; + + interface PrinterInfo { + /** Indicates whether the Auto-Cut feature is supported by the printer or not. Note: The property is only defined if printerType is "TapePrinter". */ + isAutoCutSupported: boolean; + /** Indicates whether the printer is connected to a computer or not. Note: Currently only returns properly for local USB-connected printers on Windows. */ + isConnected: boolean; + /** Indicates whether the printer is a local USB-connected printer or a shared network printer. Note: Currently only returns properly on Windows. */ + isLocal: boolean; + /** Indicates whether the printer is a "LabelWriter Twin Turbo" (has two rolls) or not. Note: The property is only defined if printerType is "LabelWriterPrinter". */ + isTwinTurbo: boolean; + /** Returns the printer model/driver name. */ + modelName: string; + /** Returns the printer name (print queue name on Mac). */ + name: string; + /** Returns the printer type; "LabelWriterPrinter" or "TapePrinter". */ + printerType: string; + } + + /** + * Gets a list of all printers supported by the DYMO Label Framework. + * Results are returned in an array-like object. + * Each item is of the type dymo.label.framework.PrinterInfo. + * In addition, items can be accessed by printer name. + */ + function getPrinters(): PrinterInfo[]; + + /** + * Convenience method (overload of getPrinters) to get a list of all printers of type "LabelWriterPrinter". + */ + function getLabelWriterPrinters(): PrinterInfo[]; + + /** + * Convenience method (overload of getPrinters) to get a list of all printers of type "TapePrinter". + */ + function getTapePrinters(): PrinterInfo[]; + + /** + * Loads an image from a URL or file and returns it as a base64-encoded PNG stream. + * The loaded image is not necessarily in PNG format. + * The image can be in any format supported by the Framework (by DYMO Label v.8). + * The loaded data can be used to set content for an image object on a label. + * Note: The comments for {@link openLabelFile} apply to this function as well. + * + * @param imageUri URL or file name to load the image from. + * + * @returns A base64-encoded PNG stream. + */ + function loadImageAsPngBase64(imageUri: string): string; + + /** Print Job */ + interface PrintJob { + /** + * Gets a status of the print job + * + * @param replyCallback a function called when the status is available + */ + getStatus(replyCallback: (printJobStatusInfo: PrintJobStatusInfo) => any): void; + } + + /** Print Job Status Info */ + interface PrintJobStatusInfo { + statusMessage: string; + status: PrintJobStatus; + } + + /** + * There is no constructor function for ILabel. To get ILabel instance use the + * dymo.label.framework.openLabelFile or dymo.label.framework.openLabelXml function. + * ILabel provides methods for manipulating label content, such as set address or text + * on the label. + */ + interface ILabel { + /** + * Gets the Intelligent Mail barcode position for an Address object. + * + * @param addressIndex The zero-based index of the Address object in a 'virtual' array of all Address objects on the label. + * + * @returns A string with one of the values defined by the dymo.label.framework.AddressBarcodePosition enumeration. + */ + getAddressBarcodePosition(addressIndex: number): AddressBarcodePosition; + + /** + * Gets the number of Address objects on the label. + */ + getAddressObjectCount(): number; + + /** + * Gets the text content of an Address object. + * + * @param addressIndex The zero-based index of the Address object in a 'virtual' array of all Address objects on the label. + * + * @returns The plain text from the Address object. + */ + getAddressText(addressIndex: number): string; + + /** + * Returns the current label as an XML string. The returned XML string can be passed + * to functions that accept label XML as a parameter, or can be used to direct content + * manipulations not currently supported by the Framework. + */ + getLabelXml(): string; + + /** + * Gets an array of object reference names on the label. Returns an array of strings. + */ + getObjectNames(): string[]; + + /** + * Gets the 'text' content of an object. The content depends on the object type. + * * Address and Text objects - Returns the object text without formatting. + * * Barcode object - Returns the barcode string. + * * Image - Returns the base64-encoded string on the image's PNG stream (only if image data is embedded with the label and not linked to a URL or file). + * * Circular Text object - Returns the object text. + * * Other objects - Returns an empty string. + * + * @param objectName The name of the object. + */ + getObjectText(objectName: string): string; + + /** + * Prints the label. + * + * @param printerName The name of the printer to print to. A list of printers can be obtained using dymo.label.framework.getPrinters. + * @param printParamsXml The print parameters, such as number of copies, print quality, etc. See [PrintParams.xsd]{@link http://labelwriter.com/software/dls/sdk/PrintParams.xsd}. + * @param labelSetXml + * The LabelSet to print. LabelSet is used to print multiple labels with the same layout, but with different + * data, such as multiple addresses. Use the dymo.label.framework.LabelSetBuilder class to create a LabelSet + * or construct XML manually according to [LabelSet.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelSet.xsd}. + */ + print(printerName: string, printParamsXml: string, labelSetXml: string): void; + + /** + * Prints a label and runs status checking in a loop + * + * @param printerName The name of the printer to print to. A list of printers can be obtained using dymo.label.framework.getPrinters. + * @param printParamsXml The print parameters, such as number of copies, print quality, etc. See [PrintParams.xsd]{@link http://labelwriter.com/software/dls/sdk/PrintParams.xsd}. + * @param labelSetXml The LabelSet to print. + * LabelSet is used to print multiple labels with the same layout, but with different data, such as multiple + * addresses. Use the dymo.label.framework.LabelSetBuilder class to create a LabelSet or construct XML manually + * according to [LabelSet.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelSet.xsd}. + * @param statusCallback Status callback function called when the service returned status information. + * The callback takes two parameters; the first is PrintJob object. It can be used to get the status information on demand, + * without using polling. Also, it might be extended in the future to provide more control over the print job, e.g. an ability + * to cancel it. The second parameter to the callback is PrintJobStatusInfo class. PrintJobStatusInfo has two properties: + * statusMessage that contains a status message string; and status that contains status code. The callback has to return a + * boolean value. If true is returned, than pritnAndPollStatus() will poll the service again after the pollInterval passed. + * If false is returned, then printAndPollStatus() finishes processing. + * @param pollInterval Interval in milliseconds to ask the proxy service for the job status information. + * + * @returns The print job. + */ + printAndPollStatus( + printerName: string, + printParamsXml: string, + labelSetXml: string, + statusCallback: (printJob: PrintJob, printJobStatusInfo: PrintJobStatusInfo) => boolean, + pollInterval: number): PrintJob; + + /** + * Creates a label raster image that can be used for label previewing. + * + * @param renderParamsXml Rendering parameters, such as shadow depth, label color, etc. + * See [LabelRenderParams.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelRenderParams.xsd}. + * @param printerName The name of the printer that the preview is generated for. + * The preview/output can be different for different printers, + * especially for tape printers with different print head sizes. + * If it is not important what printer the label is printed to, + * an empty string can be passed. In this case, the default printer metrics will + * be used. The default is LW400 for LabelWriter printers and LW400 DUO Tape for + * tape printers. + */ + render(renderParamsXml: string, printerName: string): string; + + /** + * Sets the Intelligent Mail barcode position for an Address object. + * + * @param addressIndex The zero-based index of the Address object in a 'virtual' array of all Address objects on the label. + * @param barcodePosition The barcode position. + * + * @returns self + */ + setAddressBarcodePosition(addressIndex: number, barcodePosition: AddressBarcodePosition): ILabel; + + /** + * Sets the text content of an Address object. + * + * @param addressIndex The zero-based index of the Address object in a 'virtual' array of all Address objects on the label. + * @param text The plain text string that contains the content of the Address object. Note: The current text formatting is retained on a line-by-line basis. + * + * @returns self + */ + setAddressText(addressIndex: number, text: string): ILabel; + + /** + * Sets the text content for an object. The content and/or text formatting are set differently + * depending on the object type. + * + * * Address object - The formatting is applied on a line-by-line basis (using list). + * * Text object - The formatting of the current first character is applied to all text. + * * Barcode object - The barcode text. + * * Image object - The base64-encoded string of image's PNG stream. + * * CircularText object - The object text. + * * Date and Time and Counter objects - The object's 'Before' text. + * * Other objects - An empty string. + * + * @param objectName The name of the object. + * @param text The plain text string for new object content. + */ + setObjectText(objectName: string, text: string): ILabel; + } + + /** + * ILabelSetRecord instance holds data of one LabelSet record. ILabelSetRecord provides + * methods for adding data to the record. To create ILabelSetRecord instance, + * use dymo.label.framework.LabelSetBuilder.prototype.addRecord method. + */ + interface ILabelSetRecord { + /** + * Adds image data to the record. + * + * @param objectName The name of the object that the markup is set for. + * @param base64Image The string containing the base64-encoded PNG image stream. + * + * @returns self + */ + setBase64Image(objectName: string, base64Image: string): ILabelSetRecord; + + /** Adds data to the record specified as plain text. + * + * @param objectName The name of the object that the markup is set for. + * @param text The object text to set. + * + * @returns self + */ + setText(objectName: string, text: string): ILabelSetRecord; + + /** + * Adds data to the record specified as text markup. + * + * @param objectName The name of the object that the markup is set for. + * @param textMarkup The markup string. See [TextMarkup.xsd]{@link http://labelwriter.com/software/dls/sdk/TextMarkup.xsd}. + * + * @returns self + */ + setTextMarkup(objectName: string, textMarkup: string): ILabelSetRecord; + } + + /** + * Loads label content from a file or URL. + * The following considerations should be taken before using this function: + * + * * The full file name or URL should be specified. The function will not honor relative paths based on document.location.href. + * * The fileName can be an http:// or file:// URL. On Windows the file name can be a regular file name, for example 'c:\users\desktop\address.label'. + * * The content of the label will be loaded synchronously. Therefore, if the remote server is down there will be a timeout. + * * Any local file can be accessed or attempted to be accessed. The function is not limited by any browser restrictions. However, only a valid label file (according to label.xsd schema) can be loaded. This could still be a potential security concern. + * * The URL is not limited to same-site-origin browser policy. Any URL can be opened. + * * The proxy settings are the system default settings, these are not necessarily the browser settings. + * + * Use this function only when there is no other way to load label data. In most cases, label data should be loaded using dymo.label.framework.openLabelXml. + * + * @param fileName FileName or URL to load label from. + *  + * @returns Returns Label object; provides label manipulation methods. + */ + function openLabelFile(fileName: string): ILabel; + + /** + * Loads label content from an XML stream/string. + * Note: This is the preferred way to load/open label files. + * Use XMLHttpRequest() or other standard browser methods to get XML string. + * + * @param labelXml The label definition as an XML string. + * @returns Label object. + */ + function openLabelXml(labelXml: string): ILabel; + + /** + * Prints one or more labels. + * + * @param printerName The name of the printer to print to. A list of printers can be obtained using + * dymo.label.framework.getPrinters. + * @param printParamsXml The print parameters, such as number of copies, print quality, etc. + * See [PrintParams.xsd]{@link http://labelwriter.com/software/dls/sdk/PrintParams.xsd}. + * @param labelXml The label to print. + * @param labelSetXml The LabelSet to print. LabelSet is used to print multiple labels with the same layout, + * but with different data, such as multiple addresses. Use dymo.label.framework.LabelSetBuilder class to + * create a LabelSet, or construct XML manualy according to + * [LabelSet.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelSet.xsd}. + */ + function printLabel(printerName: string, printParamsXml: string, labelXml: string, labelSetXml: string): void; + + /** + * Prints a label and returns a print job object + * + * @param printerName The printer to print on. A list of printers can be obtained by getPrinters() + * @param printParamsXml Printing parameters, like number of copies, print quality, etc. See [PrintParams.xsd]{@link http://labelwriter.com/software/dls/sdk/PrintParams.xsd} + * @param labelXml Label to print + * @param labelSetXml + * LabelSet to print. LabelSet is used to print multiple labels with same layout but different data, e.g. multiple addresses. + * Use LabelSetBuilder to create a LabelSet or construct xml manualy according to [LabelSet.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelSet.xsd}. + */ + function printLabel2(printerName: string, printParamsXml: string, labelXml: string, labelSetXml: string): PrintJob; + + /** + * Prints a label and runs status checking in a loop + * + * @param printerName The printer to print on. A list of printers can be obtained by getPrinters() + * @param printParamsXml Printing parameters, like number of copies, print quality, etc. See [PrintParams.xsd]{@link http://labelwriter.com/software/dls/sdk/PrintParams.xsd} + * @param labelXml Label to print + * @param labelSetXml + * LabelSet to print. LabelSet is used to print multiple labels with same layout but different data, e.g. + * multiple addresses. + * Use LabelSetBuilder to create a LabelSet or construct xml manually according to + * [LabelSet.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelSet.xsd} + * @param statusCallback + * Function to be called when a print job status is available. + * To continue polling the status the function should return true, false otherwise. + * @param pollInterval Polling interval in milliseconds + */ + function printLabelAndPollStatus( + printerName: string, + printParamsXml: string, + labelXml: string, + labelSetXml: string, + statusCallback: (printJob: PrintJob, printJobStatusInfo: PrintJobStatusInfo) => boolean, + pollInterval: number): PrintJob; + + /** + * Creates a label raster image that can be used for label previewing. + * Returns a string that is a base64-encoded PNG stream of the label image. + * This string can be used as data: url for element. + * Note: data: urls are not supported by IE6 and IE7. IE8 supports them with a 32KB limit (so it may not be possible to preview 'large' labels). + * + * @param labelXml Label to preview. + * @param renderParamsXml The rendering parameters, such as shadow depth, label color, etc. See [LabelRenderParams.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelRenderParams.xsd}. + * @param printerName The name of the printer that the preview is generated for. + * The preview/output can be different for different printers, especially for tape printers + * with different print head sizes. If it is not important what printer the label is + * printed to, an empty string can be passed. In this case, the default printer metrics + * will be used. The default is LW400 for LabelWriter printers and LW400 DUO Tape for tape printers. + * + * @returns A base64-encoded PNG stream of the label image. + */ + function renderLabel(labelXml: string, renderParamsXml: string, printerName: string): string; + + /** + * Undocumented + */ + interface AddPrinterUriCallback { + (printerUri: string): any; + } + + /** + * Undocumented, removed, see http://developers.dymo.com/2013/08/14/dymo-sdk-qa/#comment-27119 + */ + function addPrinterUri( + printerUri: string, + location?: string, + successCallback?: AddPrinterUriCallback, + errorCallback?: AddPrinterUriCallback): void; + + /** + * Undocumented, removed, see http://developers.dymo.com/2013/08/14/dymo-sdk-qa/#comment-27119 + */ + function removePrinterUri(printerUri: string): void; + + /** + * Undocumented, removed, see http://developers.dymo.com/2013/08/14/dymo-sdk-qa/#comment-27119 + */ + function removeAllPrinterUri(): void; + + /** + * LabelSetBuilder is used to create a LabelSet to print multiple labels in one print job. + * LabelSet is a collection of records. Each record contains multiple pairs; each pair consists + * of the object name and the object text data/content. The data of each record are applied to all + * corresponend objects and for each record one label is printed. + */ + class LabelSetBuilder { + /** + * Converts record objects to XML format. The XML format schema is defined in [LabelSet.xsd]{@link http://labelwriter.com/software/dls/sdk/LabelSet.xsd}. + * Returned XML can be passed to dymo.label.framefork.printLabel as labelSetXml parameter. This function can be used independent of other LabelSetBuilder methods, if records data is generated by other functions. + * + * @param records The records to convert to XML. Records should be an array-like object of associative-arrays with object names as keys and object text as values. + * + * @returns An XML string. + */ + static toXml(records: {}[]): string; + + /** + * Adds a new record to the LabelSet. Returns a record object. + */ + addRecord(): ILabelSetRecord; + + /** + * Get all record objects in this LabelSetBuilder. + */ + getRecords(): ILabelSetRecord[]; + + /** + * Converts the builder's content to an XML string suitable to pass to dymo.label.framefork.printLabel. + */ + toString(): string; + } +} diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 9fe420766..c47c4248c 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Ember.js 1.0.0 +// Type definitions for Ember.js 1.11.3 // Project: http://emberjs.com/ // Definitions by: Jed Mao // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -387,8 +387,10 @@ interface DisconnectOutletOptions { interface RenderOptions { into?: string; - outlet?: string; controller?: string; + model?: any; + outlet?: string; + view?: string; } interface ModifyObserver { @@ -1683,7 +1685,21 @@ declare module Ember { cacheFor(keyName: string): any; decrementProperty(keyName: string, decrement?: number): number; endPropertyChanges(): Observable; + + /** + * Retrieves the value of a property from the object + * @param keyName + * @returns {} + */ get(keyName: string): any; + + /** + * Retrieves the value of a property from the object + * @param keyName + * @returns {} + */ + get(keyName: string): T; + getProperties(...args: string[]): {}; getProperties(keys: string[]): {}; getWithDefault(keyName: string, defaultValue: any): any; @@ -1764,10 +1780,70 @@ declare module Ember { remove(obj: any): void; toArray(): any[]; } + + // FYI - RSVP source comes from https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/promise.js module RSVP { + interface PromiseResolve { + (value?: any): void; + } + interface PromiseReject { + (reason?: any): void; + } + interface PromiseResolverFunction { + (resolve: PromiseResolve, reject: PromiseReject): void; + } + class Promise { - constructor(resolver: Function, label?: string); - then(done?: Function, fail?: Function): Promise; + + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + @class RSVP.Promise + @param {function} resolver + @param {String} label optional string for labeling the promise. + Useful for tooling. + @constructor + */ + constructor(resolver: PromiseResolverFunction, label?: string); + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + @method then + @param {Function} onFulfilled + @param {Function} onRejected + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + then(onFulfilled?: Function, onRejected?: Function): Promise; + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + @method catch + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + catch(onRejection: Function, label?: string): Promise; + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + @method finally + @param {Function} callback + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + finally(callback: Function, label?: string): Promise; } } class RenderBuffer { @@ -1789,41 +1865,531 @@ declare module Ember { elementTag: string; parentBuffer: RenderBuffer; } - class Route extends Object implements ActionHandlerMixin { - static detect(obj: any): boolean; - static detectInstance(obj: any): boolean; - /** - Iterate over each computed property for the class, passing its name and any - associated metadata (see metaForProperty) to the callback. - **/ - static eachComputedProperty(callback: Function, binding: {}): void; - /** - Returns the original hash that was passed to meta(). - @param key property name - **/ - static metaForProperty(key: string): {}; + + /** + The `Ember.Route` class is used to define individual routes. Refer to + the [routing guide](http://emberjs.com/guides/routing/) for documentation. + */ + class Route extends Object implements ActionHandlerMixin, Evented { + static isClass: boolean; static isMethod: boolean; + + /** + This hook is executed when the router enters the route. It is not executed + when the model for the route changes. + @method activate + */ activate: Function; + + /** + This hook is called after this route's model has resolved. + It follows identical async/promise semantics to `beforeModel` + but is provided the route's resolved model in addition to + the `transition`, and is therefore suited to performing + logic that can only take place after the model has already + resolved. + + Refer to documentation for `beforeModel` for a description + of transition-pausing semantics when a promise is returned + from this hook. + @method afterModel + @param {Object} resolvedModel the value returned from `model`, + or its resolved value if it was a promise + @param {Transition} transition + @return {Promise} if the value returned from this hook is + a promise, the transition will pause until the transition + resolves. Otherwise, non-promise return values are not + utilized in any way. + */ afterModel(resolvedModel: any, transition: EmberStates.Transition): RSVP.Promise; + + /** + This hook is the first of the route entry validation hooks + called when an attempt is made to transition into a route + or one of its children. It is called before `model` and + `afterModel`, and is appropriate for cases when: + 1) A decision can be made to redirect elsewhere without + needing to resolve the model first. + 2) Any async operations need to occur first before the + model is attempted to be resolved. + This hook is provided the current `transition` attempt + as a parameter, which can be used to `.abort()` the transition, + save it for a later `.retry()`, or retrieve values set + on it from a previous hook. You can also just call + `this.transitionTo` to another route to implicitly + abort the `transition`. + You can return a promise from this hook to pause the + transition until the promise resolves (or rejects). This could + be useful, for instance, for retrieving async code from + the server that is required to enter a route. + + @method beforeModel + @param {Transition} transition + @return {Promise} if the value returned from this hook is + a promise, the transition will pause until the transition + resolves. Otherwise, non-promise return values are not + utilized in any way. + */ beforeModel(transition: EmberStates.Transition): RSVP.Promise; + + /** + The controller associated with this route. + + @property controller + @type Ember.Controller + @since 1.6.0 + */ + controller: Controller; + + /** + Returns the controller for a particular route or name. + The controller instance must already have been created, either through entering the + associated route or using `generateController`. + + @method controllerFor + @param {String} name the name of the route or controller + @return {Ember.Controller} + */ controllerFor(name: string): Controller; + + /** + The name of the controller to associate with this route. + By default, Ember will lookup a route's controller that matches the name + of the route (i.e. `App.PostController` for `App.PostRoute`). However, + if you would like to define a specific controller to use, you can do so + using this property. + This is useful in many ways, as the controller specified will be: + * passed to the `setupController` method. + * used as the controller for the view being rendered by the route. + * returned from a call to `controllerFor` for the route. + @property controllerName + @type String + @default null + @since 1.4.0 + */ + controllerName: string; + + /** + This hook is executed when the router completely exits this route. It is + not executed when the model for the route changes. + @method deactivate + */ deactivate: Function; - disconnectOutlet(options?: DisconnectOutletOptions): void; - generateController(name: string, model: {}): void; - model(params: {}, transition: EmberStates.Transition): any; + + /** + Deserializes value of the query parameter based on defaultValueType + @method deserializeQueryParam + @param {Object} value + @param {String} urlKey + @param {String} defaultValueType + */ + deserializeQueryParam(value: any, urlKey: string, defaultValueType: string): any; + + /** + Disconnects a view that has been rendered into an outlet. + You may pass any or all of the following options to `disconnectOutlet`: + * `outlet`: the name of the outlet to clear (default: 'main') + * `parentView`: the name of the view containing the outlet to clear + (default: the view rendered by the parent route) + + @method disconnectOutlet + @param {Object|String} options the options hash or outlet name + */ + disconnectOutlet(options: DisconnectOutletOptions|string): void; + + /** + @method findModel + @param {String} type the model type + @param {Object} value the value passed to find + */ + findModel(type: string, value: any): any; + + /** + Generates a controller for a route. + If the optional model is passed then the controller type is determined automatically, + e.g., an ArrayController for arrays. + + @method generateController + @param {String} name the name of the controller + @param {Object} model the model to infer the type of the controller (optional) + */ + generateController(name: string, model: {}): Controller; + + /** + Perform a synchronous transition into another route without attempting + to resolve promises, update the URL, or abort any currently active + asynchronous transitions (i.e. regular transitions caused by + `transitionTo` or URL changes). + This method is handy for performing intermediate transitions on the + way to a final destination route, and is called internally by the + default implementations of the `error` and `loading` handlers. + @method intermediateTransitionTo + @param {String} name the name of the route + @param {...Object} models the model(s) to be used while transitioning + to the route. + @since 1.2.0 + */ + intermediateTransitionTo(name: string, ...models: any[]): void; + + /** + A hook you can implement to convert the URL into the model for + this route. + + @method model + @param {Object} params the parameters extracted from the URL + @param {Transition} transition + @return {Object|Promise} the model for this route. If + a promise is returned, the transition will pause until + the promise resolves, and the resolved value of the promise + will be used as the model for this route. + */ + model(params: {}, transition: EmberStates.Transition): any|RSVP.Promise; + + /** + Returns the model of a parent (or any ancestor) route + in a route hierarchy. During a transition, all routes + must resolve a model object, and if a route + needs access to a parent route's model in order to + resolve a model (or just reuse the model from a parent), + it can call `this.modelFor(theNameOfParentRoute)` to + retrieve it. + + @method modelFor + @param {String} name the name of the route + @return {Object} the model object + */ modelFor(name: string): {}; + + /** + Retrieves parameters, for current route using the state.params + variable and getQueryParamsFor, using the supplied routeName. + @method paramsFor + @param {String} name + */ + paramsFor(name: string) : any; + + /** + Configuration hash for this route's queryParams. + @property queryParams + @for Ember.Route + @type Hash + */ + queryParams: {}; + + /** + Refresh the model on this route and any child routes, firing the + `beforeModel`, `model`, and `afterModel` hooks in a similar fashion + to how routes are entered when transitioning in from other route. + The current route params (e.g. `article_id`) will be passed in + to the respective model hooks, and if a different model is returned, + `setupController` and associated route hooks will re-fire as well. + An example usage of this method is re-querying the server for the + latest information using the same parameters as when the route + was first entered. + Note that this will cause `model` hooks to fire even on routes + that were provided a model object when the route was initially + entered. + @method refresh + @return {Transition} the transition object associated with this + attempted transition + @since 1.4.0 + */ + redirect(): EmberStates.Transition; + + + /** + Refresh the model on this route and any child routes, firing the + `beforeModel`, `model`, and `afterModel` hooks in a similar fashion + to how routes are entered when transitioning in from other route. + The current route params (e.g. `article_id`) will be passed in + to the respective model hooks, and if a different model is returned, + `setupController` and associated route hooks will re-fire as well. + An example usage of this method is re-querying the server for the + latest information using the same parameters as when the route + was first entered. + Note that this will cause `model` hooks to fire even on routes + that were provided a model object when the route was initially + entered. + @method refresh + @return {Transition} the transition object associated with this + attempted transition + @since 1.4.0 + */ + refresh(): EmberStates.Transition; + + /** + `render` is used to render a template into a region of another template + (indicated by an `{{outlet}}`). `render` is used both during the entry + phase of routing (via the `renderTemplate` hook) and later in response to + user interaction. + + @method render + @param {String} name the name of the template to render + @param {Object} [options] the options + @param {String} [options.into] the template to render into, + referenced by name. Defaults to the parent template + @param {String} [options.outlet] the outlet inside `options.template` to render into. + Defaults to 'main' + @param {String|Object} [options.controller] the controller to use for this template, + referenced by name or as a controller instance. Defaults to the Route's paired controller + @param {Object} [options.model] the model object to set on `options.controller`. + Defaults to the return value of the Route's model hook + */ render(name: string, options?: RenderOptions): void; + + /** + A hook you can use to render the template for the current route. + This method is called with the controller for the current route and the + model supplied by the `model` hook. By default, it renders the route's + template, configured with the controller for the route. + This method can be overridden to set up and render additional or + alternative templates. + + @method renderTemplate + @param {Object} controller the route's controller + @param {Object} model the route's model + */ renderTemplate(controller: Controller, model: {}): void; - // ReSharper disable once InconsistentNaming - replaceWith(name: string, ...object: any[]): void; - send(name: string, ...args: any[]): void; + + /** + Transition into another route while replacing the current URL, if possible. + This will replace the current history entry instead of adding a new one. + Beside that, it is identical to `transitionTo` in all other respects. See + 'transitionTo' for additional information regarding multiple models. + + @method replaceWith + @param {String} name the name of the route or a URL + @param {...Object} models the model(s) or identifier(s) to be used while + transitioning to the route. + @return {Transition} the transition object associated with this + attempted transition + */ + replaceWith(name: string, ...models: any[]): void; + + /** + A hook you can use to reset controller values either when the model + changes or the route is exiting. + + @method resetController + @param {Controller} controller instance + @param {Boolean} isExiting + @param {Object} transition + @since 1.7.0 + */ + resetController(controller: Ember.Controller, isExiting: boolean, transition: any): void; + + /** + A hook you can implement to convert the route's model into parameters + for the URL. + + The default `serialize` method will insert the model's `id` into the + route's dynamic segment (in this case, `:post_id`) if the segment contains '_id'. + If the route has multiple dynamic segments or does not contain '_id', `serialize` + will return `Ember.getProperties(model, params)` + This method is called when `transitionTo` is called with a context + in order to populate the URL. + @method serialize + @param {Object} model the route's model + @param {Array} params an Array of parameter names for the current + route (in the example, `['post_id']`. + @return {Object} the serialized parameters + */ serialize(model: {}, params: string[]): string; + + /** + Serializes value of the query parameter based on defaultValueType + @method serializeQueryParam + @param {Object} value + @param {String} urlKey + @param {String} defaultValueType + */ + serializeQueryParam(value: any, urlKey: string, defaultValueType: string): string; + + /** + Serializes the query parameter key + @method serializeQueryParamKey + @param {String} controllerPropertyName + */ + serializeQueryParamKey(controllerPropertyName: string): string; + + /** + A hook you can use to setup the controller for the current route. + This method is called with the controller for the current route and the + model supplied by the `model` hook. + By default, the `setupController` hook sets the `model` property of + the controller to the `model`. + If you implement the `setupController` hook in your Route, it will + prevent this default behavior. If you want to preserve that behavior + when implementing your `setupController` function, make sure to call + `_super` + @method setupController + @param {Controller} controller instance + @param {Object} model + */ setupController(controller: Controller, model: {}): void; - // ReSharper disable once InconsistentNaming + + /** + Store property provides a hook for data persistence libraries to inject themselves. + By default, this store property provides the exact same functionality previously + in the model hook. + Currently, the required interface is: + `store.find(modelName, findArguments)` + @method store + @param {Object} store + */ + store(store: any): any; + + /** + The name of the template to use by default when rendering this routes + template. + This is similar with `viewName`, but is useful when you just want a custom + template without a view. + + @property templateName + @type String + @default null + @since 1.4.0 + */ + templateName: string; + + /** + Transition the application into another route. The route may + be either a single route or route path + + @method transitionTo + @param {String} name the name of the route or a URL + @param {...Object} models the model(s) or identifier(s) to be used while + transitioning to the route. + @param {Object} [options] optional hash with a queryParams property + containing a mapping of query parameters + @return {Transition} the transition object associated with this + attempted transition + */ transitionTo(name: string, ...object: any[]): EmberStates.Transition; + + /** + The name of the view to use by default when rendering this routes template. + When rendering a template, the route will, by default, determine the + template and view to use from the name of the route itself. If you need to + define a specific view, set this property. + This is useful when multiple routes would benefit from using the same view + because it doesn't require a custom `renderTemplate` method. + @property viewName + @type String + @default null + @since 1.4.0 + */ + viewName: string; + + // ActionHandlerMixin methods + + /** + Sends an action to the router, which will delegate it to the currently + active route hierarchy per the bubbling rules explained under actions + + @method send + @param {String} actionName The action to trigger + @param {*} context a context to send with the action + */ + send(name: string, ...args: any[]): void; + + /** + The collection of functions, keyed by name, available on this + `ActionHandler` as action targets. + These functions will be invoked when a matching `{{action}}` is triggered + from within a template and the application's current route is this route. + Actions can also be invoked from other parts of your application + via `ActionHandler#send`. + The `actions` hash will inherit action handlers from + the `actions` hash defined on extended parent classes + or mixins rather than just replace the entire hash. + + Within a Controller, Route, View or Component's action handler, + the value of the `this` context is the Controller, Route, View or + Component object: + + It is also possible to call `this._super.apply(this, arguments)` from within an + action handler if it overrides a handler defined on a parent + class or mixin. + + ## Bubbling + By default, an action will stop bubbling once a handler defined + on the `actions` hash handles it. To continue bubbling the action, + you must return `true` from the handler + + @property actions + @type Hash + @default null + */ actions: ActionsHash; + + // Evented methods + + /** + Subscribes to a named event with given function. + + An optional target can be passed in as the 2nd argument that will + be set as the "this" for the callback. This is a good way to give your + function access to the object triggering the event. When the target + parameter is used the callback becomes the third argument. + + @method on + @param {String} name The name of the event + @param {Object} [target] The "this" binding for the callback + @param {Function} method The callback to execute + @return this + */ + on(name: string, target: any, method: Function): Evented; + + /** + Subscribes a function to a named event and then cancels the subscription + after the first time the event is triggered. It is good to use ``one`` when + you only care about the first time an event has taken place. + This function takes an optional 2nd argument that will become the "this" + value for the callback. If this argument is passed then the 3rd argument + becomes the function. + + @method one + @param {String} name The name of the event + @param {Object} [target] The "this" binding for the callback + @param {Function} method The callback to execute + @return this + */ + one(name: string, target: any, method: Function): Evented; + + /** + Triggers a named event for the object. Any additional arguments + will be passed as parameters to the functions that are subscribed to the + event. + + @method trigger + @param {String} name The name of the event + @param {Object...} args Optional arguments to pass on + */ + trigger(name: string, ...args: string[]): void; + + /** + Cancels subscription for given name, target, and method. + + @method off + @param {String} name The name of the event + @param {Object} target The target of the subscription + @param {Function} method The function of the subscription + @return this + */ + off(name: string, target:any , method: Function): Evented; + + /** + Checks to see if object has any subscriptions for named event. + + @method has + @param {String} name The name of the event + @return {Boolean} does the object have a subscription for event + */ + has(name: string): boolean; } + class Router extends Object { static detect(obj: any): boolean; static detectInstance(obj: any): boolean; @@ -2264,7 +2830,7 @@ declare module Ember { function compare(v: any, w: any): number; // ReSharper disable once DuplicatingLocalDeclaration var computed: { - (callback: Function): ComputedProperty; + (...args: any[]): ComputedProperty; alias(dependentKey: string): ComputedProperty; and(...args: string[]): ComputedProperty; any(...args: string[]): ComputedProperty; @@ -2350,7 +2916,7 @@ declare module Ember { **/ var none: typeof deprecateFunc; function normalizeTuple(target: any, path: string): any[]; - function observer(func: Function, ...args: string[]): Function; + function observer(...args: any[]): Function; function observersFor(obj: any, path: string): any[]; function onLoad(name: string, callback: Function): void; function oneWay(obj: any, to: string, from: string): Binding; @@ -2531,6 +3097,9 @@ declare module Em { class Observable extends Ember.Observable { } class OrderedSet extends Ember.OrderedSet { } module RSVP { + interface PromiseResolve extends Ember.RSVP.PromiseResolve { } + interface PromiseReject extends Ember.RSVP.PromiseReject { } + interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } class Promise extends Ember.RSVP.Promise { } } class RenderBuffer extends Ember.RenderBuffer { } @@ -2772,6 +3341,9 @@ declare module "Ember" { class Observable extends Ember.Observable { } class OrderedSet extends Ember.OrderedSet { } module RSVP { + interface PromiseResolve extends Ember.RSVP.PromiseResolve { } + interface PromiseReject extends Ember.RSVP.PromiseReject { } + interface PromiseResolverFunction extends Ember.RSVP.PromiseResolverFunction { } class Promise extends Ember.RSVP.Promise { } } class RenderBuffer extends Ember.RenderBuffer { } diff --git a/es6-promise/es6-promise-tests.ts b/es6-promise/es6-promise-tests.ts index dc54f3b1b..0980ac26c 100644 --- a/es6-promise/es6-promise-tests.ts +++ b/es6-promise/es6-promise-tests.ts @@ -160,3 +160,32 @@ getJSON('story.json').then(function(story: Story) { }).then(function() { (document.querySelector('.spinner')).style.display = 'none'; }); + +interface T1 { + __t1: string; +} + +interface T2 { + __t2: string; +} + +interface T3 { + __t3: string; +} + +function f1(): Promise { + return Promise.resolve({ __t1: "foo_t1" }); +} + +function f2(x: T1): T2 { + return { __t2: x.__t1 + ":foo_21" }; +} + +var x3 = f1() + .then(f2, (e: Error) => { + console.log("error 1"); + throw e; +}) + .then((x: T2) => { + return { __t3: x.__t2 + "bar" }; +}); \ No newline at end of file diff --git a/es6-promise/es6-promise.d.ts b/es6-promise/es6-promise.d.ts index 4a793e540..86c82273a 100644 --- a/es6-promise/es6-promise.d.ts +++ b/es6-promise/es6-promise.d.ts @@ -4,7 +4,8 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Thenable { - then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; } declare class Promise implements Thenable { @@ -27,7 +28,8 @@ declare class Promise implements Thenable { * @param onFulfilled called when/if "promise" resolves * @param onRejected called when/if "promise" rejects */ - then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Promise; /** * Sugar for promise.then(undefined, onRejected) diff --git a/fabricjs/fabricjs-tests.ts b/fabricjs/fabricjs-tests.ts index e59212d80..c3dfd8d6d 100644 --- a/fabricjs/fabricjs-tests.ts +++ b/fabricjs/fabricjs-tests.ts @@ -1,1065 +1,1063 @@ /// function sample1() { - var canvas = new fabric.Canvas('c', { - hoverCursor: 'pointer', - selection: false, + var canvas = new fabric.Canvas('c', { + hoverCursor: 'pointer', + selection: false, + }); + + canvas.on('object:moving', function(e: fabric.IEvent) { + e.target.opacity = 0.5; + }); + canvas.on('object:modified', function(e: fabric.IEvent) { + e.target.opacity = 1; + }); + + for (var i = 0, len = 15; i < len; i++) { + fabric.Image.fromURL('../assets/ladybug.png', function(img) { + img.set({ + left: fabric.util.getRandomInt(0, 600), + top: fabric.util.getRandomInt(0, 500), + angle: fabric.util.getRandomInt(0, 90) + }); + + img.perPixelTargetFind = true; + // img.targetFindTolerance = 4; + img.hasControls = img.hasBorders = false; + + img.scale(fabric.util.getRandomInt(50, 100) / 100); + + canvas.add(img); }); - - canvas.on({ - 'object:moving': function (e) { - (e.target).opacity = 0.5; - }, - 'object:modified': function (e) { - (e.target).opacity = 1; - } - }); - - for (var i = 0, len = 15; i < len; i++) { - fabric.Image.fromURL('../assets/ladybug.png', function (img) { - img.set({ - left: fabric.util.getRandomInt(0, 600), - top: fabric.util.getRandomInt(0, 500), - angle: fabric.util.getRandomInt(0, 90) - }); - - img.perPixelTargetFind = true; - // img.targetFindTolerance = 4; - img.hasControls = img.hasBorders = false; - - img.scale(fabric.util.getRandomInt(50, 100) / 100); - - canvas.add(img); - }); - } + } } function sample2() { - var dot, i, - t1, t2, - startTimer = function () { - t1 = new Date().getTime(); - return t1; - }, - stopTimer = function () { - t2 = new Date().getTime(); - return t2 - t1; - }, - getRandomInt = fabric.util.getRandomInt, - rainbow = ["#ffcc66", "#ccff66", "#66ccff", "#ff6fcf", "#ff6666"], - rainbowEnd = rainbow.length - 1; + var dot, i, + t1, t2, + startTimer = function() { + t1 = new Date().getTime(); + return t1; + }, + stopTimer = function() { + t2 = new Date().getTime(); + return t2 - t1; + }, + getRandomInt = fabric.util.getRandomInt, + rainbow = ["#ffcc66", "#ccff66", "#66ccff", "#ff6fcf", "#ff6666"], + rainbowEnd = rainbow.length - 1; - // - // Rendering canvas #1 - // - var canvas1 = new fabric.Canvas('c1', { backgroundColor: "#000" }), - results1 = document.getElementById('results-c1'); + // + // Rendering canvas #1 + // + var canvas1 = new fabric.Canvas('c1', { backgroundColor: "#000" }), + results1 = document.getElementById('results-c1'); - startTimer(); - for (i = 100; i >= 0; i--) { - dot = new fabric.Circle({ - left: getRandomInt(0, 400), - top: getRandomInt(0, 350), - radius: 3, - fill: rainbow[getRandomInt(0, rainbowEnd)] - }); - canvas1.add(dot); - } - results1.innerHTML = 'Regular rendering of 100 elements in ' + stopTimer() + 'ms'; + startTimer(); + for (i = 100; i >= 0; i--) { + dot = new fabric.Circle({ + left: getRandomInt(0, 400), + top: getRandomInt(0, 350), + radius: 3, + fill: rainbow[getRandomInt(0, rainbowEnd)] + }); + canvas1.add(dot); + } + results1.innerHTML = 'Regular rendering of 100 elements in ' + stopTimer() + 'ms'; - // - // Rendering canvas #2 - // - var canvas2 = new fabric.Canvas('c2', { backgroundColor: "#000", renderOnAddition: false }), - results2 = document.getElementById('results-c2'); + // + // Rendering canvas #2 + // + var canvas2 = new fabric.Canvas('c2', { backgroundColor: "#000", renderOnAddition: false }), + results2 = document.getElementById('results-c2'); - startTimer(); - for (i = 1000; i >= 0; i--) { - dot = new fabric.Circle({ - left: getRandomInt(0, 400), - top: getRandomInt(0, 350), - radius: 3, - fill: rainbow[getRandomInt(0, rainbowEnd)] - }); - canvas2.add(dot); - } - canvas2.renderAll(); // Note, calling renderAll() is important in this case - results2.innerHTML = 'Rendering 1000 elements using canvas.renderOnAddition = false in ' + stopTimer() + 'ms'; + startTimer(); + for (i = 1000; i >= 0; i--) { + dot = new fabric.Circle({ + left: getRandomInt(0, 400), + top: getRandomInt(0, 350), + radius: 3, + fill: rainbow[getRandomInt(0, rainbowEnd)] + }); + canvas2.add(dot); + } + canvas2.renderAll(); // Note, calling renderAll() is important in this case + results2.innerHTML = 'Rendering 1000 elements using canvas.renderOnAddition = false in ' + stopTimer() + 'ms'; } function sample3() { - var $ = function (id) {return document.getElementById(id) }; + var $ = function(id) { return document.getElementById(id) }; - function applyFilter(index, filter) { - var obj = canvas.getActiveObject(); - obj.filters[index] = filter; - obj.applyFilters(canvas.renderAll.bind(canvas)); - } - - function applyFilterValue(index, prop, value) { - var obj = canvas.getActiveObject(); - if (obj.filters[index]) { - obj.filters[index][prop] = value; - obj.applyFilters(canvas.renderAll.bind(canvas)); - } - } - - var canvas = new fabric.Canvas('c', { backgroundImage: '../lib/bg.png' }), - f = fabric.Image.filters; - - canvas.on({ - 'object:selected': function () { - fabric.util.toArray(document.getElementsByTagName('input')).forEach(function (el) { el.disabled = false; }) - - var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2', 'brightness', - 'noise', 'gradient-transparency', 'pixelate', 'blur', 'sharpen']; - - for (var i = 0; i < filters.length; i++) { - var checkBox = $(filters[i]); - var image = canvas.getActiveObject(); - checkBox.checked = !!image.filters[i]; - } - }, - 'selection:cleared': function () { - fabric.util.toArray(document.getElementsByTagName('input')).forEach(function (el) { el.disabled = true; }) + function applyFilter(index, filter) { + var obj = canvas.getActiveObject(); + obj.filters[index] = filter; + obj.applyFilters(canvas.renderAll.bind(canvas)); } - }); - fabric.Image.fromURL('../assets/printio.png', function (img) { - var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9); - canvas.add(oImg).renderAll(); - canvas.setActiveObject(oImg); - }); + function applyFilterValue(index, prop, value) { + var obj = canvas.getActiveObject(); + if (obj.filters[index]) { + obj.filters[index][prop] = value; + obj.applyFilters(canvas.renderAll.bind(canvas)); + } + } - $('grayscale').onclick = function () { - applyFilter(0, this.checked && new f.Grayscale()); - }; - $('invert').onclick = function () { - applyFilter(1, this.checked && new f.Invert()); - }; - $('remove-white').onclick = function () { - applyFilter(2, this.checked && new f.RemoveWhite({ - threshold: ($('remove-white-threshold')).value, - distance: ($('remove-white-distance')).value - })); - }; - $('remove-white-threshold').onchange = function () { - applyFilterValue(2, 'threshold', this.value); - }; - $('remove-white-distance').onchange = function () { - applyFilterValue(2, 'distance', this.value); - }; - $('sepia').onclick = function () { - applyFilter(3, this.checked && new f.Sepia()); - }; - $('sepia2').onclick = function () { - applyFilter(4, this.checked && new f.Sepia2()); - }; - $('brightness').onclick = function () { - applyFilter(5, this.checked && new f.Brightness({ - brightness: parseInt(($('brightness-value')).value, 10) - })); - }; - $('brightness-value').onchange = function () { - applyFilterValue(5, 'brightness', parseInt(this.value, 10)); - }; - $('noise').onclick = function () { - applyFilter(6, this.checked && new f.Noise({ - noise: parseInt(($('noise-value')).value, 10) - })); - }; - $('noise-value').onchange = function () { - applyFilterValue(6, 'noise', parseInt(this.value, 10)); - }; - $('gradient-transparency').onclick = function () { - applyFilter(7, this.checked && new f.GradientTransparency({ - threshold: parseInt(($('gradient-transparency-value')).value, 10) - })); - }; - $('gradient-transparency-value').onchange = function () { - applyFilterValue(7, 'threshold', parseInt(this.value, 10)); - }; - $('pixelate').onclick = function () { - applyFilter(8, this.checked && new f.Pixelate({ - blocksize: parseInt(($('pixelate-value')).value, 10) - })); - }; - $('pixelate-value').onchange = function () { - applyFilterValue(8, 'blocksize', parseInt(this.value, 10)); - }; - $('blur').onclick = function () { - applyFilter(9, this.checked && new f.Convolute({ - matrix: [1 / 9, 1 / 9, 1 / 9, - 1 / 9, 1 / 9, 1 / 9, - 1 / 9, 1 / 9, 1 / 9] - })); - }; - $('sharpen').onclick = function () { - applyFilter(10, this.checked && new f.Convolute({ - matrix: [0, -1, 0, - -1, 5, -1, - 0, -1, 0] - })); - }; - $('emboss').onclick = function () { - applyFilter(11, this.checked && new f.Convolute({ - matrix: [1, 1, 1, - 1, 0.7, -1, - -1, -1, -1] - })); - }; + var canvas = new fabric.Canvas('c', { backgroundImage: '../lib/bg.png' }), + f = fabric.Image.filters; + + canvas.on({ + 'object:selected': function() { + fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = false; }) + + var filters = ['grayscale', 'invert', 'remove-white', 'sepia', 'sepia2', 'brightness', + 'noise', 'gradient-transparency', 'pixelate', 'blur', 'sharpen']; + + for (var i = 0; i < filters.length; i++) { + var checkBox = $(filters[i]); + var image = canvas.getActiveObject(); + checkBox.checked = !!image.filters[i]; + } + }, + 'selection:cleared': function() { + fabric.util.toArray(document.getElementsByTagName('input')).forEach(function(el) { el.disabled = true; }) + } + }); + + fabric.Image.fromURL('../assets/printio.png', function(img) { + var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9); + canvas.add(oImg).renderAll(); + canvas.setActiveObject(oImg); + }); + + $('grayscale').onclick = function() { + applyFilter(0, this.checked && new f.Grayscale()); + }; + $('invert').onclick = function() { + applyFilter(1, this.checked && new f.Invert()); + }; + $('remove-white').onclick = function() { + applyFilter(2, this.checked && new f.RemoveWhite({ + threshold: parseInt(($('remove-white-threshold')).value), + distance: parseInt(($('remove-white-distance')).value) + })); + }; + $('remove-white-threshold').onchange = function() { + applyFilterValue(2, 'threshold', this.value); + }; + $('remove-white-distance').onchange = function() { + applyFilterValue(2, 'distance', this.value); + }; + $('sepia').onclick = function() { + applyFilter(3, this.checked && new f.Sepia()); + }; + $('sepia2').onclick = function() { + applyFilter(4, this.checked && new f.Sepia2()); + }; + $('brightness').onclick = function() { + applyFilter(5, this.checked && new f.Brightness({ + brightness: parseInt(($('brightness-value')).value, 10) + })); + }; + $('brightness-value').onchange = function() { + applyFilterValue(5, 'brightness', parseInt(this.value, 10)); + }; + $('noise').onclick = function() { + applyFilter(6, this.checked && new f.Noise({ + noise: parseInt(($('noise-value')).value, 10) + })); + }; + $('noise-value').onchange = function() { + applyFilterValue(6, 'noise', parseInt(this.value, 10)); + }; + $('gradient-transparency').onclick = function() { + applyFilter(7, this.checked && new f.GradientTransparency({ + threshold: parseInt(($('gradient-transparency-value')).value, 10) + })); + }; + $('gradient-transparency-value').onchange = function() { + applyFilterValue(7, 'threshold', parseInt(this.value, 10)); + }; + $('pixelate').onclick = function() { + applyFilter(8, this.checked && new f.Pixelate({ + blocksize: parseInt(($('pixelate-value')).value, 10) + })); + }; + $('pixelate-value').onchange = function() { + applyFilterValue(8, 'blocksize', parseInt(this.value, 10)); + }; + $('blur').onclick = function() { + applyFilter(9, this.checked && new f.Convolute({ + matrix: [1 / 9, 1 / 9, 1 / 9, + 1 / 9, 1 / 9, 1 / 9, + 1 / 9, 1 / 9, 1 / 9] + })); + }; + $('sharpen').onclick = function() { + applyFilter(10, this.checked && new f.Convolute({ + matrix: [0, -1, 0, + -1, 5, -1, + 0, -1, 0] + })); + }; + $('emboss').onclick = function() { + applyFilter(11, this.checked && new f.Convolute({ + matrix: [1, 1, 1, + 1, 0.7, -1, + -1, -1, -1] + })); + }; } function sample4() { - var canvas = new fabric.Canvas('c'); - var $ = function (id) { return document.getElementById(id); }; + var canvas = new fabric.Canvas('c'); + var $ = function(id) { return document.getElementById(id); }; - var rect = new fabric.Rect({ - width: 100, - height: 100, - top: 150, - left: 150, - fill: 'rgba(255,0,0,0.5)' - }); + var rect = new fabric.Rect({ + width: 100, + height: 100, + top: 150, + left: 150, + fill: 'rgba(255,0,0,0.5)' + }); - canvas.add(rect); + canvas.add(rect); - var angleControl = $('angle-control'); - angleControl.onchange = function () { - rect.setAngle(this.value).setCoords(); - canvas.renderAll(); - }; + var angleControl = $('angle-control'); + angleControl.onchange = function() { + rect.setAngle(this.value).setCoords(); + canvas.renderAll(); + }; - var scaleControl = $('scale-control'); - scaleControl.onchange = function () { - rect.scale(this.value).setCoords(); - canvas.renderAll(); - }; + var scaleControl = $('scale-control'); + scaleControl.onchange = function() { + rect.scale(this.value).setCoords(); + canvas.renderAll(); + }; - var topControl = $('top-control'); - topControl.onchange = function () { - rect.setTop(this.value).setCoords(); - canvas.renderAll(); - }; + var topControl = $('top-control'); + topControl.onchange = function() { + rect.setTop(this.value).setCoords(); + canvas.renderAll(); + }; - var leftControl = $('left-control'); - leftControl.onchange = function () { - rect.setLeft(this.value).setCoords(); - canvas.renderAll(); - }; + var leftControl = $('left-control'); + leftControl.onchange = function() { + rect.setLeft(this.value).setCoords(); + canvas.renderAll(); + }; - function updateControls() { + function updateControls() { - scaleControl.value = rect.getScaleX().toString(); - angleControl.value = rect.getAngle().toString(); - leftControl.value = rect.getLeft().toString(); - topControl.value = rect.getTop().toString(); - } - canvas.on({ - 'object:moving': updateControls, - 'object:scaling': updateControls, - 'object:resizing': updateControls - }); + scaleControl.value = rect.getScaleX().toString(); + angleControl.value = rect.getAngle().toString(); + leftControl.value = rect.getLeft().toString(); + topControl.value = rect.getTop().toString(); + } + canvas.on({ + 'object:moving': updateControls, + 'object:scaling': updateControls, + 'object:resizing': updateControls + }); } module fabric { - export interface CircleWithLineInfos extends ICircle { - line1?: ILine; - line2?: ILine; - line3?: ILine; - line4?: ILine; - } + export interface CircleWithLineInfos extends ICircle { + line1?: ILine; + line2?: ILine; + line3?: ILine; + line4?: ILine; + } } function sample5() { - var makeCircle = function (left: number, top: number, line1?: fabric.ILine, line2?: fabric.ILine, line3?: fabric.ILine, line4?: fabric.ILine): fabric.ICircle { - var c = new fabric.Circle({ - left: left, - top: top, - strokeWidth: 5, - radius: 12, - fill: '#fff', - stroke: '#666' - }); - - c.line1 = line1; - c.line2 = line2; - c.line3 = line3; - c.line4 = line4; - c.hasControls = c.hasBorders = false; - return c; - } - -function makeLine(coords: number[]) { - return new fabric.Line(coords, { - fill: 'red', - strokeWidth: 5, - selectable: false - }); - } - - var canvas = new fabric.Canvas('c', { selection: false }); - - var line = makeLine([250, 125, 250, 175]), - line2 = makeLine([250, 175, 250, 250]), - line3 = makeLine([250, 250, 300, 350]), - line4 = makeLine([250, 250, 200, 350]), - line5 = makeLine([250, 175, 175, 225]), - line6 = makeLine([250, 175, 325, 225]); - - canvas.add(line, line2, line3, line4, line5, line6); - - canvas.add( - makeCircle(line.x1, line.y1, null, line), - makeCircle(line.x2, line.y2, line, line2, line5, line6), - makeCircle(line2.x2, line2.y2, line2, line3, line4), - makeCircle(line3.x2, line3.y2, line3), - makeCircle(line4.x2, line4.y2, line4), - makeCircle(line5.x2, line5.y2, line5), - makeCircle(line6.x2, line6.y2, line6) - ); - - canvas.on('object:moving', function (e) { - var p = e.target; - p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top }); - p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top }); - p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top }); - p.line4 && p.line4.set({ 'x1': p.left, 'y1': p.top }); - canvas.renderAll(); + var makeCircle = function(left: number, top: number, line1?: fabric.ILine, line2?: fabric.ILine, line3?: fabric.ILine, line4?: fabric.ILine): fabric.ICircle { + var c = new fabric.Circle({ + left: left, + top: top, + strokeWidth: 5, + radius: 12, + fill: '#fff', + stroke: '#666' }); + + c.line1 = line1; + c.line2 = line2; + c.line3 = line3; + c.line4 = line4; + c.hasControls = c.hasBorders = false; + return c; + } + + function makeLine(coords: number[]) { + return new fabric.Line(coords, { + fill: 'red', + strokeWidth: 5, + selectable: false + }); + } + + var canvas = new fabric.Canvas('c', { selection: false }); + + var line = makeLine([250, 125, 250, 175]), + line2 = makeLine([250, 175, 250, 250]), + line3 = makeLine([250, 250, 300, 350]), + line4 = makeLine([250, 250, 200, 350]), + line5 = makeLine([250, 175, 175, 225]), + line6 = makeLine([250, 175, 325, 225]); + + canvas.add(line, line2, line3, line4, line5, line6); + + canvas.add( + makeCircle(line.x1, line.y1, null, line), + makeCircle(line.x2, line.y2, line, line2, line5, line6), + makeCircle(line2.x2, line2.y2, line2, line3, line4), + makeCircle(line3.x2, line3.y2, line3), + makeCircle(line4.x2, line4.y2, line4), + makeCircle(line5.x2, line5.y2, line5), + makeCircle(line6.x2, line6.y2, line6) + ); + + canvas.on('object:moving', function(e) { + var p = e.target; + p.line1 && p.line1.set({ 'x2': p.left, 'y2': p.top }); + p.line2 && p.line2.set({ 'x1': p.left, 'y1': p.top }); + p.line3 && p.line3.set({ 'x1': p.left, 'y1': p.top }); + p.line4 && p.line4.set({ 'x1': p.left, 'y1': p.top }); + canvas.renderAll(); + }); } function sample6() { - var canvas = new fabric.Canvas('c'); - fabric.loadSVGFromURL('../assets/135.svg', function (objects) { - var obj = objects[0].scale(0.25); - canvas.centerObject(obj); - canvas.add(obj); + var canvas = new fabric.Canvas('c'); + fabric.loadSVGFromURL('../assets/135.svg', function(objects) { + var obj = objects[0].scale(0.25); + canvas.centerObject(obj); + canvas.add(obj); - canvas.add(obj.clone().set({ left: 100, top: 100, angle: -15 })); - canvas.add(obj.clone().set({ left: 480, top: 100, angle: 15 })); - canvas.add(obj.clone().set({ left: 100, top: 400, angle: -15 })); - canvas.add(obj.clone().set({ left: 480, top: 400, angle: 15 })); + canvas.add(obj.clone(() => {}).set({ left: 100, top: 100, angle: -15 })); + canvas.add(obj.clone(() => {}).set({ left: 480, top: 100, angle: 15 })); + canvas.add(obj.clone(() => {}).set({ left: 100, top: 400, angle: -15 })); + canvas.add(obj.clone(() => {}).set({ left: 480, top: 400, angle: 15 })); - canvas.on('mouse:move', function (options) { - var p = canvas.getPointer(options.e); + canvas.on('mouse:move', function(options) { + var p = canvas.getPointer(options.e); - canvas.forEachObject(function (obj) { - var distX = Math.abs(p.x - obj.left), - distY = Math.abs(p.y - obj.top), - dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2))); - obj.setOpacity(1 / (dist / 20)); - }); - - }); + canvas.forEachObject(function(obj) { + var distX = Math.abs(p.x - obj.left), + distY = Math.abs(p.y - obj.top), + dist = Math.round(Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2))); + obj.setOpacity(1 / (dist / 20)); + }); }); + + }); } module fabric { - export interface ImageWithInfo extends IImage { - movingLeft: boolean; - } + export interface ImageWithInfo extends IImage { + movingLeft: boolean; + } } function sample7() { - var canvas = new fabric.Canvas('c', { selection: false }); + var canvas = new fabric.Canvas('c', { selection: false }); - setInterval(function () { - fabric.Image.fromURL('../assets/ladybug.png', function (obj) { - var img = obj; - img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50); - img.movingLeft = !!Math.round(Math.random()); - canvas.add(img); - }); - }, 1000); - - - var animate = (function animate() { - canvas.forEachObject(function (obj) { - var img = obj; - img.left += (img.movingLeft ? -1 : 1); - img.top += 1; - if (img.left > 900 || img.top > 500) { - canvas.remove(img); - } - else { - img.setAngle(img.getAngle() + 2); - } - }); - canvas.renderAll(); - window.requestAnimationFrame(animate); + setInterval(function() { + fabric.Image.fromURL('../assets/ladybug.png', function(obj) { + var img = obj; + img.set('left', fabric.util.getRandomInt(200, 600)).set('top', -50); + img.movingLeft = !!Math.round(Math.random()); + canvas.add(img); }); + }, 1000); - animate(); + + var animate = (function animate() { + canvas.forEachObject(function(obj) { + var img = obj; + img.left += (img.movingLeft ? -1 : 1); + img.top += 1; + if (img.left > 900 || img.top > 500) { + canvas.remove(img); + } + else { + img.setAngle(img.getAngle() + 2); + } + }); + canvas.renderAll(); + window.requestAnimationFrame(animate); + }); + + animate(); } function sample8() { - function pad(str: string, length: number): string { - while (str.length < length) { - str = '0' + str; - } - return str; - }; + function pad(str: string, length: number): string { + while (str.length < length) { + str = '0' + str; + } + return str; + }; - var getRandomInt = fabric.util.getRandomInt; + var getRandomInt = fabric.util.getRandomInt; - function getRandomColor() { - return ( - pad(getRandomInt(0, 255).toString(16), 2) + - pad(getRandomInt(0, 255).toString(16), 2) + - pad(getRandomInt(0, 255).toString(16), 2) - ); + function getRandomColor() { + return ( + pad(getRandomInt(0, 255).toString(16), 2) + + pad(getRandomInt(0, 255).toString(16), 2) + + pad(getRandomInt(0, 255).toString(16), 2) + ); + } + + function getRandomNum(min: number, max: number): number { + return Math.random() * (max - min) + min; + } + + if (/(iPhone|iPod|iPad)/i.test(navigator.userAgent)) { + fabric.Object.prototype.cornersize = 30; + } + + var canvas = new fabric.Canvas('canvas'); + // canvas.controlsAboveOverlay = true; + + function updateComplexity() { + setTimeout(function() { + var element = document.getElementById('complexity').childNodes[1]; + element.innerHTML = ' ' + canvas.complexity(); + }, 100); + } + + document.getElementById('commands').onclick = function(ev: any) { + var ev: any = ev || window.event; + + if (ev.preventDefault) { + ev.preventDefault() + } + else if (ev.returnValue) { + ev.returnValue = false; } - function getRandomNum(min: number, max: number): number { - return Math.random() * (max - min) + min; + var element: any = ev.target || ev.srcElement; + if (element.nodeName.toLowerCase() === 'strong') { + element = element.parentNode; } - if (/(iPhone|iPod|iPad)/i.test(navigator.userAgent)) { - fabric.Object.prototype.cornersize = 30; - } - - var canvas = new fabric.Canvas('canvas'); - // canvas.controlsAboveOverlay = true; - - function updateComplexity() { - setTimeout(function () { - var element = document.getElementById('complexity').childNodes[1]; - element.innerHTML = ' ' + canvas.complexity(); - }, 100); - } - - document.getElementById('commands').onclick = function (ev: any) { - var ev: any = ev || window.event; - - if (ev.preventDefault) { - ev.preventDefault() - } - else if (ev.returnValue) { - ev.returnValue = false; - } - - var element: any = ev.target || ev.srcElement; - if (element.nodeName.toLowerCase() === 'strong') { - element = element.parentNode; - } - - var className = element.className, - offset = 50, - left = fabric.util.getRandomInt(0 + offset, 700 - offset), - top = fabric.util.getRandomInt(0 + offset, 500 - offset), - angle = fabric.util.getRandomInt(-20, 40), - width = fabric.util.getRandomInt(30, 50), - opacity = (function (min, max) { return Math.random() * (max - min) + min; })(0.5, 1); + var className = element.className, + offset = 50, + left = fabric.util.getRandomInt(0 + offset, 700 - offset), + top = fabric.util.getRandomInt(0 + offset, 500 - offset), + angle = fabric.util.getRandomInt(-20, 40), + width = fabric.util.getRandomInt(30, 50), + opacity = (function(min, max) { return Math.random() * (max - min) + min; })(0.5, 1); - switch (className) { - case 'rect': - canvas.add(new fabric.Rect({ - left: left, - top: top, - fill: '#' + getRandomColor(), - width: 50, - height: 50, - opacity: 0.8 - })); - break; + switch (className) { + case 'rect': + canvas.add(new fabric.Rect({ + left: left, + top: top, + fill: '#' + getRandomColor(), + width: 50, + height: 50, + opacity: 0.8 + })); + break; - case 'circle': - canvas.add(new fabric.Circle({ - left: left, - top: top, - fill: '#' + getRandomColor(), - radius: 50, - opacity: 0.8 - })); - break; + case 'circle': + canvas.add(new fabric.Circle({ + left: left, + top: top, + fill: '#' + getRandomColor(), + radius: 50, + opacity: 0.8 + })); + break; - case 'triangle': - canvas.add(new fabric.Triangle({ - left: left, - top: top, - fill: '#' + getRandomColor(), - width: 50, - height: 50, - opacity: 0.8 - })); - break; + case 'triangle': + canvas.add(new fabric.Triangle({ + left: left, + top: top, + fill: '#' + getRandomColor(), + width: 50, + height: 50, + opacity: 0.8 + })); + break; - case 'image1': - fabric.Image.fromURL('../assets/pug.jpg', function (image) { - image.set({ - left: left, - top: top, - angle: angle, - padding: 10, - cornersize: 10 - }); - image.scale(getRandomNum(0.1, 0.25)).setCoords(); - canvas.add(image); - }); - break; + case 'image1': + fabric.Image.fromURL('../assets/pug.jpg', function(image) { + image.set({ + left: left, + top: top, + angle: angle, + padding: 10, + cornersize: 10 + }); + image.scale(getRandomNum(0.1, 0.25)).setCoords(); + canvas.add(image); + }); + break; - case 'image2': - fabric.Image.fromURL('../assets/logo.png', function (image) { - image.set({ - left: left, - top: top, - angle: angle, - padding: 10, - cornersize: 10 - }); - image.scale(getRandomNum(0.1, 1)).setCoords(); - canvas.add(image); - updateComplexity(); - }); - break; + case 'image2': + fabric.Image.fromURL('../assets/logo.png', function(image) { + image.set({ + left: left, + top: top, + angle: angle, + padding: 10, + cornersize: 10 + }); + image.scale(getRandomNum(0.1, 1)).setCoords(); + canvas.add(image); + updateComplexity(); + }); + break; - case 'shape': - var id = element.id, match; - if (match = /\d+$/.exec(id)) { - fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function (objects, options) { - var loadedObject = fabric.util.groupSVGElements(objects, options); + case 'shape': + var id = element.id, match; + if (match = /\d+$/.exec(id)) { + fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function(objects, options) { + var loadedObject = fabric.util.groupSVGElements(objects, options); - loadedObject.set({ - left: left, - top: top, - angle: angle, - padding: 10, - cornersize: 10 - }); - loadedObject/*.scaleToWidth(300)*/.setCoords(); - - // loadedObject.hasRotatingPoint = true; - - canvas.add(loadedObject); - updateComplexity(); - canvas.calcOffset(); - }); - } - break; - - case 'clear': - if (confirm('Are you sure?')) { - canvas.clear(); - } - } - updateComplexity(); - }; - - document.getElementById('execute').onclick = function () { - var code = (document.getElementById('canvas-console')).value; - if (!(/^\s+$/).test(code)) { - eval(code); - } - }; - - - document.getElementById('rasterize').onclick = function () { - if (!fabric.Canvas.supports('toDataURL')) { - alert('This browser doesn\'t provide means to serialize canvas to an image'); - } - else { - window.open(canvas.toDataURL('png')); - } - }; - - var removeSelectedEl = document.getElementById('remove-selected'); - removeSelectedEl.onclick = function () { - var activeObject = canvas.getActiveObject(), - activeGroup = canvas.getActiveGroup(); - if (activeObject) { - canvas.remove(activeObject); - } - else if (activeGroup) { - var objectsInGroup = activeGroup.getObjects(); - canvas.discardActiveGroup(); - objectsInGroup.forEach(function (object) { - canvas.remove(object); + loadedObject.set({ + left: left, + top: top, + angle: angle, + padding: 10, + cornersize: 10 }); - } - }; + loadedObject/*.scaleToWidth(300)*/.setCoords(); - var supportsInputOfType = function (type) { - return function () { - var el = document.createElement('input'); - try { - el.type = type; - } - catch (err) { } - return el.type === type; - }; - }; - - var supportsSlider = supportsInputOfType('range'), - supportsColorpicker = supportsInputOfType('color'); - - if (supportsSlider()) { - (function () { - var controls = document.getElementById('controls'); - - var sliderLabel = document.createElement('label'); - sliderLabel.htmlFor = 'opacity'; - sliderLabel.innerHTML = 'Opacity: '; - - var slider = document.createElement('input'); - - try { slider.type = 'range'; } catch (err) { } - - slider.id = 'opacity'; - slider.value = "100"; - - controls.appendChild(sliderLabel); - controls.appendChild(slider); + // loadedObject.hasRotatingPoint = true; + canvas.add(loadedObject); + updateComplexity(); canvas.calcOffset(); + }); + } + break; - slider.onchange = function () { - var activeObject = canvas.getActiveObject(), - activeGroup = canvas.getActiveGroup(); - - if (activeObject || activeGroup) { - (activeObject || activeGroup).setOpacity(parseInt(this.value, 10) / 100); - canvas.renderAll(); - } - }; - })(); + case 'clear': + if (confirm('Are you sure?')) { + canvas.clear(); + } } + updateComplexity(); + }; - if (supportsColorpicker()) { - (function () { - var controls = document.getElementById('controls'); - - var label = document.createElement('label'); - label.htmlFor = 'color'; - label.innerHTML = 'Color: '; - label.style.marginLeft = '10px'; - - var colorpicker = document.createElement('input'); - colorpicker.type = 'color'; - colorpicker.id = 'color'; - colorpicker.style.width = '40px'; - - controls.appendChild(label); - controls.appendChild(colorpicker); - - canvas.calcOffset(); - - colorpicker.onchange = function () { - var activeObject = canvas.getActiveObject(), - activeGroup = canvas.getActiveGroup(); - - if (activeObject || activeGroup) { - (activeObject || activeGroup).setFill(this.value); - canvas.renderAll(); - } - }; - })(); + document.getElementById('execute').onclick = function() { + var code = (document.getElementById('canvas-console')).value; + if (!(/^\s+$/).test(code)) { + eval(code); } + }; - var lockHorizontallyEl = document.getElementById('lock-horizontally'); - lockHorizontallyEl.onclick = function () { - var activeObject: any = canvas.getActiveObject(); - if (activeObject) { - activeObject.lockMovementX = !activeObject.lockMovementX; - lockHorizontallyEl.innerHTML = activeObject.lockMovementX - ? 'Unlock horizontal movement' - : 'Lock horizontal movement'; - } - }; - var lockVerticallyEl = document.getElementById('lock-vertically'); - lockVerticallyEl.onclick = function () { - var activeObject: any = canvas.getActiveObject(); - if (activeObject) { - activeObject.lockMovementY = !activeObject.lockMovementY; - lockVerticallyEl.innerHTML = activeObject.lockMovementY - ? 'Unlock vertical movement' - : 'Lock vertical movement'; - } - }; - - var lockScalingXEl = document.getElementById('lock-scaling-x'); - lockScalingXEl.onclick = function () { - var activeObject: any = canvas.getActiveObject(); - if (activeObject) { - activeObject.lockScalingX = !activeObject.lockScalingX; - lockScalingXEl.innerHTML = activeObject.lockScalingX - ? 'Unlock horizontal scaling' - : 'Lock horizontal scaling'; - } - }; - - var lockScalingYEl = document.getElementById('lock-scaling-y'); - lockScalingYEl.onclick = function () { - var activeObject: any = canvas.getActiveObject(); - if (activeObject) { - activeObject.lockScalingY = !activeObject.lockScalingY; - lockScalingYEl.innerHTML = activeObject.lockScalingY - ? 'Unlock vertical scaling' - : 'Lock vertical scaling'; - } - }; - - var lockRotationEl = document.getElementById('lock-rotation'); - lockRotationEl.onclick = function () { - var activeObject: any = canvas.getActiveObject(); - if (activeObject) { - activeObject.lockRotation = !activeObject.lockRotation; - lockRotationEl.innerHTML = activeObject.lockRotation - ? 'Unlock rotation' - : 'Lock rotation'; - } - }; - - var gradientifyBtn = document.getElementById('gradientify'); - - var activeObjectButtons = [ - lockHorizontallyEl, - lockVerticallyEl, - lockScalingXEl, - lockScalingYEl, - lockRotationEl, - removeSelectedEl, - gradientifyBtn - ]; - - var opacityEl = document.getElementById('opacity'); - if (opacityEl) { - activeObjectButtons.push(opacityEl); + document.getElementById('rasterize').onclick = function() { + if (!fabric.Canvas.supports('toDataURL')) { + alert('This browser doesn\'t provide means to serialize canvas to an image'); } - var colorEl = document.getElementById('color'); - if (colorEl) { - activeObjectButtons.push(colorEl); + else { + window.open(canvas.toDataURL('png')); } + }; + + var removeSelectedEl = document.getElementById('remove-selected'); + removeSelectedEl.onclick = function() { + var activeObject = canvas.getActiveObject(), + activeGroup = canvas.getActiveGroup(); + if (activeObject) { + canvas.remove(activeObject); + } + else if (activeGroup) { + var objectsInGroup = activeGroup.getObjects(); + canvas.discardActiveGroup(); + objectsInGroup.forEach(function(object) { + canvas.remove(object); + }); + } + }; + + var supportsInputOfType = function(type) { + return function() { + var el = document.createElement('input'); + try { + el.type = type; + } + catch (err) { } + return el.type === type; + }; + }; + + var supportsSlider = supportsInputOfType('range'), + supportsColorpicker = supportsInputOfType('color'); + + if (supportsSlider()) { + (function() { + var controls = document.getElementById('controls'); + + var sliderLabel = document.createElement('label'); + sliderLabel.htmlFor = 'opacity'; + sliderLabel.innerHTML = 'Opacity: '; + + var slider = document.createElement('input'); + + try { slider.type = 'range'; } catch (err) { } + + slider.id = 'opacity'; + slider.value = "100"; + + controls.appendChild(sliderLabel); + controls.appendChild(slider); + + canvas.calcOffset(); + + slider.onchange = function() { + var activeObject = canvas.getActiveObject(), + activeGroup = canvas.getActiveGroup(); + + if (activeObject || activeGroup) { + (activeObject || activeGroup).setOpacity(parseInt(this.value, 10) / 100); + canvas.renderAll(); + } + }; + })(); + } + + if (supportsColorpicker()) { + (function() { + var controls = document.getElementById('controls'); + + var label = document.createElement('label'); + label.htmlFor = 'color'; + label.innerHTML = 'Color: '; + label.style.marginLeft = '10px'; + + var colorpicker = document.createElement('input'); + colorpicker.type = 'color'; + colorpicker.id = 'color'; + colorpicker.style.width = '40px'; + + controls.appendChild(label); + controls.appendChild(colorpicker); + + canvas.calcOffset(); + + colorpicker.onchange = function() { + var activeObject = canvas.getActiveObject(), + activeGroup = canvas.getActiveGroup(); + + if (activeObject || activeGroup) { + (activeObject || activeGroup).setFill(this.value); + canvas.renderAll(); + } + }; + })(); + } + + var lockHorizontallyEl = document.getElementById('lock-horizontally'); + lockHorizontallyEl.onclick = function() { + var activeObject: any = canvas.getActiveObject(); + if (activeObject) { + activeObject.lockMovementX = !activeObject.lockMovementX; + lockHorizontallyEl.innerHTML = activeObject.lockMovementX + ? 'Unlock horizontal movement' + : 'Lock horizontal movement'; + } + }; + + var lockVerticallyEl = document.getElementById('lock-vertically'); + lockVerticallyEl.onclick = function() { + var activeObject: any = canvas.getActiveObject(); + if (activeObject) { + activeObject.lockMovementY = !activeObject.lockMovementY; + lockVerticallyEl.innerHTML = activeObject.lockMovementY + ? 'Unlock vertical movement' + : 'Lock vertical movement'; + } + }; + + var lockScalingXEl = document.getElementById('lock-scaling-x'); + lockScalingXEl.onclick = function() { + var activeObject: any = canvas.getActiveObject(); + if (activeObject) { + activeObject.lockScalingX = !activeObject.lockScalingX; + lockScalingXEl.innerHTML = activeObject.lockScalingX + ? 'Unlock horizontal scaling' + : 'Lock horizontal scaling'; + } + }; + + var lockScalingYEl = document.getElementById('lock-scaling-y'); + lockScalingYEl.onclick = function() { + var activeObject: any = canvas.getActiveObject(); + if (activeObject) { + activeObject.lockScalingY = !activeObject.lockScalingY; + lockScalingYEl.innerHTML = activeObject.lockScalingY + ? 'Unlock vertical scaling' + : 'Lock vertical scaling'; + } + }; + + var lockRotationEl = document.getElementById('lock-rotation'); + lockRotationEl.onclick = function() { + var activeObject: any = canvas.getActiveObject(); + if (activeObject) { + activeObject.lockRotation = !activeObject.lockRotation; + lockRotationEl.innerHTML = activeObject.lockRotation + ? 'Unlock rotation' + : 'Lock rotation'; + } + }; + + var gradientifyBtn = document.getElementById('gradientify'); + + var activeObjectButtons = [ + lockHorizontallyEl, + lockVerticallyEl, + lockScalingXEl, + lockScalingYEl, + lockRotationEl, + removeSelectedEl, + gradientifyBtn + ]; + + var opacityEl = document.getElementById('opacity'); + if (opacityEl) { + activeObjectButtons.push(opacityEl); + } + var colorEl = document.getElementById('color'); + if (colorEl) { + activeObjectButtons.push(colorEl); + } + + for (var i = activeObjectButtons.length; i--;) { + activeObjectButtons[i].disabled = true; + } + + canvas.on('object:selected', onObjectSelected); + canvas.on('group:selected', onObjectSelected); + + function onObjectSelected(e) { + var selectedObject = e.target; for (var i = activeObjectButtons.length; i--;) { - activeObjectButtons[i].disabled = true; + activeObjectButtons[i].disabled = false; } - canvas.on('object:selected', onObjectSelected); - canvas.on('group:selected', onObjectSelected); + lockHorizontallyEl.innerHTML = (selectedObject.lockMovementX ? 'Unlock horizontal movement' : 'Lock horizontal movement'); + lockVerticallyEl.innerHTML = (selectedObject.lockMovementY ? 'Unlock vertical movement' : 'Lock vertical movement'); + lockScalingXEl.innerHTML = (selectedObject.lockScalingX ? 'Unlock horizontal scaling' : 'Lock horizontal scaling'); + lockScalingYEl.innerHTML = (selectedObject.lockScalingY ? 'Unlock vertical scaling' : 'Lock vertical scaling'); + lockRotationEl.innerHTML = (selectedObject.lockRotation ? 'Unlock rotation' : 'Lock rotation'); + } - function onObjectSelected(e) { - var selectedObject = e.target; - - for (var i = activeObjectButtons.length; i--;) { - activeObjectButtons[i].disabled = false; - } - - lockHorizontallyEl.innerHTML = (selectedObject.lockMovementX ? 'Unlock horizontal movement' : 'Lock horizontal movement'); - lockVerticallyEl.innerHTML = (selectedObject.lockMovementY ? 'Unlock vertical movement' : 'Lock vertical movement'); - lockScalingXEl.innerHTML = (selectedObject.lockScalingX ? 'Unlock horizontal scaling' : 'Lock horizontal scaling'); - lockScalingYEl.innerHTML = (selectedObject.lockScalingY ? 'Unlock vertical scaling' : 'Lock vertical scaling'); - lockRotationEl.innerHTML = (selectedObject.lockRotation ? 'Unlock rotation' : 'Lock rotation'); + canvas.on('selection:cleared', function(e) { + for (var i = activeObjectButtons.length; i--;) { + activeObjectButtons[i].disabled = true; } + }); - canvas.on('selection:cleared', function (e) { - for (var i = activeObjectButtons.length; i--;) { - activeObjectButtons[i].disabled = true; - } + var drawingModeEl = document.getElementById('drawing-mode'), + drawingOptionsEl = document.getElementById('drawing-mode-options'), + drawingColorEl = document.getElementById('drawing-color'), + drawingLineWidthEl = document.getElementById('drawing-line-width'); + + drawingModeEl.onclick = function() { + var canvasWithDrawingMode: any = canvas; + canvasWithDrawingMode.isDrawingMode = !canvasWithDrawingMode.isDrawingMode; + if (canvasWithDrawingMode.isDrawingMode) { + drawingModeEl.innerHTML = 'Cancel drawing mode'; + drawingModeEl.className = 'is-drawing'; + drawingOptionsEl.style.display = ''; + } + else { + drawingModeEl.innerHTML = 'Enter drawing mode'; + drawingModeEl.className = ''; + drawingOptionsEl.style.display = 'none'; + } + }; + + canvas.on('path:created', function() { + updateComplexity(); + }); + + drawingColorEl.onchange = function() { + canvas.freeDrawingColor = drawingColorEl.value; + }; + drawingLineWidthEl.onchange = function() { + canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; // disallow 0, NaN, etc. + }; + + canvas.freeDrawingColor = drawingColorEl.value; + canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; + + + var text = 'Lorem ipsum dolor sit amet,\nconsectetur adipisicing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.\n' + + 'Ut enim ad minim veniam,\nquis nostrud exercitation ullamco\nlaboris nisi ut aliquip ex ea commodo consequat.'; + + document.getElementById('add-text').onclick = function() { + var textSample = new fabric.Text(text.slice(0, getRandomInt(0, text.length)), { + left: getRandomInt(350, 400), + top: getRandomInt(350, 400), + fontFamily: 'helvetica', + angle: getRandomInt(-10, 10), + fill: '#' + getRandomColor(), + scaleX: 0.5, + scaleY: 0.5, + fontWeight: '' }); + canvas.add(textSample); + updateComplexity(); + }; - var drawingModeEl = document.getElementById('drawing-mode'), - drawingOptionsEl = document.getElementById('drawing-mode-options'), - drawingColorEl = document.getElementById('drawing-color'), - drawingLineWidthEl = document.getElementById('drawing-line-width'); - drawingModeEl.onclick = function () { - var canvasWithDrawingMode: any = canvas; - canvasWithDrawingMode.isDrawingMode = !canvasWithDrawingMode.isDrawingMode; - if (canvasWithDrawingMode.isDrawingMode) { - drawingModeEl.innerHTML = 'Cancel drawing mode'; - drawingModeEl.className = 'is-drawing'; - drawingOptionsEl.style.display = ''; + document.onkeydown = function(e) { + var obj = canvas.getActiveObject() || canvas.getActiveGroup(); + if (obj && e.keyCode === 8) { + // this is horrible. need to fix, so that unified interface can be used + if (obj.type === 'group') { + // var groupObjects = obj.getObjects(); + // canvas.discardActiveGroup(); + // groupObjects.forEach(function(obj) { + // canvas.remove(obj); + // }); + } + else { + //canvas.remove(obj); + } + canvas.renderAll(); + // return false; + } + }; + + setTimeout(function() { + canvas.calcOffset(); + }, 100); + + if (document.location.search.indexOf('guidelines') > -1) { + //initCenteringGuidelines(canvas); + //initAligningGuidelines(canvas); + } + + gradientifyBtn.onclick = function() { + var obj = canvas.getActiveObject(); + if (obj) { + obj.setGradient("fill", { + x2: (getRandomInt(0, 1) ? 0 : obj.width), + y2: (getRandomInt(0, 1) ? 0 : obj.height), + colorStops: { + 0: '#' + getRandomColor(), + 1: '#' + getRandomColor() + } + }); + canvas.renderAll(); + } + }; + + var textEl = document.getElementById('text'); + if (textEl) { + textEl.onfocus = function() { + var activeObject = canvas.getActiveObject(); + + if (activeObject && activeObject.type === 'text') { + this.value = (activeObject).text; + } + }; + textEl.onkeyup = function(e) { + var activeObject = canvas.getActiveObject(); + if (activeObject) { + if (!this.value) { + canvas.discardActiveObject(); } else { - drawingModeEl.innerHTML = 'Enter drawing mode'; - drawingModeEl.className = ''; - drawingOptionsEl.style.display = 'none'; + (activeObject).text = this.value; } + canvas.renderAll(); + } }; + } - canvas.on('path:created', function () { - updateComplexity(); + var cmdUnderlineBtn = document.getElementById('text-cmd-underline'); + if (cmdUnderlineBtn) { + activeObjectButtons.push(cmdUnderlineBtn); + cmdUnderlineBtn.disabled = true; + cmdUnderlineBtn.onclick = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.textDecoration = (activeObject.textDecoration == 'underline' ? '' : 'underline'); + this.className = activeObject.textDecoration ? 'selected' : ''; + canvas.renderAll(); + } + }; + } + + var cmdLinethroughBtn = document.getElementById('text-cmd-linethrough'); + if (cmdLinethroughBtn) { + activeObjectButtons.push(cmdLinethroughBtn); + cmdLinethroughBtn.disabled = true; + cmdLinethroughBtn.onclick = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.textDecoration = (activeObject.textDecoration == 'line-through' ? '' : 'line-through'); + this.className = activeObject.textDecoration ? 'selected' : ''; + canvas.renderAll(); + } + }; + } + + var cmdOverlineBtn = document.getElementById('text-cmd-overline'); + if (cmdOverlineBtn) { + activeObjectButtons.push(cmdOverlineBtn); + cmdOverlineBtn.disabled = true; + cmdOverlineBtn.onclick = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.textDecoration = (activeObject.textDecoration == 'overline' ? '' : 'overline'); + this.className = activeObject.textDecoration ? 'selected' : ''; + canvas.renderAll(); + } + }; + } + + var cmdBoldBtn = document.getElementById('text-cmd-bold'); + if (cmdBoldBtn) { + activeObjectButtons.push(cmdBoldBtn); + cmdBoldBtn.disabled = true; + cmdBoldBtn.onclick = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.fontWeight = (activeObject.fontWeight == 'bold' ? '' : 'bold'); + this.className = activeObject.fontWeight ? 'selected' : ''; + canvas.renderAll(); + } + }; + } + + var cmdItalicBtn = document.getElementById('text-cmd-italic'); + if (cmdItalicBtn) { + activeObjectButtons.push(cmdItalicBtn); + cmdItalicBtn.disabled = true; + cmdItalicBtn.onclick = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.fontStyle = (activeObject.fontStyle == 'italic' ? '' : 'italic'); + this.className = activeObject.fontStyle ? 'selected' : ''; + canvas.renderAll(); + } + }; + } + + var cmdShadowBtn = document.getElementById('text-cmd-shadow'); + if (cmdShadowBtn) { + activeObjectButtons.push(cmdShadowBtn); + cmdShadowBtn.disabled = true; + cmdShadowBtn.onclick = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.shadow = !activeObject.shadow ? 'rgba(0,0,0,0.2) 2px 2px 10px' : ''; + this.className = activeObject.shadow ? 'selected' : ''; + canvas.renderAll(); + } + }; + } + + var textAlignSwitch = document.getElementById('text-align'); + if (textAlignSwitch) { + activeObjectButtons.push(textAlignSwitch); + textAlignSwitch.disabled = true; + textAlignSwitch.onchange = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.textAlign = this.value.toLowerCase(); + canvas.renderAll(); + } + }; + } + + var fontFamilySwitch = document.getElementById('font-family'); + if (fontFamilySwitch) { + activeObjectButtons.push(fontFamilySwitch); + fontFamilySwitch.disabled = true; + fontFamilySwitch.onchange = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.fontFamily = this.value; + canvas.renderAll(); + } + }; + } + + var bgColorField = document.getElementById('text-bg-color'); + if (bgColorField) { + bgColorField.onchange = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.backgroundColor = this.value; + canvas.renderAll(); + } + }; + } + + var strokeColorField = document.getElementById('text-stroke-color'); + if (strokeColorField) { + strokeColorField.onchange = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.stroke = this.value; + canvas.renderAll(); + } + }; + } + + if (supportsSlider) { + (function() { + var container = document.getElementById('text-controls'); + var slider = document.createElement('input'); + var label = document.createElement('label'); + label.innerHTML = 'Line height: '; + try { slider.type = 'range'; } catch (err) { } + slider.min = "0"; + slider.max = "10"; + slider.step = "0.1"; + slider.value = "1.5"; + container.appendChild(label); + label.appendChild(slider); + slider.title = "Line height"; + slider.onchange = function() { + var activeObject = canvas.getActiveObject(); + if (activeObject && activeObject.type === 'text') { + activeObject.lineHeight = this.value; + canvas.renderAll(); + } + }; + + canvas.on('object:selected', function(e: fabric.IEvent) { + slider.value = String((e.target).lineHeight ); + }); + })(); + } + + document.getElementById('load-svg').onclick = function() { + var svg = (document.getElementById('svg-console')).value; + fabric.loadSVGFromString(svg, function(objects, options) { + var obj = fabric.util.groupSVGElements(objects, options); + canvas.add(obj).centerObject(obj).renderAll(); + obj.setCoords(); }); - - drawingColorEl.onchange = function () { - canvas.freeDrawingColor = drawingColorEl.value; - }; - drawingLineWidthEl.onchange = function () { - canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; // disallow 0, NaN, etc. - }; - - canvas.freeDrawingColor = drawingColorEl.value; - canvas.freeDrawingLineWidth = parseInt(drawingLineWidthEl.value, 10) || 1; - - - var text = 'Lorem ipsum dolor sit amet,\nconsectetur adipisicing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.\n' + - 'Ut enim ad minim veniam,\nquis nostrud exercitation ullamco\nlaboris nisi ut aliquip ex ea commodo consequat.'; - - document.getElementById('add-text').onclick = function () { - var textSample = new fabric.Text(text.slice(0, getRandomInt(0, text.length)), { - left: getRandomInt(350, 400), - top: getRandomInt(350, 400), - fontFamily: 'helvetica', - angle: getRandomInt(-10, 10), - fill: '#' + getRandomColor(), - scaleX: 0.5, - scaleY: 0.5, - fontWeight: '' - }); - canvas.add(textSample); - updateComplexity(); - }; - - - document.onkeydown = function (e) { - var obj = canvas.getActiveObject() || canvas.getActiveGroup(); - if (obj && e.keyCode === 8) { - // this is horrible. need to fix, so that unified interface can be used - if (obj.type === 'group') { - // var groupObjects = obj.getObjects(); - // canvas.discardActiveGroup(); - // groupObjects.forEach(function(obj) { - // canvas.remove(obj); - // }); - } - else { - //canvas.remove(obj); - } - canvas.renderAll(); - // return false; - } - }; - - setTimeout(function () { - canvas.calcOffset(); - }, 100); - - if (document.location.search.indexOf('guidelines') > -1) { - //initCenteringGuidelines(canvas); - //initAligningGuidelines(canvas); - } - - gradientifyBtn.onclick = function () { - var obj = canvas.getActiveObject(); - if (obj) { - obj.setGradientFill({ - x2: (getRandomInt(0, 1) ? 0 : obj.width), - y2: (getRandomInt(0, 1) ? 0 : obj.height), - colorStops: { - 0: '#' + getRandomColor(), - 1: '#' + getRandomColor() - } - }); - canvas.renderAll(); - } - }; - - var textEl = document.getElementById('text'); - if (textEl) { - textEl.onfocus = function () { - var activeObject = canvas.getActiveObject(); - - if (activeObject && activeObject.type === 'text') { - this.value = (activeObject).text; - } - }; - textEl.onkeyup = function (e) { - var activeObject = canvas.getActiveObject(); - if (activeObject) { - if (!this.value) { - canvas.discardActiveObject(); - } - else { - (activeObject).text = this.value; - } - canvas.renderAll(); - } - }; - } - - var cmdUnderlineBtn = document.getElementById('text-cmd-underline'); - if (cmdUnderlineBtn) { - activeObjectButtons.push(cmdUnderlineBtn); - cmdUnderlineBtn.disabled = true; - cmdUnderlineBtn.onclick = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'underline' ? '' : 'underline'); - this.className = activeObject.textDecoration ? 'selected' : ''; - canvas.renderAll(); - } - }; - } - - var cmdLinethroughBtn = document.getElementById('text-cmd-linethrough'); - if (cmdLinethroughBtn) { - activeObjectButtons.push(cmdLinethroughBtn); - cmdLinethroughBtn.disabled = true; - cmdLinethroughBtn.onclick = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'line-through' ? '' : 'line-through'); - this.className = activeObject.textDecoration ? 'selected' : ''; - canvas.renderAll(); - } - }; - } - - var cmdOverlineBtn = document.getElementById('text-cmd-overline'); - if (cmdOverlineBtn) { - activeObjectButtons.push(cmdOverlineBtn); - cmdOverlineBtn.disabled = true; - cmdOverlineBtn.onclick = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.textDecoration = (activeObject.textDecoration == 'overline' ? '' : 'overline'); - this.className = activeObject.textDecoration ? 'selected' : ''; - canvas.renderAll(); - } - }; - } - - var cmdBoldBtn = document.getElementById('text-cmd-bold'); - if (cmdBoldBtn) { - activeObjectButtons.push(cmdBoldBtn); - cmdBoldBtn.disabled = true; - cmdBoldBtn.onclick = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.fontWeight = (activeObject.fontWeight == 'bold' ? '' : 'bold'); - this.className = activeObject.fontWeight ? 'selected' : ''; - canvas.renderAll(); - } - }; - } - - var cmdItalicBtn = document.getElementById('text-cmd-italic'); - if (cmdItalicBtn) { - activeObjectButtons.push(cmdItalicBtn); - cmdItalicBtn.disabled = true; - cmdItalicBtn.onclick = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.fontStyle = (activeObject.fontStyle == 'italic' ? '' : 'italic'); - this.className = activeObject.fontStyle ? 'selected' : ''; - canvas.renderAll(); - } - }; - } - - var cmdShadowBtn = document.getElementById('text-cmd-shadow'); - if (cmdShadowBtn) { - activeObjectButtons.push(cmdShadowBtn); - cmdShadowBtn.disabled = true; - cmdShadowBtn.onclick = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.textShadow = !activeObject.textShadow ? 'rgba(0,0,0,0.2) 2px 2px 10px' : ''; - this.className = activeObject.textShadow ? 'selected' : ''; - canvas.renderAll(); - } - }; - } - - var textAlignSwitch = document.getElementById('text-align'); - if (textAlignSwitch) { - activeObjectButtons.push(textAlignSwitch); - textAlignSwitch.disabled = true; - textAlignSwitch.onchange = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.textAlign = this.value.toLowerCase(); - canvas.renderAll(); - } - }; - } - - var fontFamilySwitch = document.getElementById('font-family'); - if (fontFamilySwitch) { - activeObjectButtons.push(fontFamilySwitch); - fontFamilySwitch.disabled = true; - fontFamilySwitch.onchange = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.fontFamily = this.value; - canvas.renderAll(); - } - }; - } - - var bgColorField = document.getElementById('text-bg-color'); - if (bgColorField) { - bgColorField.onchange = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.backgroundColor = this.value; - canvas.renderAll(); - } - }; - } - - var strokeColorField = document.getElementById('text-stroke-color'); - if (strokeColorField) { - strokeColorField.onchange = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.strokeStyle = this.value; - canvas.renderAll(); - } - }; - } - - if (supportsSlider) { - (function () { - var container = document.getElementById('text-controls'); - var slider = document.createElement('input'); - var label = document.createElement('label'); - label.innerHTML = 'Line height: '; - try { slider.type = 'range'; } catch (err) { } - slider.min = "0"; - slider.max = "10"; - slider.step = "0.1"; - slider.value = "1.5"; - container.appendChild(label); - label.appendChild(slider); - slider.title = "Line height"; - slider.onchange = function () { - var activeObject = canvas.getActiveObject(); - if (activeObject && activeObject.type === 'text') { - activeObject.lineHeight = this.value; - canvas.renderAll(); - } - }; - - canvas.on('object:selected', function (e) { - slider.value = e.target.lineHeight; - }); - })(); - } - - document.getElementById('load-svg').onclick = function () { - var svg = (document.getElementById('svg-console')).value; - fabric.loadSVGFromString(svg, function (objects, options) { - var obj = fabric.util.groupSVGElements(objects, options); - canvas.add(obj).centerObject(obj).renderAll(); - obj.setCoords(); - }); - }; + }; } function sample9() { - var canvas = new fabric.Canvas('c'); - canvas.setBackgroundImage('yolo.jpg', () => {"a"}, {opacity: 45}); - canvas.setBackgroundImage('yolo.jpg', () => {"a"}); + var canvas = new fabric.Canvas('c'); + canvas.setBackgroundImage('yolo.jpg',() => { "a" }, { opacity: 45 }); + canvas.setBackgroundImage('yolo.jpg',() => { "a" }); } diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index f764d4768..503b8c7db 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -1,899 +1,4596 @@ -// Type definitions for FabricJS +// Type definitions for FabricJS v1.5.0 // Project: http://fabricjs.com/ -// Definitions by: Oliver Klemencic +// Definitions by: Oliver Klemencic , Joseph Livecchi // Definitions: https://github.com/borisyankov/DefinitelyTyped +/* tslint:disable:no-unused-variable */ +/* tslint:disable:whitespace */ +/* tslint:disable:typedef */ + +// Support AMD require +declare module "fabric" { + export = fabric; +} + declare module fabric { - function createCanvasForNode(width: number, height: number): ICanvas; - function getCSSRules(doc: SVGElement); - function getGradientDefs(doc: SVGElement); - function loadSVGFromString(text: string, callback: (results: IObject[], options) => void , reviver?: (el, obj) => void ); - function loadSVGFromURL(url, callback: (results: IObject[], options) => void , reviver?: (el, obj) => void ); - function log(values); - function parseAttributes(element, attributes: any[]): any; - function parseElements(elements: any[], callback, options, reviver); - function parsePointsAttribute(points: string): any[]; - function parseStyleAttribute(element: SVGElement); - function parseSVGDocument(doc: SVGElement, callback: (results, options) => void , reviver?: (el, obj) => void ); - function parseTransformAttribute(attributeValue: string); - function warn(values); - - var isLikelyNode: boolean; - var isTouchSupported: boolean; - - export interface IObservable { - observe(eventCollection: IEventList); - on(eventCollection: IEventList); - - observe(eventName: string, handler: (e) => any); - on(eventName: string, handler: (e) => any); - - fire(eventName: string, options); - stopObserving(eventName: string, handler: (e) => any); - - off(eventName, handler); - } - - export interface IFilter { - new (): IFilter; - new (options: any): IFilter; - } - - export interface IEventList { - [index: string]: (e: Event) => void; - } - - export interface IObjectOptions { - angle?: number; - borderColor?: string; - borderOpacityWhenMoving?: number; - borderScaleFactor?: number; - cornerColor?: string; - cornersize?: number; - fill?: string; - fillRule?: string; - flipX?: boolean; - flipY?: boolean; - hasBorders?: boolean; - hasControls?: boolean; - hasRotatingPoint?: boolean; - height?: number; - includeDefaultValues?: boolean; - left?: number; - lockMovementX?: boolean; - lockMovementY?: boolean; - lockScalingX?: boolean; - lockScalingY?: boolean; - lockUniScaling?: boolean; - lockRotation?: boolean; - opacity?: number; - originX?: string; - originY?: string; - overlayFill?: string; - padding?: number; - perPixelTargetFind?: boolean; - rotatingPointOffset?: number; - scaleX?: number; - scaleY?: number; - selectable?: boolean; - stateProperties?: any[]; - stroke?: string; - strokeDashArray?: any[]; - strokeWidth?: number; - top?: number; - transformMatrix?: any[]; - transparentCorners?: boolean; - type?: string; - width?: number; - } - - export interface ITextOptions extends IObjectOptions { - fontSize?: number; - fontWeight?: any; - fontFamily?: string; - textDecoration?: string; - textShadow?: string; - textAlign?: string; - fontStyle?: string; - lineHeight?: number; - strokeStyle?: string; - strokeWidth?: number; - backgroundColor?: string; - textBackgroundColor?: string; - path?: string; - type?: string; - useNative?: Boolean; - } - - export interface ICircleOptions extends IObjectOptions { - radius?: number; - } - - export interface IPoint { - add(that: IPoint): IPoint; - addEquals(that: IPoint): IPoint; - distanceFrom(that: IPoint); - divide(scalar: number); - divideEquals(scalar: number); - eq(that: IPoint); - gt(that: IPoint); - gte(that: IPoint); - init(x, y); - lerp(that: IPoint, t); - lt(that: IPoint); - lte(that: IPoint); - max(that: IPoint); - min(that: IPoint); - multiply(scalar); - multiplyEquals(scalar); - scalarAdd(scalar): IPoint; - scalarAddEquals(scalar: number, thisArg: IPoint); - scalarSubtract(scalar: number); - scalarSubtractEquals(scalar); - setFromPoint(that: IPoint); - setXY(x, y); - subtract(that: IPoint): IPoint; - subtractEquals(that: IPoint): IPoint; - swap(that: IPoint); - tostring(): string; - } - - export interface IRect extends IObject { - x: number; - y: number; - rx: number; - ry: number; - - complexity(): number; - initialize(options: any); - initialize(points: number[], options: any): IRect; - toObject(propertiesToInclude: any[]): any; - toSVG(): string; - } - - export interface IText extends IObject { - fontSize: number; - fontWeight: any; - fontFamily: string; - text: string; - textDecoration: string; - textShadow?: string; - textAlign: string; - fontStyle: string; - lineHeight: number; - strokeStyle: string; - strokeWidth: number; - backgroundColor: string; - textBackgroundColor: string; - path?: string; - type: string; - useNative: Boolean; - - initialize(options: any); - initialize(text: string, options: any): IText; - toString(): string; - render(ctx: CanvasRenderingContext2D, noTransform: boolean); - toObject(propertiesToInclude: any[]): IObject; - toSVG(): string; - setColor(value: string): IText; - setFontsize(value: number): IText; - getText(): string; - setText(value: string): IText; - } - - export interface ITriangle extends IObject { - complexity(): number; - initialize(options: any): ITriangle; - toSVG(): string; - } - - export interface IEllipse { - initialize(options: any): any; - toObject(propertiesToInclude: any[]): any; - toSVG(): string; - render(ctx: CanvasRenderingContext2D, noTransform: boolean); - complexity(): number; - } - - export interface IGradient { - initialize(options): any; - toObject(): any; - toLiveGradient(ctx: CanvasRenderingContext2D): any; - } - - export interface IColor { - getSource(): any[]; - setSource(source: any[]): any; - toRgb(): string; - toRgba(): string; - toHex(): string; - getAlpha(): number; - setAlpha(alpha: number): IColor; - toGrayscale(): IColor; - toBlackWhite(threshold): IColor; - overlayWith(otherColor: string): IColor; - overlayWith(otherColor: IColor): IColor; - } - - export interface IElement { - } - - export interface IObject extends IObservable { - - // constraint properties - lockMovementX: boolean; - lockMovementY: boolean; - lockScalingX: boolean; - lockScalingY: boolean; - lockScaling: boolean; - lockUniScaling: boolean; - lockRotation: boolean; - - getCurrentWidth(): number; - getCurrentHeight(): number; - - originX: string; - originY: string; - - angle: number; - getAngle(): number; - setAngle(value: number): IObject; - - borderColor: string; - getBorderColor(): string; - setBorderColor(value: string): IObject; - - borderOpacityWhenMoving: number; - borderScaleFactor: number; - getBorderScaleFactor(): number; - - cornerColor: string; - - cornersize: number; - getCornersize(): number; - setCornersize(value: number): IObject; - - fill: string; - getFill(): string; - setFill(value: string): IObject; - - fillRule: string; - getFillRule(): string; - setFillRule(value: string): IObject; - - flipX: boolean; - getFlipX(): boolean; - setFlipX(value: boolean): IObject; - - flipY: boolean; - getFlipY(): boolean; - setFlipY(value: boolean): IObject; - - hasBorders: boolean; - - hasControls: boolean; - hasRotatingPoint: boolean; - - height: number; - getHeight(): number; - setHeight(value: number): IObject; - - includeDefaultValues: boolean; - - left: number; - getLeft(): number; - setLeft(value: number): IObject; - - opacity: number; - getOpacity(): number; - setOpacity(value: number): IObject; - - overlayFill: string; - getOverlayFill(): string; - setOverlayFill(value: string): IObject; - - padding: number; - perPixelTargetFind: boolean; - rotatingPointOffset: number; - - scaleX: number; - getScaleX(): number; - setScaleX(value: number): IObject; - - scaleY: number; - getScaleY(): number; - setScaleY(value: number): IObject; - - selectable: boolean; - stateProperties: any[]; - stroke: string; - strokeDashArray: any[]; - strokeWidth: number; - - top: number; - getTop(): number; - setTop(value: number): IObject; - - transformMatrix: any[]; - transparentCorners: boolean; - type: string; - - width: number; - getWidth(): number; - setWidth(value: number): IObject; - - // methods - bringForward(intersecting?: boolean): IObject; - bringToFront(): IObject; - center(): IObject; - centerH(): IObject; - centerV(): IObject; - clone(callback?, propertiesToInclude?): IObject; - cloneAsImage(callback): IObject; - complexity(): number; - drawBorders(context: CanvasRenderingContext2D): IObject; - drawCorners(context: CanvasRenderingContext2D): IObject; - get (property: string): any; - getBoundingRect(): {left:number; top:number; width:number; height:number}; - getBoundingRectHeight(): number; - getBoundingRectWidth(): number; - getSvgStyles(): string; - getSvgTransform(): string; - hasStateChanged(): boolean; - initialize(options: any); - intersectsWithObject(other: IObject): boolean; - intersectsWithRect(selectionTL: any, selectionBR: any): boolean; - isActive(): boolean; - isContainedWithinObject(other: IObject): boolean; - isContainedWithinRect(selectionTL: any, selectionBR: any): boolean; - isType(type: string): boolean; - remove(): IObject; - render(ctx: CanvasRenderingContext2D, noTransform: boolean); - rotate(value: number): IObject; - saveState(): IObject; - scale(value: number): IObject; - scaleToHeight(value: number): IObject; - scaleToWidth(value: number): IObject; - sendBackwards(intersecting?: boolean): IObject; - sendToBack(): IObject; - - set (properties: IObjectOptions): IObject; - set (name: string, value: any): IObject; - setActive(active: boolean): IObject; - setCoords(); - setGradientFill(options); - setOptions(options: any); - setSourcePath(value: string): IObject; - toDatalessObject(propertiesToInclude): any; - toDataURL(callback): string; - toggle(property): IObject; - toGrayscale(): IObject; - toJSON(propertiesToInclude): string; - toObject(propertiesToInclude): any; - tostring(): string; - transform(ctx: CanvasRenderingContext2D); - } - - export interface IGroup extends IObject { - type: string; - - activateAllObjects(): IGroup; - add(object): IGroup; - addWithUpdate(object): IGroup; - complexity(): number; - contains(object): boolean; - containsPoint(point): boolean; - destroy(): IGroup; - getObjects(): IObject[]; - hasMoved(): boolean; - initialize(options: any); - initialize(objects, options): any; - item(index): IObject; - remove(object?): IGroup; - removeWithUpdate(object): IGroup; - render(ctx, noTransform): void; - saveCoords(): IGroup; - setObjectsCoords(): IGroup; - size(): number; - toGrayscale(): IGroup; - toObject(propertiesToInclude: any[]): any; - tostring(): string; - toSVG(): string; - } - - - export interface ILine extends IObject { - x1: number; - x2: number; - y1: number; - y2: number; - - complexity(): number; - initialize(options: any); - initialize(points: number[], options: any): ILine; - toObject(propertiesToInclude: any[]): any; - toSVG(): string; - } - - export interface IIntersection { - appendPoint(status: string); - appendPoints(status: string); - init(status: string); - } - - export interface IImage extends IObject { - filters: any; - - applyFilters(callback); - clone(callback?, propertiesToInclude?): IObject; - clone(propertiesToInclude, callback); - complexity(): number; - getElement(): HTMLImageElement; - getOriginalSize(): { width: number; height: number; }; - getSrc(): string; - initialize(options: any); - initialize(element: string, options: any); - initialize(element: HTMLImageElement, options: any); - render(ctx: CanvasRenderingContext2D, noTransform: boolean); - setElement(element): IImage; - toObject(propertiesToInclude): any; - tostring(): string; - toSVG(): string; - } - - export interface ICircle extends IObject { - // methods - complexity(): number; - getRadiusX(): number; - getRadiusY(): number; - initialize(options: ICircleOptions): ICircle; - setRadius(value: number): number; - toObject(propertiesToInclude): any; - toSVG(): string; - } - - - - export interface IPath extends IObject { - complexity(): number; - initialize(options: any); - initialize(path, options); - render(ctx: CanvasRenderingContext2D, noTransform: boolean); - toDatalessObject(propertiesToInclude): any; - toObject(propertiesToInclude): any; - tostring(): string; - toSVG(): string; - } - - export interface IPolygon extends IObject { - complexity(): number; - initialize(options: any); - initialize(points, options); - toObject(propertiesToInclude): any; - toSVG(): string; - } - - export interface IPolyline extends IObject { - complexity(): number; - initialize(options: any); - initialize(points, options); - toObject(propertiesToInclude): any; - toSVG(): string; - } - - export interface IPathGroup extends IObject { - complexity(): number; - initialize(options: any); - initialize(paths, options); - isSameColor(): boolean; - render(ctx: CanvasRenderingContext2D); - toDatalessObject(propertiesToInclude): any; - toGrayscale(): IPathGroup; - toObject(propertiesToInclude): any; - tostring(): string; - toSVG(): string; - } - - export interface IStaticCanvas extends IObservable { - - // fields - backgroundColor: string; - backgroundImage: string; - backgroundImageOpacity: number; - backgroundImageStretch: number; - clipTo(clipFunction: (context: CanvasRenderingContext2D) => void ); - controlsAboveOverlay: boolean; - includeDefaultValues: boolean; - overlayImage: string; - overlayImageLeft: number; - overlayImageTop: number; - renderOnAddition: boolean; - stateful: boolean; - - // static - EMPTY_JSON: string; - supports(methodName: string): boolean; - - // methods - add(...object: IObject[]): ICanvas; - bringForward(object: IObject): ICanvas; - calcOffset(): ICanvas; - centerObject(object: IObject): ICanvas; - centerObjectH(object: IObject): ICanvas; - centerObjectV(object: IObject): ICanvas; - clear(): ICanvas; - clearContext(context: CanvasRenderingContext2D): ICanvas; - complexity(): number; - dispose(): ICanvas; - drawControls(); - forEachObject(callback: (object: IObject) => void , context?: CanvasRenderingContext2D): ICanvas; - getActiveGroup(): IGroup; - getActiveObject(): IObject; - getCenter(): IObject; - getContext(): CanvasRenderingContext2D; - getElement(): HTMLCanvasElement; - getHeight(): number; - getObjects(): IObject[]; - getWidth(): number; - insertAt(object: IObject, index: number, nonSplicing: boolean): ICanvas; - isEmpty(): boolean; - item(index: number): IObject; - onBeforeScaleRotate(target: IObject); - remove(object: IObject): IObject; - renderAll(allOnTop?: boolean): ICanvas; - renderTop(): ICanvas; - - sendBackwards(object: IObject): ICanvas; - sendToBack(object: IObject): ICanvas; - setBackgroundImage(image: any, callback: () => any, options?): ICanvas; - setDimensions(object: { width: number; height: number; }): ICanvas; - setHeight(height: number): ICanvas; - setOverlayImage(url: string, callback: () => any, options): ICanvas; - setWidth(width: number): ICanvas; - toDatalessJSON(propertiesToInclude?: any[]): string; - toDatalessObject(propertiesToInclude?: any[]): string; - toDataURL(format: string, quality?: number): string; - toDataURLWithMultiplier(propertiesToInclude: any[]): string; - toGrayscale(propertiesToInclude: any[]): string; - toJSON(propertiesToInclude: any[]): string; - toObject(propertiesToInclude: any[]): string; - tostring(): string; - toSVG(): string; - } - - export interface ICanvas extends IStaticCanvas { - - // constructors - (element: HTMLCanvasElement): ICanvas; - (element: string): ICanvas; - - _objects: IObject[]; - - // fields - containerClass: string; - defaultCursor: string; - freeDrawingColor: string; - freeDrawingLineWidth: number; - hoverCursor: string; - interactive: boolean; - moveCursor: string; - perPixelTargetFind: boolean; - rotationCursor: string; - selection: boolean; - selectionBorderColor: string; - selectionColor: string; - selectionDashArray: number[]; - selectionLineWidth: number; - targetFindTolerance: number; - - // methods - containsPoint(e: Event, target: IObject): boolean; - deactivateAll(): ICanvas; - deactivateAllWithDispatch(): ICanvas; - discardActiveGroup(): ICanvas; - discardActiveObject(): ICanvas; - drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, dashArray: number[]): ICanvas; - findTarget(e: MouseEvent, skipGroup: boolean): ICanvas; - getActiveGroup(): IGroup; - getActiveObject(): IObject; - getPointer(e): { x: number; y: number; }; - getSelectionContext(): CanvasRenderingContext2D; - getSelectionElement(): HTMLCanvasElement; - setActiveGroup(group: IGroup): ICanvas; - setActiveObject(object: IObject, e?): ICanvas; - - loadFromJSON(json, callback: () => void): void; - loadFromDatalessJSON(json, callback: () => void): void; - } - - export interface IPattern { - (options: IPatternOptions): IPattern; - - initialise(options: IPatternOptions): IPattern; - - toLive(ctx: CanvasRenderingContext2D): IPattern; - toObject(): any; - toSVG(): string; - - offsetX: number; - offsetY: number; - repeat: string; - source: any; - } - - export interface IBrightnessFilter { - } - export interface IInvertFilter { - } - export interface IRemoveWhiteFilter { - } - export interface IGrayscaleFilter { - } - export interface ISepiaFilter { - } - export interface ISepia2Filter { - } - export interface INoiseFilter { - } - export interface IGradientTransparencyFilter { - } - export interface IPixelateFilter { - } - export interface IConvoluteFilter { - } - - export interface ICanvasOptions { - containerClass?: string; - defaultCursor?: string; - freeDrawingColor?: string; - freeDrawingLineWidth?: number; - hoverCursor?: string; - interactive?: boolean; - moveCursor?: string; - perPixelTargetFind?: boolean; - rotationCursor?: string; - selection?: boolean; - selectionBorderColor?: string; - selectionColor?: string; - selectionDashArray?: number[]; - selectionLineWidth?: number; - targetFindTolerance?: number; - - backgroundColor?: string; - backgroundImage?: string; - backgroundImageOpacity?: number; - backgroundImageStretch?: number; - controlsAboveOverlay?: boolean; - includeDefaultValues?: boolean; - overlayImage?: string; - overlayImageLeft?: number; - overlayImageTop?: number; - renderOnAddition?: boolean; - stateful?: boolean; - } - - export interface IPatternOptions { - source: any; - offsetX: number; - offsetY: number; - repeat: string; - } - - export interface IRectOptions extends IObjectOptions { - x?: number; - y?: number; - rx?: number; - ry?: number; - } - - export interface ITriangleOptions extends IObjectOptions { - } - - var Rect: { - fromElement(element: SVGElement, options: IRectOptions): IRect; - fromObject(object): IRect; - new (options?: IRectOptions): IRect; - prototype: any; - } - - var Triangle: { - new (options?: ITriangleOptions): ITriangle; - } - - var Canvas: { - new (element: HTMLCanvasElement, options?: ICanvasOptions): ICanvas; - new (element: string, options?: ICanvasOptions): ICanvas; - - EMPTY_JSON: string; - supports(methodName: string): boolean; - prototype: any; - } - - var StaticCanvas: { - new (element: HTMLCanvasElement, options?: ICanvasOptions): ICanvas; - new (element: string, options?: ICanvasOptions): ICanvas; - - EMPTY_JSON: string; - supports(methodName: string): boolean; - prototype: any; - } - - var Pattern: { - new (options: IPatternOptions): IPattern; - - prototype: any; - } - - var Circle: { - ATTRIBUTE_NAMES: string[]; - fromElement(element: SVGElement, options: ICircleOptions): ICircle; - fromObject(object): ICircle; - new (options?: ICircleOptions): ICircle; - prototype: any; - } - - var Group: { - new (items?: any[], options?: IObjectOptions): IGroup; - } - - var Line: { - ATTRIBUTE_NAMES: string[]; - fromElement(element: SVGElement, options): ILine; - fromObject(object): ILine; - prototype: any; - new (points: number[], objObjects?: IObjectOptions): ILine; - } - - var Intersection: { - intersectLineLine(a1, a2, b1, b2); - intersectLinePolygon(a1, a2, points); - intersectPolygonPolygon(points1, points2); - intersectPolygonRectangle(points, r1, r2); - } - - var Path: { - fromElement(element: SVGElement, options): IPath; - fromObject(object): IPath; - new (): IPath; - } - - var PathGroup: { - fromObject(object): IPathGroup; - new (): IPathGroup; - prototype: any; - } - - var Point: { - new (x, y): IPoint; - prototype: any; - } - - var Object: { - prototype: any; - } - - var Polygon: { - fromObject(object): IPolygon; - fromElement(element: SVGElement, options): IPolygon; - new (): IPolygon; - prototype: any; - } - - var Polyline: { - fromObject(object): IPolyline; - fromElement(element: SVGElement, options): IPolyline; - new (): IPolyline; - prototype: any; - } - - var Text: { - new (text: string, options?: ITextOptions): IText; - } - - var Image: { - fromURL(url: string): IImage; - fromURL(url: string, callback: (image: IImage) => any): IImage; - fromURL(url: string, callback: (image: IImage) => any, objObjects: IObjectOptions): IImage; - new (element: HTMLImageElement, objObjects: IObjectOptions): IImage; - prototype: any; - - filters: - { - Grayscale: { - new (): IGrayscaleFilter; - }; - Brightness: { - new (options?: { brightness: number; }): IBrightnessFilter; - }; - RemoveWhite: { - new (options?: { - threshold?: string; // TODO: Check this - distance?: string; // TODO: Check this - }): IRemoveWhiteFilter; - }; - Invert: { - new (): IInvertFilter; - }; - Sepia: { - new (): ISepiaFilter; - }; - Sepia2: { - new (): ISepia2Filter; - }; - Noise: { - new (options?: { - noise?: number; - }): INoiseFilter; - }; - GradientTransparency: { - new (options?: { - threshold?: number; - }): IGradientTransparencyFilter; - }; - Pixelate: { - new (options?: { - color?: any; - }): IPixelateFilter; - }; - Convolute: { - new (options?: { - matrix: any; - }): IConvoluteFilter; - }; - }; - - } - - var util: { - addClass(element: HTMLElement, className: string); - addListener(element, eventName: string, handler); - animate(options: { - onChange?: (value: number) => void; - onComplete?: () => void; - startValue?: number; - endValue?: number; - byValue?: number; - easing?: (currentTime, startValue, byValue, duration) => number; - duration?: number; - }); - createClass(parent, properties); - degreesToRadians(degrees: number): number; - falseFunction(): () => boolean; - getById(id: HTMLElement): HTMLElement; - getById(id: string): HTMLElement; - getElementOffset(element): { left: number; top: number; }; - getPointer(event: Event); - getRandomInt(min: number, max: number); - getScript(url: string, callback); - groupSVGElements(elements: any[], options, path?: string); - loadImage(url, callback, context); - makeElement(tagName: string, attributes); - makeElementSelectable(element: HTMLElement); - makeElementUnselectable(element: HTMLElement); - populateWithProperties(source, destination, properties): any[]; - radiansToDegrees(radians: number): number; - removeFromArray(array: any[], value); - removeListener(element: HTMLElement, eventName, handler); - request(url, options); - requestAnimFrame(callback, element); - setStyle(element: HTMLElement, styles); - toArray(arrayLike): any[]; - toFixed(number, fractionDigits); - wrapElement(element: HTMLElement, wrapper, attributes); - rotatePoint(point: IPoint, origin: IPoint, radians: number); - transformPoint(p: IPoint, t: any[], ignoreOffset: boolean); - invertTransform(t: any[]); - parseUnit(value: number|string, fontSize?: number); - getKlass(type: string, namespace: string); - resolveNamespace(namespace: string); - enlivenObjects(objects: any[], callback: Function, namespace: string, reviver: Function); - drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, da: any[]); - createCanvasElement(canvasEl?: HTMLElement); - createImage(); - createAccessors(klass: Object); - clipContext(receiver: IObject, ctx: CanvasRenderingContext2D); - isTransparent(ctx: CanvasRenderingContext2D, x: number, y: number, tolerance: number); - - } + var isLikelyNode: boolean; + var isTouchSupported: boolean; + + ///////////////////////////////////////////////////////////// + // farbic Functions + ///////////////////////////////////////////////////////////// + + function createCanvasForNode(width: number, height: number): ICanvas; + + // Parse + // ---------------------------------------------------------- + /** + * Creates markup containing SVG referenced elements like patterns, gradients etc. + * @param {fabric.Canvas} canvas instance of fabric.Canvas + */ + function createSVGRefElementsMarkup(canvas: IStaticCanvas): string; + /** + * Creates markup containing SVG font faces + * @param {Array} objects Array of fabric objects + */ + function createSVGFontFacesMarkup(objects: IObject[]): string; + /** + * Takes string corresponding to an SVG document, and parses it into a set of fabric objects + * @param {String} string + * @param {Function} callback + * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ + function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function); + /** + * Takes url corresponding to an SVG document, and parses it into a set of fabric objects. + * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy) + * @param {String} url + * @param {Function} callback + * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ + function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function); + /** + * Returns CSS rules for a given SVG document + * @param {SVGDocument} doc SVG document to parse + */ + function getCSSRules(doc: SVGElement): any; + + function parseElements(elements: any[], callback: Function, options: any, reviver?: Function); + /** + * Parses "points" attribute, returning an array of values + * @param {String} points points attribute string + */ + function parsePointsAttribute(points: string): any[]; + /** + * Parses "style" attribute, retuning an object with values + * @param {SVGElement} element Element to parse + */ + function parseStyleAttribute(element: SVGElement): any; + /** + * Transforms an array of svg elements to corresponding fabric.* instances + * @param {Array} elements Array of elements to parse + * @param {Function} callback Being passed an array of fabric instances (transformed from SVG elements) + * @param {Object} [options] Options object + * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ + function parseElements(elements: any[], callback: Function, options?: any, reviver?: Function): void; + /** + * Returns an object of attributes' name/value, given element and an array of attribute names; + * Parses parent "g" nodes recursively upwards. + * @param {DOMElement} element Element to parse + * @param {Array} attributes Array of attributes to parse + */ + function parseAttributes(elemen: HTMLElement, attributes: string[], svgUid?: string): { [key: string]: string } + /** + * Parses an SVG document, returning all of the gradient declarations found in it + * @param {SVGDocument} doc SVG document to parse + */ + function getGradientDefs(doc: SVGElement): { [key: string]: any }; + /** + * Parses a short font declaration, building adding its properties to a style object + * @param {String} value font declaration + * @param {Object} oStyle definition + */ + function parseFontDeclaration(value: string, oStyle: any): void; + /** + * Parses an SVG document, converts it to an array of corresponding fabric.* instances and passes them to a callback + * @param {SVGDocument} doc SVG document to parse + * @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document). + * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. + */ + function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function); + /** + * Parses "transform" attribute, returning an array of values + * @param {String} attributeValue String containing attribute value + */ + function parseTransformAttribute(attributeValue: string): number[]; + + // fabric Log + // --------------- + /** + * Wrapper around `console.log` (when available) + */ + function log(...values: any[]); + /** + * Wrapper around `console.warn` (when available) + */ + function warn(...values: any[]); + + //////////////////////////////////////////////////// + // Classes + //////////////////////////////////////////////////// + var Canvas: ICanvasStatic; + var StaticCanvas: IStaticCanvasStatic; + + var Color: IColorStatic; + var Pattern: IPatternStatic; + var Intersection: IIntersectionStatic; + var Point: IPointStatic; + + var Circle: ICircleStatic; + var Ellipse: IEllipseStatic; + var Group: IGroupStatic; + var Image: IImageStatic; + var Line: ILineStatic; + var Object: IObjectStatic; + var Path: IPathStatic; + var PathGroup: IPathGroupStatic; + var Polygon: IPolygonStatic; + var Polyline: IPolylineStatic; + var Rect: IRectStatic; + var Shadow: IShadowStatic; + var Text: ITextStatic; + var IText: IITextStatic; + var Triangle: ITriangleStatic; + + var util: IUtil; + + /////////////////////////////////////////////////////////////////////////////// + // Data Object Interfaces - These intrface are not specific part of fabric, + // They are just helpful for for defining function paramters + ////////////////////////////////////////////////////////////////////////////// + interface IDataURLOptions { + /** + * The format of the output image. Either "jpeg" or "png" + */ + format?: string; + /** + * Quality level (0..1). Only used for jpeg + */ + quality?: number; + /** + * Multiplier to scale by + */ + multiplier?: number; + /** + * Cropping left offset. Introduced in v1.2.14 + */ + left?: number; + /** + * Cropping top offset. Introduced in v1.2.14 + */ + top?: number; + /** + * Cropping width. Introduced in v1.2.14 + */ + width?: number; + /** + * Cropping height. Introduced in v1.2.14 + */ + height?: number; + } + + interface IEvent { + e: Event; + target?: IObject; + } + + interface IFillOptions { + /** + * options.source Pattern source + */ + source: string | HTMLImageElement; + /** + * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) + */ + repeat?: string; + /** + * Pattern horizontal offset from object's left/top corner + */ + offsetX?: number; + /** + * Pattern vertical offset from object's left/top corner + */ + offsetY?: number; + } + + interface IToSVGOptions { + /** + * If true xml tag is not included + */ + suppressPreamble: boolean; + /** + * SVG viewbox object + */ + viewBox: IViewBox; + /** + * Encoding of SVG output + */ + encoding: string; + } + + interface IViewBox { + /** + * x-cooridnate of viewbox + */ + x: number; + /** + * y-coordinate of viewbox + */ + y: number; + /** + * Width of viewbox + */ + width: number; + /** + * Height of viewbox + */ + height: number; + } + + /////////////////////////////////////////////////////////////////////////////// + // Mixins Interfaces + ////////////////////////////////////////////////////////////////////////////// + interface ICollection { + /** + * Adds objects to collection, then renders canvas (if `renderOnAddRemove` is not `false`) + * Objects should be instances of (or inherit from) fabric.Object + * @param {...fabric.Object} object Zero or more fabric instances + */ + add(...object: IObject[]): T; + + /** + * Inserts an object into collection at specified index, then renders canvas (if `renderOnAddRemove` is not `false`) + * An object should be an instance of (or inherit from) fabric.Object + * @param {Object} object Object to insert + * @param {Number} index Index to insert object at + * @param {Boolean} nonSplicing When `true`, no splicing (shifting) of objects occurs + * @return {Self} thisArg + * @chainable + */ + insertAt(object: IObject, index: number, nonSplicing: boolean): T; + + /** + * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) + * @param {...fabric.Object} object Zero or more fabric instances + * @return {Self} thisArg + * @chainable + */ + remove(...object: IObject[]): T; + + /** + * Executes given function for each object in this group + * @param {Function} callback + * @param {Object} context Context (aka thisObject) + * @return {Self} thisArg + */ + forEachObject(callback: (element: IObject, index: number, array: IObject[]) => any, context?: any): T; + + /** + * Returns an array of children objects of this instance + * Type parameter introduced in 1.3.10 + * @param {String} [type] When specified, only objects of this type are returned + * @return {Array} + */ + getObjects(type?: string): IObject[]; + + /** + * Returns object at specified index + * @param {Number} index + * @return {Self} thisArg + */ + item(index: number): T; + + /** + * Returns true if collection contains no objects + * @return {Boolean} true if collection is empty + */ + isEmpty(): boolean; + + /** + * Returns a size of a collection (i.e: length of an array containing its objects) + * @return {Number} Collection size + */ + size(): number; + + /** + * Returns true if collection contains an object + * @param {Object} object Object to check against + * @return {Boolean} `true` if collection contains an object + */ + contains(object: IObject): boolean; + + /** + * Returns number representation of a collection complexity + * @return {Number} complexity + */ + complexity(): number; + } + + interface IObservable { + /** + * Observes specified event + * @param eventName Event name (eg. 'after:render') + * @param handler Function that receives a notification when an event of the specified type occurs + */ + on(eventName: string, handler: (e: IEvent) => any): T; + + /** + * Observes specified event + * @param eventName Object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) + */ + on(eventName: {[key:string] : Function}): T; + /** + * Fires event with an optional options object + * @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead) + * @param {String} eventName Event name to fire + * @param {Object} [options] Options object + */ + trigger(eventName: string, options?: any): T; + /** + * Stops event observing for a particular event handler. Calling this method + * without arguments removes all handlers for all events + * @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead) + * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) + * @param handler Function to be deleted from EventListeners + */ + off(eventName: string|any, handler: (e: IEvent) => any): T; + } + + // animation mixin + // ---------------------------------------------------- + interface ICanvasAnimation { + FX_DURATION: number; + /** + * Centers object horizontally with animation. + * @param {fabric.Object} object Object to center + * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties + * @param {Function} [callbacks.onComplete] Invoked on completion + * @param {Function} [callbacks.onChange] Invoked on every step of animation + */ + fxCenterObjectH(object: IObject, callbacks?: { onComplete: Function; onChange: Function; }): T; + + /** + * Centers object vertically with animation. + * @param {fabric.Object} object Object to center + * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties + * @param {Function} [callbacks.onComplete] Invoked on completion + * @param {Function} [callbacks.onChange] Invoked on every step of animation + */ + fxCenterObjectV(object: IObject, callbacks?: { onComplete: Function; onChange: Function; }): T; + + /** + * Same as `fabric.Canvas#remove` but animated + * @param {fabric.Object} object Object to remove + * @param {Object} [callbacks] Callbacks object with optional "onComplete" and/or "onChange" properties + * @param {Function} [callbacks.onComplete] Invoked on completion + * @param {Function} [callbacks.onChange] Invoked on every step of animation + * @return {fabric.Canvas} thisArg + * @chainable + */ + fxRemove(object: IObject, callbacks?: { onComplete: Function; onChange: Function; }): T; + } + interface IObjectAnimation { + /** + * Animates object's properties + * object.animate('left', ..., {duration: ...}); + * @param property Property to animate + * @param value Value to animate property + * @param options The animation options + */ + animate(property: string, value: number|string, options?: IAnimationOptions): IObject; + /** + * Animates object's properties + * object.animate({ left: ..., top: ... }, { duration: ... }); + * @param properties Properties to animate + * @param value Options object + */ + animate(properties: any, options?: IAnimationOptions): IObject; + } + interface IAnimationOptions { + /** + * Allows to specify starting value of animatable property (if we don't want current value to be used). + */ + from?: string|number; + /** + * Defaults to 500 (ms). Can be used to change duration of an animation. + */ + duration?: number; + /** + * Callback; invoked on every value change + */ + onChange?: Function; + /** + * Callback; invoked when value change is completed + */ + onComplete?: Function; + + /** + * Easing function. Default: fabric.util.ease.easeInSine + */ + easing?: Function; + /** + * Value to modify the property by, default: end - start + */ + by?: number; + } + + /////////////////////////////////////////////////////////////////////////////// + // General Fabric Interfaces + ////////////////////////////////////////////////////////////////////////////// + interface IColor { + /** + * Returns source of this color (where source is an array representation; ex: [200, 200, 100, 1]) + */ + getSource(): number[]; + + /** + * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1]) + */ + setSource(source: number[]); + + /** + * Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255) + */ + toRgb(): string; + + /** + * Returns color represenation in RGBA format ex: rgba(0-255,0-255,0-255,0-1) + */ + toRgba(): string; + + /** + * Returns color represenation in HSL format ex: hsl(0-360,0%-100%,0%-100%) + */ + toHsl(): string; + + /** + * Returns color represenation in HSLA format ex: hsla(0-360,0%-100%,0%-100%,0-1) + */ + toHsla(): string; + + /** + * Returns color represenation in HEX format ex: FF5555 + */ + toHex(): string; + + /** + * Gets value of alpha channel for this color + */ + getAlpha(): number; + + /** + * Sets value of alpha channel for this color + * @param {Number} alpha Alpha value 0-1 + */ + setAlpha(alpha: number); + + /** + * Transforms color to its grayscale representation + */ + toGrayscale(): IColor; + + /** + * Transforms color to its black and white representation + * @param {Number} threshold + */ + toBlackWhite(threshold: number): IColor; + /** + * Overlays color with another color + * @param {String|fabric.Color} otherColor + */ + overlayWith(otherColor: string|IColor): IColor; + } + interface IColorStatic { + /** + * Color class + * The purpose of Color is to abstract and encapsulate common color operations; + * @param {String} color optional in hex or rgb(a) format + */ + new (color?: string): IColor; + + /** + * Returns new color object, when given a color in RGB format + * @param {String} color Color value ex: rgb(0-255,0-255,0-255) + */ + fromRgb(color: string): IColor; + /** + * Returns new color object, when given a color in RGBA format + * @param {String} color Color value ex: rgb(0-255,0-255,0-255) + */ + fromRgba(color: string): IColor; + /** + * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in RGB or RGBA format + * @param {String} color Color value ex: rgb(0-255,0-255,0-255), rgb(0%-100%,0%-100%,0%-100%) + */ + sourceFromRgb(color: string): number[]; + /** + * Returns new color object, when given a color in HSL format + * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%) + */ + fromHsl(color: string): IColor; + /** + * Returns new color object, when given a color in HSLA format + * @param {String} color Color value ex: hsl(0-260,0%-100%,0%-100%) + */ + fromHsla(color: string): IColor; + /** + * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HSL or HSLA format. + * @param {String} color Color value ex: hsl(0-360,0%-100%,0%-100%) or hsla(0-360,0%-100%,0%-100%, 0-1) + */ + sourceFromHsl(color: string): number[]; + /** + * Returns new color object, when given a color in HEX format + * @param {String} color Color value ex: FF5555 + */ + fromHex(color: string): IColor; + + /** + * Returns array represenatation (ex: [100, 100, 200, 1]) of a color that's in HEX format + * @param {String} color ex: FF5555 + */ + sourceFromHex(color: string): number[]; + /** + * Returns new color object, when given color in array representation (ex: [200, 100, 100, 0.5]) + * @param {Array} source + */ + fromSource(source: number[]): IColor; + prototype: any; + } + + interface IGradientOptions { + /** + * @param {String} [options.type] Type of gradient 'radial' or 'linear' + */ + type?: string; + /** + * x-coordinate of start point + */ + x1?: number; + /** + * y-coordinate of start point + */ + y1?: number; + /** + * x-coordinate of end point + */ + x2?: number; + /** + * y-coordinate of end point + */ + y2?: number; + /** + * Radius of start point (only for radial gradients) + */ + r1?: number; + /** + * Radius of end point (only for radial gradients) + */ + r2?: number; + /** + * Color stops object eg. {0:string; 1:string; + */ + colorStops?: any; + } + interface IGradient extends IGradientOptions { + /** + * Adds another colorStop + * @param {Object} colorStop Object with offset and color + */ + addColorStop(colorStop: any): IGradient; + /** + * Returns object representation of a gradient + */ + toObject(): any; + /** + * Returns SVG representation of an gradient + * @param {Object} object Object to create a gradient for + * @param {Boolean} normalize Whether coords should be normalized + * @return {String} SVG representation of an gradient (linear/radial) + */ + toSVG(object: IObject, normalize?: boolean): string; + + /** + * Returns an instance of CanvasGradient + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + toLive(ctx: CanvasRenderingContext2D, object?: IPathGroup): CanvasGradient; + } + interface IGrandientStatic { + new (options?: IGradientOptions): IGradient; + /** + * Returns instance from an SVG element + * @param {SVGGradientElement} el SVG gradient element + * @param {fabric.Object} instance + */ + fromElement(el: SVGGradientElement, instance: IObject): IGradient; + /** + * Returns instance from its object representation + * @param {Object} obj + * @param {Object} [options] Options object + */ + fromObject(obj: any, options: any[]): IGradient; + } + + interface IIntersection { + /** + * Appends a point to intersection + */ + appendPoint(point: IPoint); + /** + * Appends points to intersection + */ + appendPoints(points: IPoint[]); + } + interface IIntersectionStatic { + /** + * Intersection class + */ + new (status?: string); + /** + * Checks if polygon intersects another polygon + */ + intersectPolygonPolygon(points1: IPoint[], points2: IPoint[]): IIntersection; + /** + * Checks if line intersects polygon + */ + intersectLinePolygon(a1: IPoint, a2: IPoint, points: IPoint[]): IIntersection; + /** + * Checks if one line intersects another + */ + intersectLineLine(a1: IPoint, a2: IPoint, b1: IPoint, b2: IPoint): IIntersection; + /** + * Checks if polygon intersects rectangle + */ + intersectPolygonRectangle(points: IPoint[], r1: number, r2: number): IIntersection; + } + + interface IPatternOptions { + /** + * Repeat property of a pattern (one of repeat, repeat-x, repeat-y or no-repeat) + */ + repeat: string; + + /** + * Pattern horizontal offset from object's left/top corner + */ + offsetX: number; + + /** + * Pattern vertical offset from object's left/top corner + */ + offsetY: number; + /** + * The source for the pattern + */ + source: string|HTMLImageElement; + } + interface IPattern extends IPatternOptions { + new (options?: IPatternOptions): IPattern; + + initialise(options?: IPatternOptions): IPattern; + /** + * Returns an instance of CanvasPattern + */ + toLive(ctx: CanvasRenderingContext2D): IPattern; + + /** + * Returns object representation of a pattern + */ + toObject(): any; + /** + * Returns SVG representation of a pattern + * @param {fabric.Object} object + */ + toSVG(object: IObject): string; + } + interface IPatternStatic { + new (options?: IPatternOptions): IPattern; + prototype: any; + } + + interface IPoint { + x: number; + y: number; + /** + * Adds another point to this one and returns another one + * @param {fabric.Point} that + */ + add(that: IPoint): IPoint; + + /** + * Adds another point to this one + * @param {fabric.Point} that + */ + addEquals(that: IPoint): IPoint; + + /** + * Adds value to this point and returns a new one + * @param {Number} scalar + */ + scalarAdd(scalar: number): IPoint; + + /** + * Adds value to this point + * @param {Number} scalar + */ + scalarAddEquals(scalar: number): IPoint; + + /** + * Subtracts another point from this point and returns a new one + * @param {fabric.Point} that + */ + subtract(that: IPoint): IPoint; + + /** + * Subtracts another point from this point + * @param {fabric.Point} that + */ + subtractEquals(that: IPoint): IPoint; + + /** + * Subtracts value from this point and returns a new one + * @param {Number} scalar + */ + scalarSubtract(scalar: number): IPoint; + + /** + * Subtracts value from this point + * @param {Number} scalar + */ + scalarSubtractEquals(scalar: number): IPoint; + + /** + * Miltiplies this point by a value and returns a new one + * @param {Number} scalar + */ + multiply(scalar: number): IPoint; + + /** + * Miltiplies this point by a value + * @param {Number} scalar + */ + multiplyEquals(scalar: number): IPoint; + + /** + * Divides this point by a value and returns a new one + * @param {Number} scalar + */ + divide(scalar: number): IPoint; + + /** + * Divides this point by a value + * @param {Number} scalar + */ + divideEquals(scalar: number): IPoint; + + /** + * Returns true if this point is equal to another one + * @param {fabric.Point} that + */ + eq(that: IPoint): IPoint; + + /** + * Returns true if this point is less than another one + * @param {fabric.Point} that + */ + lt(that: IPoint): IPoint; + + /** + * Returns true if this point is less than or equal to another one + * @param {fabric.Point} that + */ + lte(that: IPoint): IPoint; + + /** + * Returns true if this point is greater another one + * @param {fabric.Point} that + */ + gt(that: IPoint): IPoint; + + /** + * Returns true if this point is greater than or equal to another one + * @param {fabric.Point} that + */ + gte(that: IPoint): IPoint; + + /** + * Returns new point which is the result of linear interpolation with this one and another one + * @param {fabric.Point} that + * @param {Number} t + */ + lerp(that: IPoint, t: number): IPoint; + + /** + * Returns distance from this point and another one + * @param {fabric.Point} that + */ + distanceFrom(that: IPoint): number; + + /** + * Returns the point between this point and another one + * @param {fabric.Point} that + */ + midPointFrom(that: IPoint): IPoint; + + /** + * Returns a new point which is the min of this and another one + * @param {fabric.Point} that + */ + min(that: IPoint): IPoint; + + /** + * Returns a new point which is the max of this and another one + * @param {fabric.Point} that + */ + max(that: IPoint): IPoint; + + /** + * Returns string representation of this point + */ + toString(): string; + + /** + * Sets x/y of this point + * @param {Number} x + * @param {Number} y + */ + setXY(x:number, y: number): IPoint; + + /** + * Sets x/y of this point from another point + * @param {fabric.Point} that + */ + setFromPoint(that: IPoint): IPoint; + + /** + * Swaps x/y of this point and another point + * @param {fabric.Point} that + */ + swap(that: IPoint): IPoint; + } + interface IPointStatic { + new (x: number, y: number): IPoint; + prototype: any; + } + + interface IShadowOptions { + /** + * Whether the shadow should affect stroke operations + */ + affectStrike: boolean; + /** + * Shadow blur + */ + blur: number; + /** + * Shadow color + */ + color: string; + /** + * Indicates whether toObject should include default values + */ + includeDefaultValues: boolean; + /** + * Shadow horizontal offset + */ + offsetX: number; + /** + * Shadow vertical offset + */ + offsetY: number; + } + interface IShadow extends IShadowOptions { + initialize(options?: IShadowOptions|string): IShadow; + /** + * Returns object representation of a shadow + */ + toObject(): IObject; + /** + * Returns a string representation of an instance, CSS3 text-shadow declaration + */ + toString(): string; + /** + * Returns SVG representation of a shadow + * @param {fabric.Object} object + */ + toSVG(object: IObject): string; + + /** + * Regex matching shadow offsetX, offsetY and blur, Static + */ + reOffsetsAndBlur: RegExp + } + interface IShadowStatic { + new (options?: IShadowOptions): IShadow; + reOffsetsAndBlur: RegExp; + } + + /////////////////////////////////////////////////////////////////////////////// + // Canvas Interfaces + ////////////////////////////////////////////////////////////////////////////// + interface ICanvasDimensions { + /** + * Width of canvas element + */ + width: number; + /** + * Height of canvas element + */ + height: number; + } + interface ICanvasDimensionsOptions { + /** + * Set the given dimensions only as canvas backstore dimensions + */ + backstoreOnly?: boolean; + /** + * Set the given dimensions only as css dimensions + */ + cssOnly?: boolean; + } + + interface IStaticCanvasOptions { + /** + * Indicates whether the browser can be scrolled when using a touchscreen and dragging on the canvas + */ + allowTouchScrolling?: boolean; + /** + * Indicates whether this canvas will use image smoothing, this is on by default in browsers + */ + imageSmoothingEnabled?: boolean; + + /** + * Indicates whether objects should remain in current stack position when selected. + * When false objects are brought to top and rendered as part of the selection group + */ + preserveObjectStacking?: boolean; + + /** + * The transformation (in the format of Canvas transform) which focuses the viewport + */ + viewportTransform?: number[]; + + freeDrawingColor?: string; + freeDrawingLineWidth?: number; + + /** + * Background color of canvas instance. + * Should be set via setBackgroundColor + */ + backgroundColor?: string|IPattern; + /** + * Background image of canvas instance. + * Should be set via setBackgroundImage + * Backwards incompatibility note: The "backgroundImageOpacity" and "backgroundImageStretch" properties are deprecated since 1.3.9. + */ + backgroundImage?: IImage | string; + backgroundImageOpacity?: number; + backgroundImageStretch?: number; + /** + * Function that determines clipping of entire canvas area + * Being passed context as first argument. See clipping canvas area + */ + clipTo?: (context: CanvasRenderingContext2D) => void; + + /** + * Indicates whether object controls (borders/controls) are rendered above overlay image + */ + controlsAboveOverlay?: boolean; + + /** + * Indicates whether toObject/toDatalessObject should include default values + */ + includeDefaultValues?: boolean; + /** + * Overlay color of canvas instance. + * Should be set via setOverlayColor + */ + overlayColor?: string|IPattern; + /** + * Overlay image of canvas instance. + * Should be set via setOverlayImage + * Backwards incompatibility note: The "overlayImageLeft" and "overlayImageTop" properties are deprecated since 1.3.9. + */ + overlayImage?: IImage; + overlayImageLeft?: number; + overlayImageTop?: number; + /** + * Indicates whether add, insertAt and remove should also re-render canvas. + * Disabling this option could give a great performance boost when adding/removing a lot of objects to/from canvas at once + * (followed by a manual rendering after addition/deletion) + */ + renderOnAddRemove?: boolean; + /** + * Indicates whether objects' state should be saved + */ + stateful?: boolean; + } + interface IStaticCanvas extends IObservable, IStaticCanvasOptions, ICollection, ICanvasAnimation { + /** + * Calculates canvas element offset relative to the document + * This method is also attached as "resize" event handler of window + */ + calcOffset(): IStaticCanvas; + + /** + * Sets {@link fabric.StaticCanvas#overlayImage|overlay image} for this canvas + * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set overlay to + * @param {Function} callback callback to invoke when image is loaded and set as an overlay + * @param {Object} [options] Optional options to set for the {@link fabric.Image|overlay image}. + */ + setOverlayImage(image: IImage|string, callback: Function, options?: IObjectOptions): IStaticCanvas; + + /** + * Sets {@link fabric.StaticCanvas#backgroundImage|background image} for this canvas + * @param {(fabric.Image|String)} image fabric.Image instance or URL of an image to set background to + * @param {Function} callback Callback to invoke when image is loaded and set as background + * @param {Object} [options] Optional options to set for the {@link fabric.Image|background image}. + */ + setBackgroundImage(image: IImage|string, callback: Function, options?: IObjectOptions): IStaticCanvas; + + /** + * Sets {@link fabric.StaticCanvas#overlayColor|background color} for this canvas + * @param {(String|fabric.Pattern)} overlayColor Color or pattern to set background color to + * @param {Function} callback Callback to invoke when background color is set + */ + setOverlayColor(overlayColor: string|IPattern, callback: Function): IStaticCanvas; + + /** + * Sets {@link fabric.StaticCanvas#backgroundColor|background color} for this canvas + * @param {(String|fabric.Pattern)} backgroundColor Color or pattern to set background color to + * @param {Function} callback Callback to invoke when background color is set + */ + setBackgroundColor(backgroundColor: string|IPattern, callback: Function): IStaticCanvas; + + /** + * Returns canvas width (in px) + */ + getWidth(): number; + + /** + * Returns canvas height (in px) + */ + getHeight(): number; + + /** + * Sets width of this canvas instance + * @param {Number|String} value Value to set width to + * @param {Object} [options] Options object + */ + setWidth(value: number|string, options?: ICanvasDimensionsOptions): IStaticCanvas + + /** + * Sets height of this canvas instance + * @param {Number|String} value Value to set height to + * @param {Object} [options] Options object + */ + setHeight(value: number|string, options?: ICanvasDimensionsOptions): IStaticCanvas; + + /** + * Sets dimensions (width, height) of this canvas instance. when options.cssOnly flag active you should also supply the unit of measure (px/%/em) + * @param {Object} dimensions Object with width/height properties + * @param {Object} [options] Options object + */ + setDimensions(dimensions: ICanvasDimensions, options?: ICanvasDimensionsOptions): IStaticCanvas; + + /** + * Returns canvas zoom level + */ + getZoom(): number; + + /** + * Sets viewport transform of this canvas instance + * @param {Array} vpt the transform in the form of context.transform + */ + setViewportTransform(vpt: number[]): IStaticCanvas; + + /** + * Sets zoom level of this canvas instance, zoom centered around point + * @param {fabric.Point} point to zoom with respect to + * @param {Number} value to set zoom to, less than 1 zooms out + */ + zoomToPoint(point: IPoint, value: number): IStaticCanvas; + + /** + * Sets zoom level of this canvas instance + * @param {Number} value to set zoom to, less than 1 zooms out + */ + setZoom(value: number): IStaticCanvas; + + /** + * Pan viewport so as to place point at top left corner of canvas + * @param {fabric.Point} point to move to + */ + absolutePan(point: IPoint): IStaticCanvas; + + /** + * Pans viewpoint relatively + * @param {fabric.Point} point (position vector) to move by + */ + relativePan(point: IPoint): IStaticCanvas; + + /** + * Returns element corresponding to this instance + */ + getElement(): HTMLCanvasElement; + + /** + * Returns currently selected object, if any + */ + getActiveObject(): IObject; + + /** + * Returns currently selected group of object, if any + */ + getActiveGroup(): IGroup; + + /** + * Clears specified context of canvas element + * @param {CanvasRenderingContext2D} ctx Context to clear + * @chainable + */ + clearContext(ctx: CanvasRenderingContext2D): IStaticCanvas; + + /** + * Returns context of canvas where objects are drawn + */ + getContext(): CanvasRenderingContext2D; + + /** + * Clears all contexts (background, main, top) of an instance + */ + clear(): IStaticCanvas; + + /** + * Renders both the top canvas and the secondary container canvas. + * @param {Boolean} [allOnTop] Whether we want to force all images to be rendered on the top canvas + * @chainable + */ + renderAll(allOnTop?: boolean): IStaticCanvas; + + /** + * Method to render only the top canvas. + * Also used to render the group selection box. + * @chainable + */ + renderTop(): IStaticCanvas; + + /** + * Returns coordinates of a center of canvas. + * Returned value is an object with top and left properties + */ + getCenter(): { top: number; left: number; }; + /** + * Centers object horizontally. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param {fabric.Object} object Object to center horizontally + */ + centerObjectH(object: IObject): IStaticCanvas; + + /** + * Centers object vertically. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param {fabric.Object} object Object to center vertically + */ + centerObjectV(object: IObject): IStaticCanvas; + + /** + * Centers object vertically and horizontally. + * You might need to call `setCoords` on an object after centering, to update controls area. + * @param {fabric.Object} object Object to center vertically and horizontally + */ + centerObject(object: IObject): IStaticCanvas; + + /** + * Returs dataless JSON representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toDatalessJSON(propertiesToInclude?: any[]): string; + + /** + * Returns object representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: any[]): any; + + /** + * Returns dataless object representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toDatalessObject(propertiesToInclude?: any[]): any; + + /** + * When true, getSvgTransform() will apply the StaticCanvas.viewportTransform to the SVG transformation. When true, + * a zoomed canvas will then produce zoomed SVG output. + */ + svgViewportTransformation: boolean; + + /** + * Returns SVG representation of canvas + * @param {Object} [options] Options object for SVG output + * @param {Function} [reviver] Method for further parsing of svg elements, called after each fabric object converted into svg representation. + */ + toSVG(options: IToSVGOptions, reviver?: Function): string; + + /** + * Moves an object to the bottom of the stack of drawn objects + * @param {fabric.Object} object Object to send to back + * @chainable + */ + sendToBack(object: IObject): IStaticCanvas; + + /** + * Moves an object to the top of the stack of drawn objects + * @param {fabric.Object} object Object to send + * @chainable + */ + bringToFront(object: IObject): IStaticCanvas; + + /** + * Moves an object down in stack of drawn objects + * @param {fabric.Object} object Object to send + * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object + * @chainable + */ + sendBackwards(object: IObject): IStaticCanvas; + + /** + * Moves an object up in stack of drawn objects + * @param {fabric.Object} object Object to send + * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object + * @chainable + */ + bringForward(object: IObject): IStaticCanvas; + /** + * Moves an object to specified level in stack of drawn objects + * @param {fabric.Object} object Object to send + * @param {Number} index Position to move to + * @chainable + */ + moveTo(object: IObject, index: number): IStaticCanvas; + + /** + * Clears a canvas element and removes all event listeners + */ + dispose(): IStaticCanvas; + + /** + * Returns a string representation of an instance + */ + toString(): string; + + /** + * Exports canvas element to a dataurl image. Note that when multiplier is used, cropping is scaled appropriately + * @param {Object} [options] Options object + */ + toDataURL(options?: IDataURLOptions): string; + + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * @param {String} methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" + * @return {Boolean | null} `true` if method is supported (or at least exists), null` if canvas element or context can not be initialized + */ + supports(methodName: string): boolean; + + /** + * Populates canvas with data from the specified JSON. + * JSON format must conform to the one of toJSON formats + * @param {String|Object} json JSON string or object + * @param {Function} callback Callback, invoked when json is parsed + * and corresponding objects (e.g: {@link fabric.Image}) + * are initialized + * @param {Function} [reviver] Method for further parsing of JSON elements, called after each fabric object created. + */ + loadFromJSON(json: string|any, callback: Function, reviver?: Function): ICanvas; + /** + * Clones canvas instance + * @param {Object} [callback] Receives cloned instance as a first argument + * @param {Array} [properties] Array of properties to include in the cloned canvas and children + */ + clone(callback: (canvas: IStaticCanvas) => any, properties?: any[]): void; + + /** + * Clones canvas instance without cloning existing data. + * This essentially copies canvas dimensions, clipping properties, etc. + * but leaves data empty (so that you can populate it with your own) + * @param {Object} [callback] Receives cloned instance as a first argument + */ + cloneWithoutData(callback: (canvas: IStaticCanvas) => any): void; + + /** + * Callback; invoked right before object is about to be scaled/rotated + */ + onBeforeScaleRotate(target: IObject); + + // Functions from object straighten mixin + // -------------------------------------------------------------------------------------------------------------------------------- + + /** + * Straightens object, then rerenders canvas + * @param {fabric.Object} object Object to straighten + */ + straightenObject(object: IObject): IStaticCanvas + + /** + * Same as straightenObject, but animated + * @param {fabric.Object} object Object to straighten + */ + fxStraightenObject(object: IObject): IStaticCanvas + } + interface IStaticCanvasStatic { + /** + * Constructor + * @param {HTMLElement|String} element element to initialize instance on + * @param {Object} [options] Options object + */ + new (element: HTMLCanvasElement|string, options?: ICanvasOptions): IStaticCanvas; + + EMPTY_JSON: string; + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * @param {String} methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" + */ + supports(methodName: string): boolean; + prototype: any; + /** + * Returns JSON representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toJSON(propertiesToInclude?: any[]): string; + } + + interface ICanvasOptions extends IStaticCanvasOptions { + /** + * When true, objects can be transformed by one side (unproportionally) + */ + uniScaleTransform?: boolean; + + /** + * When true, objects use center point as the origin of scale transformation. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredScaling?: boolean; + + /** + * When true, objects use center point as the origin of rotate transformation. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredRotation?: boolean; + + /** + * Indicates that canvas is interactive. This property should not be changed. + */ + interactive?: boolean; + + /** + * Indicates whether group selection should be enabled + */ + selection?: boolean; + + /** + * Color of selection + */ + selectionColor?: string; + + /** + * Default dash array pattern + * If not empty the selection border is dashed + */ + selectionDashArray?: any[]; + + /** + * Color of the border of selection (usually slightly darker than color of selection itself) + */ + selectionBorderColor?: string; + + /** + * Width of a line used in object/group selection + */ + selectionLineWidth?: number; + + /** + * Default cursor value used when hovering over an object on canvas + */ + hoverCursor?: string; + + /** + * Default cursor value used when moving an object on canvas + */ + moveCursor?: string; + + /** + * Default cursor value used for the entire canvas + */ + defaultCursor?: string; + + /** + * Cursor value used during free drawing + */ + freeDrawingCursor?: string; + + /** + * Cursor value used for rotation point + */ + rotationCursor?: string; + + /** + * Default element class that's given to wrapper (div) element of canvas + */ + containerClass?: string; + + /** + * When true, object detection happens on per-pixel basis rather than on per-bounding-box + */ + perPixelTargetFind?: boolean; + + /** + * Number of pixels around target pixel to tolerate (consider active) during object detection + */ + targetFindTolerance?: number; + + /** + * When true, target detection is skipped when hovering over canvas. This can be used to improve performance. + */ + skipTargetFind?: boolean; + + /** + * When true, mouse events on canvas (mousedown/mousemove/mouseup) result in free drawing. + * After mousedown, mousemove creates a shape, + * and then mouseup finalizes it and adds an instance of `fabric.Path` onto canvas. + */ + isDrawingMode?: boolean; + } + interface ICanvas extends IStaticCanvas, ICanvasOptions { + _objects: IObject[]; + + /** + * Checks if point is contained within an area of given object + * @param {Event} e Event object + * @param {fabric.Object} target Object to test against + */ + containsPoint(e: Event, target: IObject): boolean; + /** + * Deactivates all objects on canvas, removing any active group or object + * @return {fabric.Canvas} thisArg + */ + deactivateAll(): ICanvas; + /** + * Deactivates all objects and dispatches appropriate events + * @param {Event} [e] Event (passed along when firing) + * @return {fabric.Canvas} thisArg + */ + deactivateAllWithDispatch(e?: Event): ICanvas; + /** + * Discards currently active group + * @param {Event} [e] Event (passed along when firing) + * @return {fabric.Canvas} thisArg + */ + discardActiveGroup(e?: Event): ICanvas; + /** + * Discards currently active object + * @param {Event} [e] Event (passed along when firing) + * @return {fabric.Canvas} thisArg + * @chainable + */ + discardActiveObject(e?: Event): ICanvas; + /** + * Draws objects' controls (borders/controls) + * @param {CanvasRenderingContext2D} ctx Context to render controls on + */ + drawControls(ctx: CanvasRenderingContext2D): void; + /** + * Method that determines what object we are clicking on + * @param {Event} e mouse event + * @param {Boolean} skipGroup when true, group is skipped and only objects are traversed through + */ + findTarget(e: MouseEvent, skipGroup: boolean): ICanvas; + /** + * Returns currently active group + * @return {fabric.Group} Current group + */ + getActiveGroup(): IGroup; + /** + * Returns currently active object + * @return {fabric.Object} active object + */ + getActiveObject(): IObject; + /** + * Returns pointer coordinates relative to canvas. + * @param {Event} e + * @return {Object} object with "x" and "y" number values + */ + getPointer(e: Event, ignoreZoom?: boolean, upperCanvasEl?: CanvasRenderingContext2D): { x: number; y: number; }; + /** + * Returns context of canvas where object selection is drawn + * @return {CanvasRenderingContext2D} + */ + getSelectionContext(): CanvasRenderingContext2D; + /** + * Returns element on which object selection is drawn + * @return {HTMLCanvasElement} + */ + getSelectionElement(): HTMLCanvasElement; + /** + * Returns true if object is transparent at a certain location + * @param {fabric.Object} target Object to check + * @param {Number} x Left coordinate + * @param {Number} y Top coordinate + */ + isTargetTransparent(target: IObject, x: number, y: number): boolean; + /** + * Sets active group to a speicified one + * @param {fabric.Group} group Group to set as a current one + * @param {Event} [e] Event (passed along when firing) + */ + setActiveGroup(group: IGroup, e?: Event): ICanvas; + /** + * Sets given object as the only active object on canvas + * @param {fabric.Object} object Object to set as an active one + * @param {Event} [e] Event (passed along when firing "object:selected") + */ + setActiveObject(object: IObject, e?: Event): ICanvas; + /** + * Set the cursor type of the canvas element + * @param {String} value Cursor type of the canvas element. + * @see http://www.w3.org/TR/css3-ui/#cursor + */ + setCursor(value: string): void; + + /** + * Removes all event listeners + */ + removeListeners(): void + } + interface ICanvasStatic { + /** + * Constructor + * @param {HTMLElement|String} element element to initialize instance on + * @param {Object} [options] Options object + */ + new (element: HTMLCanvasElement | string, options?: ICanvasOptions): ICanvas; + + EMPTY_JSON: string; + /** + * Provides a way to check support of some of the canvas methods + * (either those of HTMLCanvasElement itself, or rendering context) + * @param {String} methodName Method to check support for; Could be one of "getImageData", "toDataURL", "toDataURLWithQuality" or "setLineDash" + */ + supports(methodName: string): boolean; + prototype: any; + /** + * Returns JSON representation of canvas + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toJSON(propertiesToInclude?: any[]): string; + } + + /////////////////////////////////////////////////////////////////////////////// + // Shape Interfaces + ////////////////////////////////////////////////////////////////////////////// + + interface ICircleOptions extends IObjectOptions { + /** + * Radius of this circle + */ + radius?: number; + /** + * Start angle of the circle, moving clockwise + */ + startAngle?: number; + + /** + * End angle of the circle + */ + endAngle?: number; + } + interface ICircle extends IObject, ICircleOptions { + /** + * Returns complexity of an instance + * @return {Number} complexity of this instance + */ + complexity(): number; + /** + * Returns horizontal radius of an object (according to how an object is scaled) + * @return {Number} + */ + getRadiusX(): number; + /** + * Returns vertical radius of an object (according to how an object is scaled) + * @return {Number} + */ + getRadiusY(): number; + /** + * Sets radius of an object (and updates width accordingly) + * @return {Number} + */ + setRadius(value: number): number; + + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface ICircleStatic { + /** + * List of attribute names to account for when parsing SVG element (used by {@link fabric.Circle.fromElement}) + */ + ATTRIBUTE_NAMES: string[]; + /** + * Returns Circle instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, options: ICircleOptions): ICircle; + /** + * Returns Circle instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ICircle; + /** + * Circle class + */ + new (options?: ICircleOptions): ICircle; + prototype: any; + } + + interface IEllipseOptions extends IObjectOptions { + /** + * Horizontal radius + */ + rx?: number; + /** + * Vertical radius + */ + ry?: number; + } + interface IEllipse extends IObject, IEllipseOptions { + /** + * Returns horizontal radius of an object (according to how an object is scaled) + * @return {Number} + */ + getRx(): number; + + /** + * Returns Vertical radius of an object (according to how an object is scaled) + * @return {Number} + */ + getRy(): number; + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + /** + * Returns complexity of an instance + * @return {Number} complexity + */ + complexity(): number; + } + interface IEllipseStatic { + new (options?: IEllipseOptions): IEllipse; + /** + * List of attribute names to account for when parsing SVG element (used by {@link fabric.Ellipse.fromElement}) + */ + ATTRIBUTE_NAMES: string[]; + + /** + * Returns Ellipse instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, options?: IEllipseOptions): IEllipse; + + /** + * Returns Ellipse instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IEllipse; + } + + interface IGroup extends IObject, ICollection { + activateAllObjects(): IGroup; + /** + * Adds an object to a group; Then recalculates group's dimension, position. + * @param {Object} object + * @return {fabric.Group} thisArg + * @chainable + */ + addWithUpdate(object: IObject): IGroup; + containsPoint(point: IPoint): boolean; + /** + * Destroys a group (restoring state of its objects) + * @return {fabric.Group} thisArg + * @chainable + */ + destroy(): IGroup; + /** + * Returns requested property + * @param {String} prop Property to get + * @return {Any} + */ + get(prop: string): any; + /** + * Checks whether this group was moved (since `saveCoords` was called last) + * @return {Boolean} true if an object was moved (since fabric.Group#saveCoords was called) + */ + hasMoved(): boolean; + /** + * Removes an object from a group; Then recalculates group's dimension, position. + * @param {Object} object + * @return {fabric.Group} thisArg + * @chainable + */ + removeWithUpdate(object: IObject): IGroup; + /** + * Renders instance on a given context + * @param {CanvasRenderingContext2D} ctx context to render instance on + */ + render(ctx: CanvasRenderingContext2D): void; + /** + * Removes objects from a collection, then renders canvas (if `renderOnAddRemove` is not `false`) + * @param {...fabric.Object} object Zero or more fabric instances + * @return {Self} thisArg + * @chainable + */ + remove(...object: IObject[]): IGroup; + /** + * Saves coordinates of this instance (to be used together with `hasMoved`) + * @saveCoords + * @return {fabric.Group} thisArg + * @chainable + */ + saveCoords(): IGroup; + /** + * Sets coordinates of all group objects + * @return {fabric.Group} thisArg + * @chainable + */ + setObjectsCoords(): IGroup; + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns string represenation of a group + * @return {String} + */ + toString(): string; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface IGroupStatic { + /** + * Constructor + * @param {Object} objects Group objects + * @param {Object} [options] Options object + */ + new (items?: any[], options?: IObjectOptions): IGroup; + /** + * Returns {@link fabric.Group} instance from an object representation + * @param {Object} object Object to create a group from + * @param {Function} [callback] Callback to invoke when an group instance is created + */ + fromObject(object: any, callback: (group: IGroup) => any): void; + } + + interface IImageOptions extends IObjectOptions { + /** + * crossOrigin value (one of "", "anonymous", "allow-credentials") + */ + crossOrigin: string; + + /** + * AlignX value, part of preserveAspectRatio (one of "none", "mid", "min", "max") + * This parameter defines how the picture is aligned to its viewport when image element width differs from image width. + */ + alignX: string; + + /** + * AlignY value, part of preserveAspectRatio (one of "none", "mid", "min", "max") + * This parameter defines how the picture is aligned to its viewport when image element height differs from image height. + */ + alignY: string; + + /** + * meetOrSlice value, part of preserveAspectRatio (one of "meet", "slice"). + * if meet the image is always fully visibile, if slice the viewport is always filled with image. + * @see http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute + */ + meetOrSlice: string; + + /** + * Image filter array + */ + filters: IBaseFilter[]; + } + interface IImage extends IObject, IImageOptions { + initialize(element?: string|HTMLImageElement, options?: IImageOptions); + /** + * Applies filters assigned to this image (from "filters" array) + * @param {Function} callback Callback is invoked when all filters have been applied and new image is generated + */ + applyFilters(callback: Function); + /** + * Returns a clone of an instance + * @param {Function} callback Callback is invoked with a clone as a first argument + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + clone(callback?: Function, propertiesToInclude?: any[]): IObject; + /** + * Returns complexity of an instance + * @return {Number} complexity of this instance + */ + complexity(): number; + /** + * Returns image element which this instance if based on + * @return {HTMLImageElement} Image element + */ + getElement(): HTMLImageElement; + /** + * Returns original size of an image + * @return {Object} Object with "width" and "height" properties + */ + getOriginalSize(): { width: number; height: number; }; + /** + * Returns source of an image + * @return {String} Source of an image + */ + getSrc(): string; + render(ctx: CanvasRenderingContext2D, noTransform: boolean); + + /** + * Sets image element for this instance to a specified one. + * If filters defined they are applied to new image. + * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area. + * @param {HTMLImageElement} element + * @param {Function} [callback] Callback is invoked when all filters have been applied and new image is generated + * @param {Object} [options] Options object + */ + setElement(element: HTMLImageElement, callback: Function, options: IImageOptions): IImage; + /** + * Sets crossOrigin value (on an instance and corresponding image element) + */ + setCrossOrigin(value: string): IImage; + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} Object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns string representation of an instance + * @return {String} String representation of an instance + */ + toString(): string; + /** + * Returns SVG representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + /** + * Sets source of an image + * @param {String} src Source string (URL) + * @param {Function} [callback] Callback is invoked when image has been loaded (and all filters have been applied) + * @param {Object} [options] Options object + */ + setSrc(src: string, callback: Function, options: IImageOptions): IImage; + } + interface IImageStatic { + /** + * Constructor + * @param {HTMLImageElement | String} element Image element + * @param {Object} [options] Options object + */ + new (element: HTMLImageElement, objObjects: IObjectOptions): IImage; + /** + * Creates an instance of fabric.Image from an URL string + * @param {String} url URL to create an image from + * @param {Function} [callback] Callback to invoke when image is created (newly created image is passed as a first argument) + * @param {Object} [imgOptions] Options object + */ + fromURL(url: string, callback?: (image: IImage) => any, objObjects?: IObjectOptions): IImage; + /** + * Creates an instance of fabric.Image from its object representation + * @static + * @param {Object} object Object to create an instance from + * @param {Function} [callback] Callback to invoke when an image instance is created + */ + fromObject(object: any, callback: (image: IImage) => {}): void; + /** + * Returns Image instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Function} callback Callback to execute when fabric.Image object is created + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, callback: Function, options?: IImageOptions): void; + prototype: any; + /** + * Default CSS class name for canvas + */ + CSS_CANVAS: string; + + filters: IAllFilters + } + + interface ILineOptions extends IObjectOptions { + /** + * x value or first line edge + */ + x1: number; + /** + * x value or second line edge + */ + x2: number; + /** + * y value or first line edge + */ + y1: number; + /** + * y value or second line edge + */ + y2: number; + } + interface ILine extends IObject, ILineOptions { + /** + * Returns complexity of an instance + * @return {Number} complexity + */ + complexity(): number; + initialize(points?: number[], options?: ILineOptions): ILine; + /** + * Returns object representation of an instance + * @methd toObject + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude: any[]): any; + /** + * Returns SVG representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface ILineStatic { + ATTRIBUTE_NAMES: string[]; + /** + * Returns fabric.Line instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, options?: ILineOptions): ILine; + /** + * Returns fabric.Line instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ILine; + prototype: any; + /** + * Constructor + * @param {Array} [points] Array of points + * @param {Object} [options] Options object + */ + new (points?: number[], objObjects?: IObjectOptions): ILine; + } + + interface IObjectOptions { + /** + * Type of an object (rect, circle, path, etc.). + * Note that this property is meant to be read-only and not meant to be modified. + * If you modify, certain parts of Fabric (such as JSON loading) won't work correctly. + */ + type?: string; + + /** + * Horizontal origin of transformation of an object (one of "left", "right", "center") + */ + originX?: string; + + /** + * Vertical origin of transformation of an object (one of "top", "bottom", "center") + */ + originY?: string; + + /** + * Top position of an object. Note that by default it's relative to object center. You can change this by setting originY={top/center/bottom} + */ + top?: number; + + /** + * Left position of an object. Note that by default it's relative to object center. You can change this by setting originX={left/center/right} + */ + left?: number; + + /** + * Object width + */ + width?: number; + + /** + * Object height + */ + height?: number; + + /** + * Object scale factor (horizontal) + */ + scaleX?: number; + + /** + * Object scale factor (vertical) + */ + scaleY?: number; + + /** + * When true, an object is rendered as flipped horizontally + */ + flipX?: boolean; + + /** + * When true, an object is rendered as flipped vertically + */ + flipY?: boolean; + + /** + * Opacity of an object + */ + opacity?: number; + + /** + * Angle of rotation of an object (in degrees) + */ + angle?: number; + + /** + * Size of object's controlling corners (in pixels) + */ + cornerSize?: number; + + /** + * When true, object's controlling corners are rendered as transparent inside (i.e. stroke instead of fill) + */ + transparentCorners?: boolean; + + /** + * Default cursor value used when hovering over this object on canvas + */ + hoverCursor?: string; + + /** + * Padding between object and its controlling borders (in pixels) + */ + padding?: number; + + /** + * Color of controlling borders of an object (when it's active) + */ + borderColor?: string; + + /** + * Color of controlling corners of an object (when it's active) + */ + cornerColor?: string; + + /** + * When true, this object will use center point as the origin of transformation + * when being scaled via the controls. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredScaling?: boolean; + + /** + * When true, this object will use center point as the origin of transformation + * when being rotated via the controls. + * Backwards incompatibility note: This property replaces "centerTransform" (Boolean). + */ + centeredRotation?: boolean; + + /** + * Color of object's fill + */ + fill?: string; + + /** + * Fill rule used to fill an object + * accepted values are nonzero, evenodd + * Backwards incompatibility note: This property was used for setting globalCompositeOperation until v1.4.12, use `globalCompositeOperation` instead + */ + fillRule?: string; + + /** + * Composite rule used for canvas globalCompositeOperation + */ + globalCompositeOperation?: string; + + /** + * Background color of an object. Only works with text objects at the moment. + */ + backgroundColor?: string; + + /** + * When defined, an object is rendered via stroke and this property specifies its color + */ + stroke?: string; + + /** + * Width of a stroke used to render this object + */ + strokeWidth?: number; + + /** + * Array specifying dash pattern of an object's stroke (stroke must be defined) + */ + strokeDashArray?: any[]; + + /** + * Line endings style of an object's stroke (one of "butt", "round", "square") + */ + strokeLineCap?: string; + + /** + * Corner style of an object's stroke (one of "bevil", "round", "miter") + */ + strokeLineJoin?: string; + + /** + * Maximum miter length (used for strokeLineJoin = "miter") of an object's stroke + */ + strokeMiterLimit?: number; + + /** + * Shadow object representing shadow of this shape + */ + shadow?: IShadow|string; + + /** + * Opacity of object's controlling borders when object is active and moving + */ + borderOpacityWhenMoving?: number; + + /** + * Scale factor of object's controlling borders + */ + borderScaleFactor?: number; + + /** + * Transform matrix (similar to SVG's transform matrix) + */ + transformMatrix?: any[]; + + /** + * Minimum allowed scale value of an object + */ + minScaleLimit?: number; + + /** + * When set to `false`, an object can not be selected for modification (using either point-click-based or group-based selection). + * But events still fire on it. + */ + selectable?: boolean; + + /** + * When set to `false`, an object can not be a target of events. All events propagate through it. Introduced in v1.3.4 + */ + evented?: boolean; + + /** + * When set to `false`, an object is not rendered on canvas + */ + visible?: boolean; + + /** + * When set to `false`, object's controls are not displayed and can not be used to manipulate object + */ + hasControls?: boolean; + + /** + * When set to `false`, object's controlling borders are not rendered + */ + hasBorders?: boolean; + + /** + * When set to `false`, object's controlling rotating point will not be visible or selectable + */ + hasRotatingPoint?: boolean; + + /** + * Offset for object's controlling rotating point (when enabled via `hasRotatingPoint`) + */ + rotatingPointOffset?: number; + + /** + * When set to `true`, objects are "found" on canvas on per-pixel basis rather than according to bounding box + */ + perPixelTargetFind?: boolean; + + /** + * When `false`, default object's values are not included in its serialization + */ + includeDefaultValues?: boolean; + + /** + * Function that determines clipping of an object (context is passed as a first argument) + * Note that context origin is at the object's center point (not left/top corner) + * @type Function + */ + clipTo?: Function; + + /** + * When `true`, object horizontal movement is locked + */ + lockMovementX?: boolean; + + /** + * When `true`, object vertical movement is locked + */ + lockMovementY?: boolean; + + /** + * When `true`, object rotation is locked + */ + lockRotation?: boolean; + + /** + * When `true`, object horizontal scaling is locked + */ + lockScalingX?: boolean; + + /** + * When `true`, object vertical scaling is locked + */ + lockScalingY?: boolean; + + /** + * When `true`, object non-uniform scaling is locked + */ + lockUniScaling?: boolean; + + /** + * When `true`, object cannot be flipped by scaling into negative values + */ + lockScalingFlip?: boolean; + + /** + * Not used by fabric, just for convenience + */ + name?: string; + + /** + * Not used by fabric, just for convenience + */ + data?: any; + } + interface IObject extends IObservable, IObjectOptions, IObjectAnimation { + getCurrentWidth(): number; + getCurrentHeight(): number; + + getAngle(): number; + setAngle(value: number): IObject; + + getBorderColor(): string; + setBorderColor(value: string): IObject; + + getBorderScaleFactor(): number; + + getCornersize(): number; + setCornersize(value: number): IObject; + + getFill(): string; + setFill(value: string): IObject; + + getFillRule(): string; + setFillRule(value: string): IObject; + + getFlipX(): boolean; + setFlipX(value: boolean): IObject; + + getFlipY(): boolean; + setFlipY(value: boolean): IObject; + + getHeight(): number; + setHeight(value: number): IObject; + + getLeft(): number; + setLeft(value: number): IObject; + + getOpacity(): number; + setOpacity(value: number): IObject; + + overlayFill: string; + getOverlayFill(): string; + setOverlayFill(value: string): IObject; + + getScaleX(): number; + setScaleX(value: number): IObject; + + getScaleY(): number; + setScaleY(value: number): IObject; + + setShadow(options: any): IObject; + getShadow(): IObject; + + stateProperties: any[]; + getTop(): number; + setTop(value: number): IObject; + + getWidth(): number; + setWidth(value: number): IObject; + + /* * Sets object's properties from options + * @param {Object} [options] Options object + */ + setOptions(options: any): void; + + /** + * Transforms context when rendering an object + * @param {CanvasRenderingContext2D} ctx Context + * @param {Boolean} fromLeft When true, context is transformed to object's top/left corner. This is used when rendering text on Node + */ + transform(ctx: CanvasRenderingContext2D, fromLeft: boolean): void; + + /** + * Returns an object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: any[]): any; + + /** + * Returns (dataless) object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toDatalessObject(propertiesToInclude?: any[]): any; + + /** + * Returns a string representation of an instance + */ + toString(): string; + + /** + * Basic getter + * @param {String} property Property name + */ + get(property: string): any; + + /** + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param {String} key Property name + * @param {Object|Function} value Property value (if function, the value is passed into it and its return value is used as a new one) + */ + set(key: string, value: any|Function): IObject; + /** + * Sets property to a given value. + * When changing position/dimension -related properties (left, top, scale, angle, etc.) `set` does not update position of object's borders/controls. + * If you need to update those, call `setCoords()`. + * @param Object key Property object, iterate over the object properties + */ + set(key: any): IObject; + + /** + * Toggles specified property from `true` to `false` or from `false` to `true` + * @param {String} property Property to toggle + */ + toggle(property: string): IObject; + + /** + * Sets sourcePath of an object + * @param {String} value Value to set sourcePath to + */ + setSourcePath(value: string): IObject; + + /** + * Retrieves viewportTransform from Object's canvas if possible + */ + getViewportTransform(): boolean; + + /** + * Renders an object on a specified context + * @param {CanvasRenderingContext2D} ctx Context to render on + * @param {Boolean} [noTransform] When true, context is not transformed + */ + render(ctx: CanvasRenderingContext2D, noTransform?: boolean): void; + + /** + * Clones an instance + * @param {Function} callback Callback is invoked with a clone as a first argument + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + clone(callback: Function, propertiesToInclude?: any[]): IObject; + + /** + * Creates an instance of fabric.Image out of an object + * @param {Function} callback callback, invoked with an instance as a first argument + */ + cloneAsImage(callback: (image: IImage) => any): IObject; + + /** + * Converts an object into a data-url-like string + * @param options Options object + */ + toDataURL(options: IDataURLOptions): string; + + /** + * Returns true if specified type is identical to the type of an instance + * @param {String} type Type to check against + */ + isType(type: string): boolean; + + /** + * Returns complexity of an instance + */ + complexity(): number; + + /** + * Returns a JSON representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toJSON(propertiesToInclude?: any[]): any; + + /** + * Sets gradient (fill or stroke) of an object + * Backwards incompatibility note: This method was named "setGradientFill" until v1.1.0 + * @param {String} property Property name 'stroke' or 'fill' + * @param {Object} [options] Options object + */ + setGradient(property: string, options: IGradientOptions): IObject; + /** + * Sets pattern fill of an object + * @param {Object} options Options object + */ + setPatternFill(options: IFillOptions): IObject; + + /** + * Sets shadow of an object + * @param {String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") + */ + setShadow(options?: string): IObject; + /** + * Sets shadow of an object + * @param [options] Options object + */ + setShadow(options: IShadow): IObject; + + /** + * Sets "color" of an instance (alias of `set('fill', …)`) + * @param {String} color Color value + */ + setColor(color: string): IObject; + + /** + * Sets "angle" of an instance + * @param {Number} angle Angle value + */ + setAngle(angle: number): IObject; + + /** + * Sets "angle" of an instance + * @param {Number} angle Angle value + */ + rotate(angle: number): IObject; + + /** + * Centers object horizontally on canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + */ + centerH(): void; + + /** + * Centers object vertically on canvas to which it was added last. + * You might need to call `setCoords` on an object after centering, to update controls area. + */ + centerV(): void; + + /** + * Centers object vertically and horizontally on canvas to which is was added last + * You might need to call `setCoords` on an object after centering, to update controls area. + */ + center(): void; + + /** + * Removes object from canvas to which it was added last + */ + remove(): IObject; + + /** + * Returns coordinates of a pointer relative to an object + * @param {Event} e Event to operate upon + * @param {Object} [pointer] Pointer to operate upon (instead of event) + */ + getLocalPointer(e: Event, pointer: any): any; + + /** + * Sets object's properties from options + * @param {Object} [options] Options object + */ + setOptions(options: any); + /** + * Sets sourcePath of an object + * @param {String} value Value to set sourcePath to + */ + setSourcePath(value: string): IObject; + // functions from object svg export mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Returns styles-string for svg-export + */ + getSvgStyles(): string; + /** + * Returns transform-string for svg-export + */ + getSvgTransform(): string; + /** + * Returns transform-string for svg-export from the transform matrix of single elements + */ + getSvgTransformMatrix(): string; + + // functions from stateful mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Returns true if object state (one of its state properties) was changed + */ + hasStateChanged(): boolean; + /** + * Saves state of an object + * @param {Object} [options] Object with additional `stateProperties` array to include when saving state + * @return {fabric.Object} thisArg + */ + saveState(options?: { stateProperties: any[] }): IObject; + /** + * Setups state of an object + */ + setupState(): IObject; + // functions from object straightening mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Straightens an object (rotating it from current angle to one of 0, 90, 180, 270, etc. depending on which is closer) + */ + straighten(): IObject; + /** + * Same as straighten but with animation + * @param {Object} callbacks Object with callback functions + * @param {Function} [callbacks.onComplete] Invoked on completion + * @param {Function} [callbacks.onChange] Invoked on every step of animation + */ + fxStraighten(callbacks: { onComplete?: Function; onChange: Function }): IObject; + + // functions from object stacking mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Moves an object up in stack of drawn objects + * @param {Boolean} [intersecting] If `true`, send object in front of next upper intersecting object + */ + bringForward(intersecting?: boolean): IObject; + /** + * Moves an object to the top of the stack of drawn objects + */ + bringToFront(): IObject; + /** + * Moves an object down in stack of drawn objects + * @param {Boolean} [intersecting] If `true`, send object behind next lower intersecting object + */ + sendBackwards(intersecting?: boolean): IObject; + /** + * Moves an object to the bottom of the stack of drawn objects + */ + sendToBack(): IObject; + /** + * Moves an object to specified level in stack of drawn objects + * @param {Number} index New position of object + */ + moveTo(index: number): IObject; + + // functions from object origin mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /** + * Translates the coordinates from origin to center coordinates (based on the object's dimensions) + * @param {fabric.Point} point The point which corresponds to the originX and originY params + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + translateToCenterPoint(point: IPoint, originX: string, originY: string): IPoint; + + /** + * Translates the coordinates from center to origin coordinates (based on the object's dimensions) + * @param {fabric.Point} center The point which corresponds to center of the object + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + translateToOriginPoint(center: IPoint, originX: string, originY: string): IPoint; + /** + * Returns the real center coordinates of the object + */ + getCenterPoint(): IPoint; + + /** + * Returns the coordinates of the object as if it has a different origin + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + getPointByOrigin(): IPoint; + + /** + * Returns the point in local coordinates + * @param {fabric.Point} point The point relative to the global coordinate system + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + */ + toLocalPoint(point: IPoint, originX: string, originY: string): IPoint; + + /** + * Sets the position of the object taking into consideration the object's origin + * @param {fabric.Point} pos The new position of the object + * @param {String} originX Horizontal origin: 'left', 'center' or 'right' + * @param {String} originY Vertical origin: 'top', 'center' or 'bottom' + * @return {void} + */ + setPositionByOrigin(pos: IPoint, originX: string, originY: string): void; + + /** + * @param {String} to One of 'left', 'center', 'right' + */ + adjustPosition(to: string): void; + + // functions from interactivity mixin + // ----------------------------------------------------------------------------------------------------------------------------------- + /**- + * Draws borders of an object's bounding box. + * Requires public properties: width, height + * Requires public options: padding, borderColor + * @param {CanvasRenderingContext2D} ctx Context to draw on + */ + drawBorders(context: CanvasRenderingContext2D): IObject; + + /** + * Draws corners of an object's bounding box. + * Requires public properties: width, height + * Requires public options: cornerSize, padding + * @param {CanvasRenderingContext2D} ctx Context to draw on + */ + drawCorners(context: CanvasRenderingContext2D): IObject; + + /** + * Returns true if the specified control is visible, false otherwise. + * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. + */ + isControlVisible(controlName: string): boolean; + /** + * Sets the visibility of the specified control. + * @param {String} controlName The name of the control. Possible values are 'tl', 'tr', 'br', 'bl', 'ml', 'mt', 'mr', 'mb', 'mtr'. + * @param {Boolean} visible true to set the specified control visible, false otherwise + */ + setControlVisible(controlName: string, visible: boolean): IObject; + + /** + * Sets the visibility state of object controls. + * @param {Object} [options] Options object + */ + setControlsVisibility(options?: { + bl?: boolean; + br?: boolean; + mb?: boolean; + ml?: boolean; + mr?: boolean; + mt?: boolean; + tl?: boolean; + tr?: boolean; + mtr?: boolean; }): IObject; + + // functions from geometry mixin + // ------------------------------------------------------------------------------------------------------------------------------- + /** + * Sets corner position coordinates based on current angle, width and height + * See https://github.com/kangax/fabric.js/wiki/When-to-call-setCoords + */ + setCoords(): IObject; + /** + * Returns coordinates of object's bounding rectangle (left, top, width, height) + * @return {Object} Object with left, top, width, height properties + */ + getBoundingRect(): { left: number; top: number; width: number; height: number }; + /** + * Checks if object is fully contained within area of another object + * @param {Object} other Object to test + */ + isContainedWithinObject(other: IObject): boolean; + /** + * Checks if object is fully contained within area formed by 2 points + * @param {Object} pointTL top-left point of area + * @param {Object} pointBR bottom-right point of area + */ + isContainedWithinRect(pointTL: any, pointBR: any): boolean; + /** + * Checks if point is inside the object + * @param {fabric.Point} point Point to check against + */ + containsPoint(point: IPoint): boolean; + /** + * Scales an object (equally by x and y) + * @param {Number} value Scale factor + * @return {fabric.Object} thisArg + */ + scale(value: number): IObject; + /** + * Scales an object to a given height, with respect to bounding box (scaling by x/y equally) + * @param {Number} value New height value + */ + scaleToHeight(value: number): IObject; + /** + * Scales an object to a given width, with respect to bounding box (scaling by x/y equally) + * @param {Number} value New width value + */ + scaleToWidth(value: number): IObject; + /** + * Checks if object intersects with another object + * @param {Object} other Object to test + */ + intersectsWithObject(other: IObject): boolean; + /** + * Checks if object intersects with an area formed by 2 points + * @param {Object} pointTL top-left point of area + * @param {Object} pointBR bottom-right point of area + */ + intersectsWithRect(pointTL: any, pointBR: any): boolean; + } + interface IObjectStatic { + prototype: any; + } + + interface IPathOptions extends IObjectOptions { + /** + * Array of path points + */ + path?: any[]; + + /** + * Minimum X from points values, necessary to offset points + */ + minX?: number; + + /** + * Minimum Y from points values, necessary to offset points + */ + minY?: number; + } + interface IPath extends IObject, IPathOptions { + initialize(path?: any[], options?: IPathOptions): IPath; + + /** + * Returns number representation of an instance complexity + * @return {Number} complexity of this instance + */ + complexity(): number; + + /** + * Renders path on a specified context + * @param {CanvasRenderingContext2D} ctx context to render path on + * @param {Boolean} [noTransform] When true, context is not transformed + */ + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; + /** + * Returns dataless object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toDatalessObject(propertiesToInclude?: any[]): any; + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns string representation of an instance + * @return {String} string representation of an instance + */ + toString(): string; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface IPathStatic { + /** + * Creates an instance of fabric.Path from an SVG element + * @param {SVGElement} element to parse + * @param {Function} callback Callback to invoke when an fabric.Path instance is created + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, callback: (path: IPath) => any, options?: IPathOptions): void; + /** + * Creates an instance of fabric.Path from an object + * @param {Object} object + * @param {Function} callback Callback to invoke when an fabric.Path instance is created + */ + fromObject(object: any, callback: (path: IPath) => any): void; + /** + * Constructor + * @param {Array|String} path Path data (sequence of coordinates and corresponding "command" tokens) + * @param {Object} [options] Options object + */ + new (path?: string|any[], options?: IPathOptions): IPath; + } + + interface IPathGroup extends IObject { + initialize(paths: IPath[], options?: IObjectOptions); + /** + * Returns number representation of object's complexity + * @return {Number} complexity + */ + complexity(): number; + /** + * Returns true if all paths in this group are of same color + * @return {Boolean} true if all paths are of the same color (`fill`) + */ + isSameColor(): boolean; + /** + * Renders this group on a specified context + * @param {CanvasRenderingContext2D} ctx Context to render this instance on + */ + render(ctx: CanvasRenderingContext2D); + /** + * Returns dataless object representation of this path group + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} dataless object representation of an instance + */ + toDatalessObject(propertiesToInclude?: any[]): any; + /** + * Returns object representation of this path group + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns a string representation of this path group + * @return {String} string representation of an object + */ + toString(): string; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + /** + * Returns all paths in this path group + * @return {Array} array of path objects included in this path group + */ + getObjects(): IPath[]; + } + interface IPathGroupStatic { + fromObject(object: any): IPathGroup; + /** + * Constructor + * @param {Array} paths + * @param {Object} [options] Options object + */ + new (paths: IPath[], options?: IObjectOptions): IPathGroup; + /** + * Creates fabric.PathGroup instance from an object representation + * @static + * @memberOf fabric.PathGroup + * @param {Object} object Object to create an instance from + * @param {Function} callback Callback to invoke when an fabric.PathGroup instance is created + */ + fromObject(object: any, callback: (group: IPathGroup) => any): void; + prototype: any; + } + + interface IPolygonOptions extends IObjectOptions { + /** + * Points array + */ + points?: IPoint[]; + + /** + * Minimum X from points values, necessary to offset points + */ + minX?: number; + + /** + * Minimum Y from points values, necessary to offset points + */ + minY?: number; + } + interface IPolygon extends IObject, IPolygonOptions { + /** + * Returns complexity of an instance + * @return {Number} complexity of this instance + */ + complexity(): number; + + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface IPolygonStatic { + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) + */ + ATTRIBUTE_NAMES: string[]; + + /** + * Returns Polygon instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, options?: IPolygonOptions): IPolygon; + /** + * Returns fabric.Polygon instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IPolygon; + /** + * Constructor + * @param {Array} points Array of points + * @param {Object} [options] Options object + */ + new (points: { x: number; y: number }[], options?: IObjectOptions, skipOffset?: boolean): IPolygon; + prototype: any; + } + + interface IPolylineOptions extends IObjectOptions { + /** + * Points array + */ + points?: IPoint[]; + + /** + * Minimum X from points values, necessary to offset points + */ + minX?: number; + + /** + * Minimum Y from points values, necessary to offset points + */ + minY?: number; + } + interface IPolyline extends IObject, IPolylineOptions { + initialize(points: IPoint[], options?: IPolylineOptions); + /** + * Returns complexity of an instance + * @return {Number} complexity of this instance + */ + complexity(): number; + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} Object representation of an instance + */ + toObject(propertiesToInclude?: any[]): any; + /** + * Returns SVG representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface IPolylineStatic { + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Polygon.fromElement`) + */ + ATTRIBUTE_NAMES: string[]; + + /** + * Returns Polyline instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, options?: IPolylineOptions): IPolyline; + /** + * Returns fabric.Polyline instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IPolyline; + /** + * Constructor + * @param {Array} points Array of points (where each point is an object with x and y) + * @param {Object} [options] Options object + * @param {Boolean} [skipOffset] Whether points offsetting should be skipped + */ + new (points: { x: number; y: number }[], options?: IPolylineOptions): IPolyline; + prototype: any; + } + + interface IRectOptions extends IObjectOptions { + x?: number; + y?: number; + /** + * Horizontal border radius + */ + rx?: number; + + /** + * Vertical border radius + */ + ry?: number; + + } + interface IRect extends IObject, IRectOptions { + initialize(points?: number[], options?: any): IRect; + /** + * Returns complexity of an instance + * @return {Number} complexity + */ + complexity(): number; + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude: any[]): any; + /** + * Returns svg representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface IRectStatic { + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Rect.fromElement`) + */ + ATTRIBUTE_NAMES: string[]; + /** + * Returns Rect instance from an SVG element + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, options?: IRectOptions): IRect; + /** + * Returns Rect instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IRect; + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: IRectOptions): IRect; + prototype: any; + } + + interface ITextOptions extends IObjectOptions { + /** + * Font size (in pixels) + */ + fontSize?: number; + /** + * Font weight (e.g. bold, normal, 400, 600, 800) + */ + fontWeight?: number|string; + /** + * Font family + */ + fontFamily?: string; + /** + * Text decoration Possible values?: "", "underline", "overline" or "line-through". + */ + textDecoration?: string; + /** + * Text alignment. Possible values?: "left", "center", or "right". + */ + textAlign?: string; + /** + * Font style . Possible values?: "", "normal", "italic" or "oblique". + */ + fontStyle?: string; + /** + * Line height + */ + lineHeight?: number; + /** + * When defined, an object is rendered via stroke and this property specifies its color. + * Backwards incompatibility note?: This property was named "strokeStyle" until v1.1.6 + */ + stroke?: string; + /** + * Shadow object representing shadow of this shape. + * Backwards incompatibility note?: This property was named "textShadow" (String) until v1.2.11 + */ + shadow?: IShadow|string; + /** + * Background color of text lines + */ + textBackgroundColor?: string; + + path?: string; + useNative?: Boolean; + text?: string; + } + interface IText extends IObject, ITextOptions { + /** + * Returns complexity of an instance + */ + complexity(): number; + /** + * Returns string representation of an instance + */ + toString(): string; + /** + * Renders text instance on a specified context + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + render(ctx: CanvasRenderingContext2D, noTransform: boolean); + /** + * Returns object representation of an instance + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + */ + toObject(propertiesToInclude?: any[]): IObject; + /** + * Returns SVG representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + */ + toSVG(reviver?: Function): string; + /** + * Retrieves object's fontSize + */ + getFontSize(): number; + /** + * Sets object's fontSize + * @param {Number} fontSize Font size (in pixels) + */ + setFontSize(fontSize: number): IText; + /** + * Retrieves object's fontWeight + */ + getFontWeight(): number|string; + /** + * Sets object's fontWeight + * @param {(Number|String)} fontWeight Font weight + */ + setFontWeight(fontWeight: string|number): IText; + /** + * Retrieves object's fontFamily + */ + getFontFamily(): string; + /** + * Sets object's fontFamily + * @param {String} fontFamily Font family + */ + setFontFamily(fontFamily: string): IText; + /** + * Retrieves object's text + */ + getText(): string; + /** + * Sets object's text + * @param {String} text Text + */ + setText(text: string): IText; + /** + * Retrieves object's textDecoration + */ + getTextDecoration(): string; + /** + * Sets object's textDecoration + * @param {String} textDecoration Text decoration + */ + setTextDecoration(textDecoration: string): IText; + /** + * Retrieves object's fontStyle + */ + getFontStyle(): string; + /** + * Sets object's fontStyle + * @param {String} fontStyle Font style + */ + setFontStyle(fontStyle: string): IText; + /** + * Retrieves object's lineHeight + */ + getLineHeight(): number; + /** + * Sets object's lineHeight + * @param {Number} lineHeight Line height + */ + setLineHeight(lineHeight: number): IText; + /** + * Retrieves object's textAlign + */ + getTextAlign(): string; + /** + * Sets object's textAlign + * @param {String} textAlign Text alignment + */ + setTextAlign(textAlign: string): IText; + /** + * Retrieves object's textBackgroundColor + */ + getTextBackgroundColor(): string; + /** + * Sets object's textBackgroundColor + * @param {String} textBackgroundColor Text background color + */ + setTextBackgroundColor(textBackgroundColor: string): IText; + } + interface ITextStatic { + /** + * List of attribute names to account for when parsing SVG element (used by `fabric.Text.fromElement`) + */ + ATTRIBUTE_NAMES: string[]; + /** + * Default SVG font size + */ + DEFAULT_SVG_FONT_SIZE: number; + /** + * Constructor + * @param {String} text Text string + * @param {Object} [options] Options object + */ + new (text: string, options?: ITextOptions): IText; + + /** + * Returns fabric.Text instance from an SVG element (not yet implemented) + * @param {SVGElement} element Element to parse + * @param {Object} [options] Options object + */ + fromElement(element: SVGElement, options?: ITextOptions): IText; + /** + * Returns fabric.Text instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IText; + } + + interface IITextOptions extends IObjectOptions, ITextOptions { + /** + * Index where text selection starts (or where cursor is when there is no selection) + */ + selectionStart?: number; + + /** + * Index where text selection ends + */ + selectionEnd?: number; + + /** + * Color of text selection + */ + selectionColor?: string; + + /** + * Indicates whether text is in editing mode + */ + isEditing?: boolean; + + /** + * Indicates whether a text can be edited + */ + editable?: boolean; + + /** + * Border color of text object while it's in editing mode + */ + editingBorderColor?: string; + + /** + * Width of cursor (in px) + */ + cursorWidth?: number; + + /** + * Color of default cursor (when not overwritten by character style) + */ + cursorColor?: string; + + /** + * Delay between cursor blink (in ms) + */ + cursorDelay?: number; + + /** + * Duration of cursor fadein (in ms) + */ + cursorDuration?: number; + + /** + * Object containing character styles + * (where top-level properties corresponds to line number and 2nd-level properties -- to char number in a line) + */ + styles?: any; + + /** + * Indicates whether internal text char widths can be cached + */ + caching?: boolean; + } + interface IIText extends IObject, IText, IITextOptions { + /** + * Returns true if object has no styling + */ + isEmptyStyles(): boolean; + render(ctx: CanvasRenderingContext2D, noTransform: boolean); + /** + * Returns object representation of an instance + * @method toObject + * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output + * @return {Object} object representation of an instance + */ + toObject(propertiesToInclude?: any[]): IObject; + + setText(value: string): IText; + /** + * Sets selection start (left boundary of a selection) + * @param {Number} index Index to set selection start to + */ + setSelectionStart(index: number): void; + /** + * Sets selection end (right boundary of a selection) + * @param {Number} index Index to set selection end to + */ + setSelectionEnd(index: number): void; + /** + * Gets style of a current selection/cursor (at the start position) + * @param {Number} [startIndex] Start index to get styles at + * @param {Number} [endIndex] End index to get styles at + * @return {Object} styles Style object at a specified (or current) index + */ + getSelectionStyles(startIndex: number, endIndex: number): any; + /** + * Sets style of a current selection + * @param {Object} [styles] Styles object + * @return {fabric.IText} thisArg + * @chainable + */ + setSelectionStyles(styles: any): IText; + + /** + * Renders cursor or selection (depending on what exists) + */ + renderCursorOrSelection(): void; + + /** + * Returns 2d representation (lineIndex and charIndex) of cursor (or selection start) + * @param {Number} [selectionStart] Optional index. When not given, current selectionStart is used. + */ + get2DCursorLocation(selectionStart?: number): void; + /** + * Returns complete style of char at the current cursor + * @param {Number} lineIndex Line index + * @param {Number} charIndex Char index + * @return {Object} Character style + */ + getCurrentCharStyle(lineIndex: number, charIndex: number): any; + + /** + * Returns fontSize of char at the current cursor + * @param {Number} lineIndex Line index + * @param {Number} charIndex Char index + * @return {Number} Character font size + */ + getCurrentCharFontSize(lineIndex: number, charIndex: number): number; + + /** + * Returns color (fill) of char at the current cursor + * @param {Number} lineIndex Line index + * @param {Number} charIndex Char index + * @return {String} Character color (fill) + */ + getCurrentCharColor(lineIndex: number, charIndex: number): string; + /** + * Renders cursor + * @param {Object} boundaries + */ + renderCursor(boundaries: any): void; + + /** + * Renders text selection + * @param {Array} chars Array of characters + * @param {Object} boundaries Object with left/top/leftOffset/topOffset + */ + renderSelection(chars: string[], boundaries: any): void; + + // functions from itext behavior mixin + // ------------------------------------------------------------------------------------------------------------------------ + /** + * Initializes all the interactive behavior of IText + */ + initBehavior(): void; + + /** + * Initializes "selected" event handler + */ + initSelectedHandler(): void; + + /** + * Initializes "added" event handler + */ + initAddedHandler(): void; + + initRemovedHandler(): void; + + /** + * Initializes delayed cursor + */ + initDelayedCursor(restart: boolean): void; + + /** + * Aborts cursor animation and clears all timeouts + */ + abortCursorAnimation(): void; + + /** + * Selects entire text + */ + selectAll(): void; + + /** + * Returns selected text + */ + getSelectedText(): string; + + /** + * Find new selection index representing start of current word according to current selection index + * @param {Number} startFrom Surrent selection index + * @return {Number} New selection index + */ + findWordBoundaryLeft(startFrom: number): number; + + /** + * Find new selection index representing end of current word according to current selection index + * @param {Number} startFrom Current selection index + * @return {Number} New selection index + */ + findWordBoundaryRight(startFrom: number): number; + + /** + * Find new selection index representing start of current line according to current selection index + * @param {Number} startFrom Current selection index + */ + findLineBoundaryLeft(startFrom: number): number; + + /** + * Find new selection index representing end of current line according to current selection index + * @param {Number} startFrom Current selection index + */ + findLineBoundaryRight(startFrom: number): number; + + /** + * Returns number of newlines in selected text + */ + getNumNewLinesInSelectedText(): number; + + /** + * Finds index corresponding to beginning or end of a word + * @param {Number} selectionStart Index of a character + * @param {Number} direction: 1 or -1 + */ + searchWordBoundary(selectionStart: number, direction: number): number; + + /** + * Selects a word based on the index + * @param {Number} selectionStart Index of a character + */ + selectWord(selectionStart: number): void; + /** + * Selects a line based on the index + * @param {Number} selectionStart Index of a character + */ + selectLine(selectionStart: number): void; + + /** + * Enters editing state + */ + enterEditing(): IIText; + + /** + * Initializes "mousemove" event handler + */ + initMouseMoveHandler(): void; + /** + * Exits from editing state + * @return {fabric.IText} thisArg + * @chainable + */ + exitEditing(): IIText; + + /** + * Inserts a character where cursor is (replacing selection if one exists) + * @param {String} _chars Characters to insert + */ + insertChars(_chars: string, useCopiedStyle?: boolean): void; + /** + * Inserts new style object + * @param {Number} lineIndex Index of a line + * @param {Number} charIndex Index of a char + * @param {Boolean} isEndOfLine True if it's end of line + */ + insertNewlineStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; + + /** + * Inserts style object for a given line/char index + * @param {Number} lineIndex Index of a line + * @param {Number} charIndex Index of a char + * @param {Object} [style] Style object to insert, if given + */ + insertCharStyleObject(lineIndex: number, charIndex: number, isEndOfLine: boolean): void; + + /** + * Inserts style object(s) + * @param {String} _chars Characters at the location where style is inserted + * @param {Boolean} isEndOfLine True if it's end of line + * @param {Boolean} [useCopiedStyle] Style to insert + */ + insertStyleObjects(_chars: string, isEndOfLine: boolean, useCopiedStyle?: boolean): void; + + /** + * Shifts line styles up or down + * @param {Number} lineIndex Index of a line + * @param {Number} offset Can be -1 or +1 + */ + shiftLineStyles(lineIndex: number, offset: number): void; + + /** + * Removes style object + * @param {Boolean} isBeginningOfLine True if cursor is at the beginning of line + * @param {Number} [index] Optional index. When not given, current selectionStart is used. + */ + removeStyleObject(isBeginningOfLine: boolean, index?: number): void; + /** + * Inserts new line + */ + insertNewline(): void; + + } + interface IITextStatic extends ITextStatic { + /** + * Constructor + * @param {String} text Text string + * @param {Object} [options] Options object + */ + new (text: string, options?: IITextOptions): IIText; + /** + * Returns fabric.IText instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IIText; + } + + interface ITriangleOptions extends IObjectOptions { } + interface ITriangle extends IObject { + /** + * Returns complexity of an instance + * @return {Number} complexity of this instance + */ + + complexity(): number; + /** + * Returns SVG representation of an instance + * @param {Function} [reviver] Method for further parsing of svg representation. + * @return {String} svg representation of an instance + */ + toSVG(reviver?: Function): string; + } + interface ITriangleStatic { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: ITriangleOptions): ITriangle; + /** + * Returns Triangle instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ITriangle; + } + + //////////////////////////////////////////////////////////// + // Filters + //////////////////////////////////////////////////////////// + interface IAllFilters { + BaseFilter: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): IBaseFilter; + }; + Blend: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: { color?: string; mode?: string; alpha?: number; image?: IImage }): IBlendFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IBlendFilter + }; + Brightness: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.brightness=0] Value to brighten the image up (0..255) + */ + new (options?: { brightness: number }): IBrightnessFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IBrightnessFilter + }; + Convolute: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Boolean} [options.opaque=false] Opaque value (true/false) + * @param {Array} [options.matrix] Filter matrix + */ + new (options?: { opaque?: boolean; matrix?: number[] }): IConvoluteFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IConvoluteFilter + }; + GradientTransparency: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.threshold=100] Threshold value + */ + new (options?: { threshold?: number; }): IGradientTransparencyFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IGradientTransparencyFilter + }; + Grayscale: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): IGrayscaleFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IGrayscaleFilter + }; + Invert: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): IInvertFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IInvertFilter + }; + Mask: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {fabric.Image} [options.mask] Mask image object + * @param {Number} [options.channel=0] Rgb channel (0, 1, 2 or 3) + */ + new (options?: { mask?: IImage; channel: number; }): IMaskFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IMaskFilter + }; + Multiply: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.color=#000000] Color to multiply the image pixels with + */ + new (options?: { color: string; }): IMultiplyFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IMultiplyFilter + }; + Noise: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.noise=0] Noise value + */ + new (options?: { noise: number; }): INoiseFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): INoiseFilter + }; + Pixelate: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.blocksize=4] Blocksize for pixelate + */ + new (options?: { blocksize?: number; }): IPixelateFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IPixelateFilter + }; + RemoveWhite: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {Number} [options.threshold=30] Threshold value + * @param {Number} [options.distance=20] Distance value + */ + new (options?: { threshold?: number; distance?: number; }): IRemoveWhiteFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IRemoveWhiteFilter + }; + Resize: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): IResizeFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): IResizeFilter + }; + Sepia2: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): ISepia2Filter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ISepia2Filter + }; + Sepia: { + /** + * Constructor + * @param {Object} [options] Options object + */ + new (options?: any): ISepiaFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ISepiaFilter + }; + Tint: { + /** + * Constructor + * @param {Object} [options] Options object + * @param {String} [options.color=#000000] Color to tint the image with + * @param {Number} [options.opacity] Opacity value that controls the tint effect's transparency (0..1) + */ + new (options?: { color?: string; opacity?: number; }): ITintFilter; + /** + * Returns filter instance from an object representation + * @param {Object} object Object to create an instance from + */ + fromObject(object: any): ITintFilter + }; + } + interface IBaseFilter { + /** + * Sets filter's properties from options + * @param {Object} [options] Options object + */ + setOptions(options?: any): void; + /** + * Returns object representation of an instance + */ + toObject(): any; + /** + * Returns a JSON representation of an instance + */ + toJSON(): string; + } + interface IBlendFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IBrightnessFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IConvoluteFilter extends IBaseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IGradientTransparencyFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IGrayscaleFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IInvertFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IMaskFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IMultiplyFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface INoiseFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IPixelateFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IRemoveWhiteFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface IResizeFilter { + /** + * Resize type + */ + resizeType: string; + + /** + * Scale factor for resizing, x axis + */ + scaleX: number; + + /** + * Scale factor for resizing, y axis + */ + scaleY: number; + + /** + * LanczosLobes parameter for lanczos filter + */ + lanczosLobes: number; + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface ISepiaFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface ISepia2Filter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + interface ITintFilter { + /** + * Applies filter to canvas element + * @param {Object} canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; + } + + //////////////////////////////////////////////////////////// + // Brushes + //////////////////////////////////////////////////////////// + interface IBaseBrush { + /** + * Color of a brush + */ + color: string; + + /** + * Width of a brush + */ + width: number; + + /** + * Shadow object representing shadow of this shape. + * Backwards incompatibility note: This property replaces "shadowColor" (String), "shadowOffsetX" (Number), + * "shadowOffsetY" (Number) and "shadowBlur" (Number) since v1.2.12 + */ + shadow: IShadow|string; + /** + * Line endings style of a brush (one of "butt", "round", "square") + */ + strokeLineCap: string; + + /** + * Corner style of a brush (one of "bevil", "round", "miter") + */ + strokeLineJoin: string; + + /** + * Stroke Dash Array. + */ + strokeDashArray: any[]; + + /** + * Sets shadow of an object + * @param {Object|String} [options] Options object or string (e.g. "2px 2px 10px rgba(0,0,0,0.2)") + */ + setShadow(options: string|any): IBaseBrush; + + } + interface ICircleBrush extends IBaseBrush { + /** + * Width of a brush + */ + width: number; + /** + * Invoked inside on mouse down and mouse move + * @param {Object} pointer + */ + drawDot(pointer: any): void; + + /** + * @param {Object} pointer + * @return {fabric.Point} Just added pointer point + */ + addPoint(pointer: any): IPoint + } + interface ISprayBrush extends IBaseBrush { + /** + * Width of a brush + */ + width: number; + /** + * Density of a spray (number of dots per chunk) + */ + density: number; + + /** + * Width of spray dots + */ + dotWidth: number; + /** + * Width variance of spray dots + */ + dotWidthVariance: number; + + /** + * Whether opacity of a dot should be random + */ + randomOpacity: boolean; + /** + * Whether overlapping dots (rectangles) should be removed (for performance reasons) + */ + optimizeOverlapping: boolean; + /** + * @param {Object} pointer + */ + addSprayChunk(pointer: any): void + } + interface IPatternBrush extends IPencilBrush { + getPatternSrc(): HTMLCanvasElement; + + getPatternSrcFunction(): string; + + /** + * Creates "pattern" instance property + */ + getPattern(): any; + /** + * Creates path + */ + createPath(pathData: string): IPath; + } + interface IPencilBrush extends IBaseBrush { + /** + * Converts points to SVG path + * @param {Array} points Array of points + * @param {Number} minX + * @param {Number} minY + */ + convertPointsToSVGPath(points: { x: number; y: number }[], minX?: number, minY?: number): string[]; + + /** + * Creates fabric.Path object to add on canvas + * @param {String} pathData Path data + */ + createPath(pathData: string): IPath; + } + var BaseBrush: { + new (): IBaseBrush + }; + var CircleBrush: { + new (canvas: fabric.ICanvas): ICircle + }; + var SprayBrush: { + new (canvas: fabric.ICanvas): ISprayBrush + }; + var PencilBrush: { + new (canvas: fabric.ICanvas): IPencilBrush + }; + var PatternBrush: { + new (canvas: fabric.ICanvas): IPatternBrush + }; + /////////////////////////////////////////////////////////////////////////////// + // Fabric util Interface + ////////////////////////////////////////////////////////////////////////////// + interface IUtilAnimationOptions { + /** + * Starting value + */ + startValue?: number; + /** + * Ending value + */ + endValue?: number; + /** + * Value to modify the property by + */ + byValue: number; + /** + * Duration of change (in ms) + */ + duration?: number; + /** + * Callback; invoked on every value change + */ + onChange?: Function; + /** + * Callback; invoked when value change is completed + */ + onComplete?: Function; + /** + * Easing function + */ + easing?: Function; + } + interface IUtilAnimation { + /** + * Changes value from one to another within certain period of time, invoking callbacks as value is being changed. + * @param {Object} [options] Animation options + */ + animate(options?: IUtilAnimationOptions): void; + /** + * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + * In order to get a precise start time, `requestAnimFrame` should be called as an entry into the method + * @param {Function} callback Callback to invoke + */ + requestAnimFrame(callback: Function): void; + } + + interface IUtilAnimEase { + easeInBack(): Function; + easeInBounce(): Function; + easeInCirc(): Function; + easeInCubic(): Function; + easeInElastic(): Function; + easeInExpo(): Function; + easeInOutBack(): Function; + easeInOutBounce(): Function; + easeInOutCirc(): Function; + easeInOutCubic(): Function; + easeInOutElastic(): Function; + easeInOutExpo(): Function; + easeInOutQuad(): Function; + easeInOutQuart(): Function; + easeInOutQuint(): Function; + easeInOutSine(): Function; + easeInQuad(): Function; + easeInQuart(): Function; + easeInQuint(): Function; + easeInSine(): Function; + easeOutBack(): Function; + easeOutBounce(): Function; + easeOutCirc(): Function; + easeOutCubic(): Function; + easeOutElastic(): Function; + easeOutExpo(): Function; + easeOutQuad(): Function; + easeOutQuart(): Function; + easeOutQuint(): Function; + easeOutSine(): Function; + } + + interface IUtilArc { + /** + * Draws arc + * @param {CanvasRenderingContext2D} ctx + * @param {Number} fx + * @param {Number} fy + * @param {Array} coords + */ + drawArc(ctx: CanvasRenderingContext2D, fx: number, fy: number, coords: number[]): void; + /** + * Calculate bounding box of a elliptic-arc + * @param {Number} fx start point of arc + * @param {Number} fy + * @param {Number} rx horizontal radius + * @param {Number} ry vertical radius + * @param {Number} rot angle of horizontal axe + * @param {Number} large 1 or 0, whatever the arc is the big or the small on the 2 points + * @param {Number} sweep 1 or 0, 1 clockwise or counterclockwise direction + * @param {Number} tx end point of arc + * @param {Number} ty + */ + getBoundsOfArc(fx: number, fy: number, rx: number, ry: number, rot: number, large: number, sweep: number, tx: number, ty: number): IPoint[]; + /** + * Calculate bounding box of a beziercurve + * @param {Number} x0 starting point + * @param {Number} y0 + * @param {Number} x1 first control point + * @param {Number} y1 + * @param {Number} x2 secondo control point + * @param {Number} y2 + * @param {Number} x3 end of beizer + * @param {Number} y3 + */ + getBoundsOfCurve(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): IPoint[]; + + } + + interface IUtilDomEvent { + /** + * Cross-browser wrapper for getting event's coordinates + * @param {Event} event Event object + * @param {HTMLCanvasElement} upperCanvasEl <canvas> element on which object selection is drawn + */ + getPointer(event: Event, upperCanvasEl: HTMLCanvasElement): IPoint; + + /** + * Adds an event listener to an element + * @param {HTMLElement} element + * @param {String} eventName + * @param {Function} handler + */ + addListener(element: HTMLElement, eventName: string, handler: Function): void; + + /** + * Removes an event listener from an element + * @param {HTMLElement} element + * @param {String} eventName + * @param {Function} handler + */ + removeListener(element: HTMLElement, eventName: string, handler: Function): void; + } + + interface IUtilDomMisc { + /** + * Takes id and returns an element with that id (if one exists in a document) + * @param {String|HTMLElement} id + */ + getById(id: string|HTMLElement): HTMLElement; + /** + * Converts an array-like object (e.g. arguments or NodeList) to an array + * @param {Object} arrayLike + */ + toArray(arrayLike: any): any[]; + /** + * Creates specified element with specified attributes + * @memberOf fabric.util + * @param {String} tagName Type of an element to create + * @param {Object} [attributes] Attributes to set on an element + * @return {HTMLElement} Newly created element + */ + makeElement(tagName: string, attributes?: any): HTMLElement; + /** + * Adds class to an element + * @param {HTMLElement} element Element to add class to + * @param {String} className Class to add to an element + */ + addClass(element: HTMLElement, classname: string): void; + /** + * Wraps element with another element + * @param {HTMLElement} element Element to wrap + * @param {HTMLElement|String} wrapper Element to wrap with + * @param {Object} [attributes] Attributes to set on a wrapper + */ + wrapElement(element: HTMLElement, wrapper: HTMLElement|string, attributes?: any): HTMLElement; + /** + * Returns element scroll offsets + * @param {HTMLElement} element Element to operate on + * @param {HTMLElement} upperCanvasEl Upper canvas element + */ + getScrollLeftTop(element: HTMLElement, upperCanvasEl: HTMLElement): { left: number; right: number; }; + /** + * Returns offset for a given element + * @param {HTMLElement} element Element to get offset for + */ + getElementOffset(element: HTMLElement): { left: number; right: number; }; + /** + * Returns style attribute value of a given element + * @param {HTMLElement} element Element to get style attribute for + * @param {String} attr Style attribute to get for element + */ + getElementStyle(elment: HTMLElement, attr: string): string; + /** + * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading + * @memberOf fabric.util + * @param {String} url URL of a script to load + * @param {Function} callback Callback to execute when script is finished loading + */ + getScript(url: string, callback: Function): void; + /** + * Makes element unselectable + * @param {HTMLElement} element Element to make unselectable + */ + makeElementUnselectable(element: HTMLElement): HTMLElement; + /** + * Makes element selectable + * @param {HTMLElement} element Element to make selectable + */ + makeElementSelectable(element: HTMLElement): HTMLElement; + } + + interface IUtilDomRequest { + /** + * Cross-browser abstraction for sending XMLHttpRequest + * @param {String} url URL to send XMLHttpRequest to + * @param {Object} [options] Options object + * @param {String} [options.method="GET"] + * @param {Function} options.onComplete Callback to invoke when request is completed + */ + request(url: string, options?: { method?: string; onComplete: Function }): XMLHttpRequest; + } + + interface IUtilDomStyle { + /** + * Cross-browser wrapper for setting element's style + * @param {HTMLElement} element + * @param {Object} styles + */ + setStyle(element: HTMLElement, styles: any): HTMLElement; + } + + interface IUtilArray { + /** + * Invokes method on all items in a given array + * @param {Array} array Array to iterate over + * @param {String} method Name of a method to invoke + */ + invoke(array: any[], method: string): any[]; + /** + * Finds minimum value in array (not necessarily "first" one) + * @param {Array} array Array to iterate over + * @param {String} byProperty + */ + min(array: any[], byProperty: string): any; + /** + * Finds maximum value in array (not necessarily "first" one) + * @param {Array} array Array to iterate over + * @param {String} byProperty + */ + max(array: any[], byProperty: string): any; + } + + interface IUtilClass { + /** + * Helper for creation of "classes". + * @param {Function} [parent] optional "Class" to inherit from + * @param {Object} [properties] Properties shared by all instances of this class + * (be careful modifying objects defined here as this would affect all instances) + */ + createClass(parent: Function, properties?: any); + /** + * Helper for creation of "classes". + * @param {Object} [properties] Properties shared by all instances of this class + * (be careful modifying objects defined here as this would affect all instances) + */ + createClass(properties?: any); + + } + + interface IUtilObject { + /** + * Copies all enumerable properties of one object to another + * @param {Object} destination Where to copy to + * @param {Object} source Where to copy from + */ + extend(destination: any, source: any): any; + + /** + * Creates an empty object and copies all enumerable properties of another object to it + * @memberOf fabric.util.object + * @param {Object} object Object to clone + * @return {Object} + */ + clone(object: any): any + } + + interface IUtilString { + /** + * Camelizes a string + * @param {String} string String to camelize + */ + camelize(string: string): string; + + /** + * Capitalizes a string + * @param {String} string String to capitalize + * @param {Boolean} [firstLetterOnly] If true only first letter is capitalized + * and other letters stay untouched, if false first letter is capitalized + * and other letters are converted to lowercase. + */ + capitalize(string: string, firstLetterOnly: boolean): string; + + /** + * Escapes XML in a string + * @param {String} string String to escape + */ + escapeXml(string: string): string; + } + + interface IUtilMisc { + /** + * Removes value from an array. + * Presence of value (and its position in an array) is determined via `Array.prototype.indexOf` + * @param {Array} array + * @param {Any} value + */ + removeFromArray(array: any[], value: any): any[]; + + /** + * Returns random number between 2 specified ones. + * @param {Number} min lower limit + * @param {Number} max upper limit + */ + getRandomInt(min: number, max: number): number; + + /** + * Transforms degrees to radians. + * @param {Number} degrees value in degrees + */ + degreesToRadians(degrees: number): number; + + /** + * Transforms radians to degrees. + * @memberOf fabric.util + * @param {Number} radians value in radians + */ + radiansToDegrees(radians: number): number; + + /** + * Rotates `point` around `origin` with `radians` + * @param {fabric.Point} point The point to rotate + * @param {fabric.Point} origin The origin of the rotation + * @param {Number} radians The radians of the angle for the rotation + */ + rotatePoint(point: IPoint, origin: IPoint, radians: number): IPoint; + + /** + * Apply transform t to point p + * @param {fabric.Point} p The point to transform + * @param {Array} t The transform + * @param {Boolean} [ignoreOffset] Indicates that the offset should not be applied + */ + transformPoint(p: IPoint, t: any[], ignoreOffset?: boolean): IPoint; + + /** + * Invert transformation t + * @param {Array} t The transform + */ + invertTransform(t: any[]): any[]; + + /** + * A wrapper around Number#toFixed, which contrary to native method returns number, not string. + * @param {Number|String} number number to operate on + * @param {Number} fractionDigits number of fraction digits to "leave" + */ + toFixed(number: number, fractionDigits: number): number; + + /** + * Converts from attribute value to pixel value if applicable. + * Returns converted pixels or original value not converted. + * @param {Number|String} value number to operate on + */ + parseUnit(value: number|string, fontSize?: number): number|string; + + /** + * Function which always returns `false`. + */ + falseFunction(): boolean; + + /** + * Returns klass "Class" object of given namespace + * @param {String} type Type of object (eg. 'circle') + * @param {String} namespace Namespace to get klass "Class" object from + */ + getKlass(type: string, namespace: string): any; + + /** + * Returns object of given namespace + * @param {String} namespace Namespace string e.g. 'fabric.Image.filter' or 'fabric' + */ + resolveNamespace(namespace: string): any; + + /** + * Loads image element from given url and passes it to a callback + * @param {String} url URL representing an image + * @param {Function} callback Callback; invoked with loaded image + * @param {Any} [context] Context to invoke callback in + * @param {Object} [crossOrigin] crossOrigin value to set image element to + */ + loadImage(url: string, callback: (image: HTMLImageElement) => {}, context?: any, crossOrigin?: boolean): void; + + /** + * Creates corresponding fabric instances from their object representations + * @param {Array} objects Objects to enliven + * @param {Function} callback Callback to invoke when all objects are created + * @param {String} namespace Namespace to get klass "Class" object from + * @param {Function} reviver Method for further parsing of object elements, called after each fabric object created. + */ + enlivenObjects(objects: any[], callback: Function, namespace: string, reviver?: Function): void; + + /** + * Groups SVG elements (usually those retrieved from SVG document) + * @param {Array} elements SVG elements to group + * @param {Object} [options] Options object + */ + groupSVGElements(elements: any[], options?: any, path?: any): IPathGroup; + + /** + * Populates an object with properties of another object + * @param {Object} source Source object + * @param {Object} destination Destination object + * @param {Array} properties Propertie names to include + */ + populateWithProperties(source: any, destination: any, properties: any): void; + + /** + * Draws a dashed line between two points + * This method is used to draw dashed line around selection area. + * @param {CanvasRenderingContext2D} ctx context + * @param {Number} x start x coordinate + * @param {Number} y start y coordinate + * @param {Number} x2 end x coordinate + * @param {Number} y2 end y coordinate + * @param {Array} da dash array pattern + */ + drawDashedLine(ctx: CanvasRenderingContext2D, x: number, y: number, x2: number, y2: number, da: any[]): void; + + /** + * Creates canvas element and initializes it via excanvas if necessary + * @param {CanvasElement} [canvasEl] optional canvas element to initialize; + * when not given, element is created implicitly + */ + createCanvasElement(canvasEl?: HTMLCanvasElement): HTMLCanvasElement; + + /** + * Creates image element (works on client and node) + */ + createImage(): HTMLImageElement; + + /** + * Creates accessors (getXXX, setXXX) for a "class", based on "stateProperties" array + * @param {Object} klass "Class" to create accessors for + */ + createAccessors(klass: any): any; + + /** + * @param {fabric.Object} receiver Object implementing `clipTo` method + * @param {CanvasRenderingContext2D} ctx Context to clip + */ + clipContext(receiver: IObject, ctx: CanvasRenderingContext2D): void; + + /** + * Multiply matrix A by matrix B to nest transformations + * @param {Array} a First transformMatrix + * @param {Array} b Second transformMatrix + */ + multiplyTransformMatrices(a: any[], b: any[]): any[]; + + /** + * Returns string representation of function body + * @param {Function} fn Function to get body of + */ + getFunctionBody(fn: Function): string; + + /** + * Returns true if context has transparent pixel + * at specified location (taking tolerance into account) + * @param {CanvasRenderingContext2D} ctx context + * @param {Number} x x coordinate + * @param {Number} y y coordinate + * @param {Number} tolerance Tolerance + */ + isTransparent(ctx: CanvasRenderingContext2D, x: number, y: number, tolerance: number): boolean; + } + + interface IUtil extends IUtilAnimation, IUtilArc, IObservable, IUtilDomEvent, IUtilDomMisc, + IUtilDomRequest, IUtilDomStyle, IUtilClass, IUtilMisc { + ease: IUtilAnimEase; + array: IUtilArray; + object: IUtilObject; + string: IUtilString; + } } diff --git a/firebase/firebase.d.ts b/firebase/firebase.d.ts index fdb808ec4..f3c53b3ce 100644 --- a/firebase/firebase.d.ts +++ b/firebase/firebase.d.ts @@ -9,6 +9,11 @@ interface FirebaseAuthResult { } interface FirebaseDataSnapshot { + /** + * Returns true if this DataSnapshot contains any data. + * It is slightly more efficient than using snapshot.val() !== null. + */ + exists(): boolean; /** * Gets the JavaScript object representation of the DataSnapshot. */ @@ -108,6 +113,10 @@ interface FirebaseQuery { * Generates a new Query object ordered by key name. */ orderByKey(): FirebaseQuery; + /** + * Generates a new Query object ordered by child values. + */ + orderByValue(): FirebaseQuery; /** * Generates a new Query object ordered by priority. */ @@ -255,10 +264,14 @@ interface Firebase extends FirebaseQuery { * Creates a new user account using an email / password combination. */ createUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void; + /** + * Updates the email associated with an email / password user account. + */ + changeEmail(credentials: FirebaseChangeEmailCredentials, onComplete: (error: any) => void): void; /** * Change the password of an existing user using an email / password combination. */ - changePassword(credentials: { email: string; oldPassword: string; newPassword: string }, onComplete: (error: any) => void): void; + changePassword(credentials: FirebaseChangePasswordCredentials, onComplete: (error: any) => void): void; /** * Removes an existing user account using an email / password combination. */ @@ -266,7 +279,7 @@ interface Firebase extends FirebaseQuery { /** * Sends a password-reset email to the owner of the account, containing a token that may be used to authenticate and change the user password. */ - resetPassword(credentials: { email: string }, onComplete: (error: any) => void): void; + resetPassword(credentials: FirebaseResetPasswordCredentials, onComplete: (error: any) => void): void; onDisconnect(): FirebaseOnDisconnect; } interface FirebaseStatic { @@ -305,4 +318,20 @@ interface FirebaseAuthData { interface FirebaseCredentials { email: string; password: string; -} \ No newline at end of file +} + +interface FirebaseChangePasswordCredentials { + email: string; + oldPassword: string; + newPassword: string; +} + +interface FirebaseChangeEmailCredentials { + oldEmail: string; + newEmail: string; + password: string; +} + +interface FirebaseResetPasswordCredentials { + email: string; +} diff --git a/forge-di/forge-di-test.ts b/forge-di/forge-di-test.ts new file mode 100644 index 000000000..33bff4716 --- /dev/null +++ b/forge-di/forge-di-test.ts @@ -0,0 +1,52 @@ +/// + +import Forge = require('forge-di'); + +var forge = new Forge(); + +class Bar {} + +class Foo { + constructor(public bar: Bar) { + } +} + +forge.bind('foo').to.type(Foo); +forge.bind('bar').to.type(Bar); + +var foo: Foo = forge.get('foo'); +var barInst = foo.bar; + +// register functions +var createFoo = (bar: Bar) => new Foo(bar); +forge.bind('foo').to.function(createFoo); + +// Conditional bindings and resolution hints +class RedFoo {} +class BlueFoo {} + +forge.bind('foo').to.type(RedFoo).when('red'); +forge.bind('foo').to.type(BlueFoo).when((hint) => hint === 'blue'); + +// Lifecycles +forge.bind('foo').to.type(Foo).as.singleton(); +forge.bind('bar').to.type(Bar).as.transient(); + +// explicit arguments +var manuallyCreatedBar = new Bar(); +forge.bind('foo').to.type(Foo).with({bar: manuallyCreatedBar}); + +var bindingArgs: Forge.IBindingArguments = { + bar: manuallyCreatedBar +}; +forge.bind('foo').to.type(Foo).with(bindingArgs); + +// Ephemeral Bindings TODO +class DependsOnFoo { + constructor(public foo: Foo){} +} +var dependsOnFoo = forge.create(DependsOnFoo); + +// Unbinding and rebinding +forge.unbind('foo'); +forge.rebind('foo').to.type(Foo); \ No newline at end of file diff --git a/forge-di/forge-di.d.ts b/forge-di/forge-di.d.ts new file mode 100644 index 000000000..e28def38f --- /dev/null +++ b/forge-di/forge-di.d.ts @@ -0,0 +1,206 @@ +// Type definitions for forge-di v0.9.5 +// Project: https://github.com/nkohari/forge +// Definitions by: Adam Carr +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "forge-di" { + /** + * Implementation of the forge dependency injection manager. + */ + class Forge { + /** + * Creates a new instance + * @returns {Forge} a new instance. + */ + new(): Forge; + + /** + * The bindings mapped to this forge instance. + */ + bindings: Forge.IBindingMap; + + /** + * Creates a new binding. + * @param {string} name The binding name. + */ + bind(name: string): Forge.IBinding; + /** + * Unbinds then recreates a binding for this name. + * @param {string} name The binding name. + */ + rebind(name: string): Forge.IBinding; + /** + * Unbinds all bindings for this name. Returns the number of bindings removed. + * @param {string} name The binding name. + */ + unbind(name: string): number; + /** + * Get instance or instances of type registered under the provided name and optional hint. + * @param {string} name The binding name. + * @param {string} hint The binding hint. + * @param {...args} args Additional args. + */ + get(name: string, hint?: string, ...args: any[]): T; + /** + * Get a single instance of type registered under the provided name and optional hint. + * @param {string} name The binding name. + * @param {string} hint The binding hint. + * @param {...args} args Additional args. + */ + getOne(name: string, hint?: string, ...args: any[]): T; + /** + * Gets all instances of the type registered under the provided name. + * @param {string} name The binding name. + * @param {...args} args Additional args. + */ + getAll(name: string, ...args: any[]): T | T[]; + /** + * Creates an instance of the target type attempting to resolve any dependencies. + * @param {T} target The target type. + * @param {...args} args Additional args. + */ + create(target: T, ...args: any[]): T; + /** + * Get all bindings registered under a binding name and optional hint. + * @param {string} name The binding name. + * @param {string} hint The binding hint. + */ + getMatchingBindings(name: string, hint?: string): Forge.IBinding[]; + /** + * Returns a string that represents all bindings within this forge instance. + */ + inspect(): string; + + resolve(name: string, context?: Forge.IContext, hint?: string, all?: boolean, ...args: any[]): T | T[]; + resolveBindings(context: Forge.IContext, bindings: Forge.IBinding[], hint: string, args: any[], unwrap: boolean): Forge.IBinding[]; + } + + module Forge { + interface IContext { + new (): IContext; + bindings: IBinding[]; + has(binding: IBinding): boolean; + push(binding: IBinding): void; + pop(): IBinding; + toString(indent: number): string; + } + + interface IType { + new (...args: any[]): any; + } + + /** + * Represents arguments to help with resolving a binding. + */ + interface IBindingArguments { + [name: string]: any; + } + + /** + * Represents a binding between a name, type/instance/function and optional hint. + */ + interface IBinding { + /** The forge that contains this binding. */ + forge: Forge; + /** The binding name. */ + name: string; + /** Alias mapping to this binding. */ + to: IBinding; + /** Alias mapping to this binding. */ + as: IBinding; + /** Whether or not this binding is currently resolving. */ + isResolving: boolean; + /** The resolver for this binding. */ + resolver: IResolver; + /** The lifecycle associated with this binding. Defaults to singleton. */ + lifecycle: ILifecycle; + /** The predicate associated with this binding. Used to support hints. */ + predicate: IPredicate; + /** The additional binding arguments to help resolve dependencies. */ + arguments: IBindingArguments; + + /** + * Checks whether or not this binding matches the hint by executing the predicate. + * @param {string} hint The hint to check against. + */ + matches(hint: string): boolean; + /** + * Registers a type to a binding. This type must have a constructor. + * @param {T} target The target type. + */ + type(target: T): IBinding; + /** + * Registers a type to a binding. This must be a callable function. + * @param {T} target The target function. + */ + function(target: T): IBinding; + /** + * Registeres an instance to a binding. This instance will always be returned. + * @param {T} target The target instance. + */ + instance(target: T): IBinding; + /** + * Configures this binding lifecycle as a singleton. This is the default lifecycle. + */ + singleton(): IBinding; + /** + * Configures this binding lifecycle as transient. + * New instances will be created, if this is a type based binding, on each get. + */ + transient(): IBinding; + /** + * Registers a predicate for this binding. + * @param {IPredicate} predicate The predicate. + */ + when(predicate:IPredicate): IBinding; + /** + * Registers a hint for this binding. + * @param {string} hint The hint. + */ + when(hint: string): IBinding; + /** + * Registers additional binding arguments to help with resolving. + * @param {IBindingArguments} args The additional binding arguments. + */ + with(args: IBindingArguments): IBinding; + /** + * Returns a string representing this binding. + */ + toString(): string; + } + + /** Represents a binding map. */ + interface IBindingMap { + /** Gets a binding by name. */ + [name: string]: IBinding[]; + } + + /** Represents a predicate. */ + interface IPredicate { + /** + * Returns whether or not the hit satisfies this predicate. + * @param {string} hint The hint to check against. + */ + (hint: string): boolean; + } + + /** Represents a resolver. */ + interface IResolver { + /** + * Resolves a specific type. + */ + resolve(): T; + } + + /** Represents a binding lifecycle. */ + interface ILifecycle { + /** + * Returns the instance from a resolver based on the configured lifecycle. + * @param {IResolver} resolver The type resolver. + */ + getInstance(resolver: IResolver): T; + } + } + + export = Forge; +} diff --git a/github-electron/.editorconfig b/github-electron/.editorconfig new file mode 100644 index 000000000..2d98d905d --- /dev/null +++ b/github-electron/.editorconfig @@ -0,0 +1,2 @@ +[*.ts] +indent_style = tab diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts new file mode 100644 index 000000000..d353dfeb3 --- /dev/null +++ b/github-electron/github-electron-main-tests.ts @@ -0,0 +1,437 @@ +/// +import app = require('app'); +import AutoUpdater = require('auto-updater'); +import BrowserWindow = require('browser-window'); +import ContentTracing = require('content-tracing'); +import Dialog = require('dialog'); +import GlobalShortcut = require('global-shortcut'); +import ipc = require('ipc'); +import Menu = require('menu'); +import MenuItem = require('menu-item'); +import PowerMonitor = require('power-monitor'); +import Protocol = require('protocol'); +import Tray = require('tray'); +import Clipboard = require('clipboard'); +import CrashReporter = require('crash-reporter'); +import NativeImage = require('native-image'); +import Screen = require('screen'); +import Shell = require('shell'); + +import path = require('path'); + +// Quick start +// https://github.com/atom/electron/blob/master/docs/tutorial/quick-start.md + +// Report crashes to our server. +require('crash-reporter').start(); + +// Keep a global reference of the window object, if you don't, the window will +// be closed automatically when the javascript object is GCed. +var mainWindow: GitHubElectron.BrowserWindow = null; + +// Quit when all windows are closed. +app.on('window-all-closed', () => { + if (process.platform !== 'darwin') + app.quit(); +}); + +// This method will be called when Electron has done everything +// initialization and ready for creating browser windows. +app.on('ready', () => { + // Create the browser window. + mainWindow = new BrowserWindow({ width: 800, height: 600 }); + + // and load the index.html of the app. + mainWindow.loadUrl(`file://${__dirname}/index.html`); + + // Emitted when the window is closed. + mainWindow.on('closed', () => { + // Dereference the window object, usually you would store windows + // in an array if your app supports multi windows, this is the time + // when you should delete the corresponding element. + mainWindow = null; + }); +}); + +// Desktop environment integration +// https://github.com/atom/electron/blob/master/docs/tutorial/desktop-environment-integration.md + +app.addRecentDocument('/Users/USERNAME/Desktop/work.type'); +app.clearRecentDocuments(); +var dockMenu = Menu.buildFromTemplate([ + { + label: 'New Window', + click: () => { + console.log('New Window'); + } + }, + { + label: 'New Window with Settings', + submenu: [ + { label: 'Basic' }, + { label: 'Pro' } + ] + }, + { label: 'New Command...' } +]); +app.dock.setMenu(dockMenu); + +app.setUserTasks([ + { + program: process.execPath, + arguments: '--new-window', + iconPath: process.execPath, + iconIndex: 0, + title: 'New Window', + description: 'Create a new window' + } +]); +app.setUserTasks([]); + +var window = new BrowserWindow(); +window.setProgressBar(0.5); +window.setRepresentedFilename('/etc/passwd'); +window.setDocumentEdited(true); + +// Online/Offline Event Detection +// https://github.com/atom/electron/blob/master/docs/tutorial/online-offline-events.md + +var onlineStatusWindow: GitHubElectron.BrowserWindow; + +app.on('ready', () => { + onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false }); + onlineStatusWindow.loadUrl(`file://${__dirname}/online-status.html`); +}); + +ipc.on('online-status-changed', (event: any, status: any) => { + console.log(status); +}); + +// Synopsis +// https://github.com/atom/electron/blob/master/docs/api/synopsis.md + +app.on('ready', () => { + window = new BrowserWindow({ width: 800, height: 600 }); + window.loadUrl('https://github.com'); +}); + +// Supported Chrome command line switches +// https://github.com/atom/electron/blob/master/docs/api/chrome-command-line-switches.md + +app.commandLine.appendSwitch('remote-debugging-port', '8315'); +app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1'); +app.commandLine.appendSwitch('v', -1); +app.commandLine.appendSwitch('vmodule', 'console=0'); + +// auto-updater +// https://github.com/atom/electron/blob/master/docs/api/auto-updater.md + +AutoUpdater.setFeedUrl('http://mycompany.com/myapp/latest?version=' + app.getVersion()); + +// browser-window +// https://github.com/atom/electron/blob/master/docs/api/browser-window.md + +var win = new BrowserWindow({ width: 800, height: 600, show: false }); +win.on('closed', () => { + win = null; +}); + +win.loadUrl('https://github.com'); +win.show(); + +// content-tracing +// https://github.com/atom/electron/blob/master/docs/api/content-tracing.md + +ContentTracing.startRecording('*', ContentTracing.DEFAULT_OPTIONS, () => { + console.log('Tracing started'); + + setTimeout(() => { + ContentTracing.stopRecording('', path => { + console.log('Tracing data recorded to ' + path); + }); + }, 5000); +}); + +// dialog +// https://github.com/atom/electron/blob/master/docs/api/dialog.md + +console.log(Dialog.showOpenDialog({ + properties: ['openFile', 'openDirectory', 'multiSelections'] +})); + +// global-shortcut +// https://github.com/atom/electron/blob/master/docs/api/global-shortcut.md + +// Register a 'ctrl+x' shortcut listener. +var ret = GlobalShortcut.register('ctrl+x', () => { + console.log('ctrl+x is pressed'); +}); +if (!ret) + console.log('registerion fails'); + +// Check whether a shortcut is registered. +console.log(GlobalShortcut.isRegistered('ctrl+x')); + +// Unregister a shortcut. +GlobalShortcut.unregister('ctrl+x'); + +// Unregister all shortcuts. +GlobalShortcut.unregisterAll(); + +// ipc +// https://github.com/atom/electron/blob/master/docs/api/ipc-main-process.md + +ipc.on('asynchronous-message', (event: any, arg: any) => { + console.log(arg); // prints "ping" + event.sender.send('asynchronous-reply', 'pong'); +}); + +ipc.on('synchronous-message', (event: any, arg: any) => { + console.log(arg); // prints "ping" + event.returnValue = 'pong'; +}); + +// menu +// https://github.com/atom/electron/blob/master/docs/api/menu.md + +var menu = new Menu(); +menu.append(new MenuItem({ label: 'MenuItem1', click: () => { console.log('item 1 clicked'); } })); +menu.append(new MenuItem({ type: 'separator' })); +menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true })); + +// main.js +var template = [ + { + label: 'Electron', + submenu: [ + { + label: 'About Electron', + selector: 'orderFrontStandardAboutPanel:' + }, + { + type: 'separator' + }, + { + label: 'Services', + submenu: [] + }, + { + type: 'separator' + }, + { + label: 'Hide Electron', + accelerator: 'Command+H', + selector: 'hide:' + }, + { + label: 'Hide Others', + accelerator: 'Command+Shift+H', + selector: 'hideOtherApplications:' + }, + { + label: 'Show All', + selector: 'unhideAllApplications:' + }, + { + type: 'separator' + }, + { + label: 'Quit', + accelerator: 'Command+Q', + click: () => { app.quit(); } + } + ] + }, + { + label: 'Edit', + submenu: [ + { + label: 'Undo', + accelerator: 'Command+Z', + selector: 'undo:' + }, + { + label: 'Redo', + accelerator: 'Shift+Command+Z', + selector: 'redo:' + }, + { + type: 'separator' + }, + { + label: 'Cut', + accelerator: 'Command+X', + selector: 'cut:' + }, + { + label: 'Copy', + accelerator: 'Command+C', + selector: 'copy:' + }, + { + label: 'Paste', + accelerator: 'Command+V', + selector: 'paste:' + }, + { + label: 'Select All', + accelerator: 'Command+A', + selector: 'selectAll:' + } + ] + }, + { + label: 'View', + submenu: [ + { + label: 'Reload', + accelerator: 'Command+R', + click: () => { BrowserWindow.getFocusedWindow().reloadIgnoringCache(); } + }, + { + label: 'Toggle DevTools', + accelerator: 'Alt+Command+I', + click: () => { BrowserWindow.getFocusedWindow().toggleDevTools(); } + } + ] + }, + { + label: 'Window', + submenu: [ + { + label: 'Minimize', + accelerator: 'Command+M', + selector: 'performMiniaturize:' + }, + { + label: 'Close', + accelerator: 'Command+W', + selector: 'performClose:' + }, + { + type: 'separator' + }, + { + label: 'Bring All to Front', + selector: 'arrangeInFront:' + } + ] + }, + { + label: 'Help', + submenu: [] + } +]; + +menu = Menu.buildFromTemplate(template); + +Menu.setApplicationMenu(menu); // Must be called within app.on('ready', function(){ ... }); + +Menu.buildFromTemplate([ + { label: '4', id: '4' }, + { label: '5', id: '5' }, + { label: '1', id: '1', position: 'before=4' }, + { label: '2', id: '2' }, + { label: '3', id: '3' } +]); + +Menu.buildFromTemplate([ + { label: 'a', position: 'endof=letters' }, + { label: '1', position: 'endof=numbers' }, + { label: 'b', position: 'endof=letters' }, + { label: '2', position: 'endof=numbers' }, + { label: 'c', position: 'endof=letters' }, + { label: '3', position: 'endof=numbers' } +]); + +// power-monitor +// https://github.com/atom/electron/blob/master/docs/api/power-monitor.md + +app.on('ready', () => { + PowerMonitor.on('suspend', () => { + console.log('The system is going to sleep'); + }); +}); + +// protocol +// https://github.com/atom/electron/blob/master/docs/api/protocol.md + +app.on('ready', () => { + Protocol.registerProtocol('atom', (request: any) => { + var url = request.url.substr(7); + return new Protocol.RequestFileJob(path.normalize(`${__dirname}/${url}`)); + }); +}); + +// tray +// https://github.com/atom/electron/blob/master/docs/api/tray.md + +var appIcon: GitHubElectron.Tray = null; +app.on('ready', () => { + appIcon = new Tray('/path/to/my/icon'); + var contextMenu = Menu.buildFromTemplate([ + { label: 'Item1', type: 'radio' }, + { label: 'Item2', type: 'radio' }, + { label: 'Item3', type: 'radio', checked: true }, + { label: 'Item4', type: 'radio' }, + ]); + appIcon.setToolTip('This is my application.'); + appIcon.setContextMenu(contextMenu); +}); + +// clipboard +// https://github.com/atom/electron/blob/master/docs/api/clipboard.md + +Clipboard.writeText('Example String'); +Clipboard.writeText('Example String', 'selection'); +console.log(Clipboard.readText('selection')); + +// crash-reporter +// https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md + +CrashReporter.start({ + productName: 'YourName', + companyName: 'YourCompany', + submitUrl: 'https://your-domain.com/url-to-submit', + autoSubmit: true +}); + +// NativeImage +// https://github.com/atom/electron/blob/master/docs/api/native-image.md + +var appIcon2 = new Tray('/Users/somebody/images/icon.png'); +var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); +var image = Clipboard.readImage(); +var appIcon3 = new Tray(image); +var appIcon4 = new Tray('/Users/somebody/images/icon.png'); + +// screen +// https://github.com/atom/electron/blob/master/docs/api/screen.md + +app.on('ready', () => { + var size = Screen.getPrimaryDisplay().workAreaSize; + mainWindow = new BrowserWindow({ width: size.width, height: size.height }); +}); + +app.on('ready', () => { + var displays = Screen.getAllDisplays(); + var externalDisplay: any = null; + for (var i in displays) { + if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { + externalDisplay = displays[i]; + break; + } + } + + if (externalDisplay) { + mainWindow = new BrowserWindow({ + x: externalDisplay.bounds.x + 50, + y: externalDisplay.bounds.y + 50, + }); + } +}); + +// shell +// https://github.com/atom/electron/blob/master/docs/api/shell.md + +Shell.openExternal('https://github.com'); diff --git a/github-electron/github-electron-main.d.ts b/github-electron/github-electron-main.d.ts new file mode 100644 index 000000000..0ecdbf030 --- /dev/null +++ b/github-electron/github-electron-main.d.ts @@ -0,0 +1,227 @@ +// Type definitions for the Electron 0.25.2 main process +// Project: http://electron.atom.io/ +// Definitions by: jedmao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'app' { + var _app: GitHubElectron.App; + export = _app; +} + +declare module 'auto-updater' { + var _autoUpdater: GitHubElectron.AutoUpdater; + export = _autoUpdater; +} + +declare module 'browser-window' { + var BrowserWindow: typeof GitHubElectron.BrowserWindow; + export = BrowserWindow; +} + +declare module 'content-tracing' { + /** + * Get a set of category groups. The category groups can change as new code paths are reached. + * @param callback Called once all child processes have acked to the getCategories request. + */ + export function getCategories(callback: (categoryGroups: any[]) => void): void; + /** + * Start recording on all processes. Recording begins immediately locally, and asynchronously + * on child processes as soon as they receive the EnableRecording request. + * @param categoryFilter A filter to control what category groups should be traced. + * A filter can have an optional "-" prefix to exclude category groups that contain + * a matching category. Having both included and excluded category patterns in the + * same list would not be supported. + * @param options controls what kind of tracing is enabled, it could be a OR-ed + * combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING + * and tracing.RECORD_CONTINUOUSLY. + * @param callback Called once all child processes have acked to the startRecording request. + */ + export function startRecording(categoryFilter: string, options: number, callback: Function): void; + /** + * Stop recording on all processes. Child processes typically are caching trace data and + * only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid + * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all + * child processes to flush any pending trace data. + * @param resultFilePath Trace data will be written into this file if it is not empty, + * or into a temporary file. + * @param callback Called once all child processes have acked to the stopRecording request. + */ + export function stopRecording(resultFilePath: string, callback: + /** + * @param filePath A file that contains the traced data. + */ + (filePath: string) => void + ): void; + /** + * Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously + * on child processes as soon as they receive the startMonitoring request. + * @param callback Called once all child processes have acked to the startMonitoring request. + */ + export function startMonitoring(categoryFilter: string, options: number, callback: Function): void; + /** + * Stop monitoring on all processes. + * @param callback Called once all child processes have acked to the stopMonitoring request. + */ + export function stopMonitoring(callback: Function): void; + /** + * Get the current monitoring traced data. Child processes typically are caching trace data + * and only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid much + * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child + * processes to flush any pending trace data. + * @param callback Called once all child processes have acked to the captureMonitoringSnapshot request. + */ + export function captureMonitoringSnapshot(resultFilePath: string, callback: + /** + * @param filePath A file that contains the traced data + * @returns {} + */ + (filePath: string) => void + ): void; + /** + * Get the maximum across processes of trace buffer percent full state. + * @param callback Called when the TraceBufferUsage value is determined. + */ + export function getTraceBufferUsage(callback: Function): void; + /** + * @param callback Called every time the given event occurs on any process. + */ + export function setWatchEvent(categoryName: string, eventName: string, callback: Function): void; + /** + * Cancel the watch event. If tracing is enabled, this may race with the watch event callback. + */ + export function cancelWatchEvent(): void; + export var DEFAULT_OPTIONS: number; + export var ENABLE_SYSTRACE: number; + export var ENABLE_SAMPLING: number; + export var RECORD_CONTINUOUSLY: number; +} + +declare module 'dialog' { + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns an array of file paths chosen by the user, + * otherwise returns undefined. + */ + export var showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog; + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns the path of file chosen by the user, otherwise + * returns undefined. + */ + export var showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog; + /** + * Shows a message box. It will block until the message box is closed. It returns . + * @param callback If supplied, the API call will be asynchronous. + * @returns The index of the clicked button. + */ + export var showMessageBox: typeof GitHubElectron.Dialog.showMessageBox; + + /** + * Runs a modal dialog that shows an error message. This API can be called safely + * before the ready event of app module emits, it is usually used to report errors + * in early stage of startup. + */ + export function showErrorBox(title: string, content: string): void; +} + +declare module 'global-shortcut' { + /** + * Registers a global shortcut of accelerator. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @param callback Called when the registered shortcut is pressed by the user. + * @returns {} + */ + export function register(accelerator: string, callback: Function): void; + /** + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @returns Whether the accelerator is registered. + */ + export function isRegistered(accelerator: string): boolean; + /** + * Unregisters the global shortcut of keycode. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + */ + export function unregister(accelerator: string): void; + /** + * Unregisters all the global shortcuts. + */ + export function unregisterAll(): void; +} + +declare module 'ipc' { + var ipc: NodeJS.EventEmitter; + export = ipc; +} + +declare module 'menu' { + var Menu: typeof GitHubElectron.Menu; + export = Menu; +} + +declare module 'menu-item' { + var MenuItem: typeof GitHubElectron.MenuItem; + export = MenuItem; +} + +declare module 'power-monitor' { + var powerMonitor: NodeJS.EventEmitter; + export = powerMonitor; +} + +declare module 'protocol' { + export function registerProtocol(scheme: string, handler: (request: any) => void): void; + export function unregisterProtocol(scheme: string): void; + export function isHandledProtocol(scheme: string): boolean; + export function interceptProtocol(scheme: string, handler: (request: any) => void): void; + export function uninterceptProtocol(scheme: string): void; + export class RequestFileJob { + /** + * Create a request job which would query a file of path and set corresponding mime types. + */ + constructor(path: string); + } + export class RequestStringJob { + /** + * Create a request job which sends a string as response. + */ + constructor(options?: { + /** + * Default is "text/plain". + */ + mimeType?: string; + /** + * Default is "UTF-8". + */ + charset?: string; + data?: string; + }); + } + export class RequestBufferJob { + /** + * Create a request job which accepts a buffer and sends a string as response. + */ + constructor(options?: { + /** + * Default is "application/octet-stream". + */ + mimeType?: string; + /** + * Default is "UTF-8". + */ + encoding?: string; + data?: Buffer; + }); + } +} + +declare module 'tray' { + var Tray: typeof GitHubElectron.Tray; + export = Tray; +} diff --git a/github-electron/github-electron-renderer-tests.ts b/github-electron/github-electron-renderer-tests.ts new file mode 100644 index 000000000..4c940b651 --- /dev/null +++ b/github-electron/github-electron-renderer-tests.ts @@ -0,0 +1,116 @@ +/// +import ipc = require('ipc'); +import remote = require('remote'); +import WebFrame = require('web-frame'); +import Clipboard = require('clipboard'); +import CrashReporter = require('crash-reporter'); +import NativeImage = require('native-image'); +import Screen = require('screen'); +import Shell = require('shell'); + +import fs = require('fs'); + +// In renderer process (web page). +// https://github.com/atom/electron/blob/master/docs/api/ipc-renderer.md +console.log(ipc.sendSync('synchronous-message', 'ping')); // prints "pong" + +ipc.on('asynchronous-reply', (arg: any) => { + console.log(arg); // prints "pong" +}); +ipc.send('asynchronous-message', 'ping'); + +// remote +// https://github.com/atom/electron/blob/master/docs/api/remote.md + +var BrowserWindow: typeof GitHubElectron.BrowserWindow = remote.require('browser-window'); +var win = new BrowserWindow({ width: 800, height: 600 }); +win.loadUrl('https://github.com'); + +remote.getCurrentWindow().on('close', () => { + // blabla... +}); + +remote.getCurrentWindow().capturePage(buf => { + fs.writeFile('/tmp/screenshot.png', buf, err => { + console.log(err); + }); +}); + +remote.getCurrentWindow().capturePage(buf => { + remote.require('fs').writeFile('/tmp/screenshot.png', buf, (err: Error) => { + console.log(err); + }); +}); + +// web-frame +// https://github.com/atom/electron/blob/master/docs/api/web-frame.md + +WebFrame.setZoomFactor(2); + +WebFrame.setSpellCheckProvider('en-US', true, { + spellCheck: text => { + return !(require('spellchecker').isMisspelled(text)); + } +}); + +// clipboard +// https://github.com/atom/electron/blob/master/docs/api/clipboard.md + +Clipboard.writeText('Example String'); +Clipboard.writeText('Example String', 'selection'); +console.log(Clipboard.readText('selection')); + +// crash-reporter +// https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md + +CrashReporter.start({ + productName: 'YourName', + companyName: 'YourCompany', + submitUrl: 'https://your-domain.com/url-to-submit', + autoSubmit: true +}); + +// NativeImage +// https://github.com/atom/electron/blob/master/docs/api/native-image.md + +var Tray: typeof GitHubElectron.Tray = remote.require('Tray'); +var appIcon2 = new Tray('/Users/somebody/images/icon.png'); +var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); +var image = Clipboard.readImage(); +var appIcon3 = new Tray(image); +var appIcon4 = new Tray('/Users/somebody/images/icon.png'); + +// screen +// https://github.com/atom/electron/blob/master/docs/api/screen.md + +var app: GitHubElectron.App = remote.require('app'); + +var mainWindow: GitHubElectron.BrowserWindow = null; + +app.on('ready', () => { + var size = Screen.getPrimaryDisplay().workAreaSize; + mainWindow = new BrowserWindow({ width: size.width, height: size.height }); +}); + +app.on('ready', () => { + var displays = Screen.getAllDisplays(); + var externalDisplay: any = null; + for (var i in displays) { + if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { + externalDisplay = displays[i]; + break; + } + } + + if (externalDisplay) { + mainWindow = new BrowserWindow({ + x: externalDisplay.bounds.x + 50, + y: externalDisplay.bounds.y + 50, + }); + } +}); + +// shell +// https://github.com/atom/electron/blob/master/docs/api/shell.md + +Shell.openExternal('https://github.com'); diff --git a/github-electron/github-electron-renderer.d.ts b/github-electron/github-electron-renderer.d.ts new file mode 100644 index 000000000..e2a310d28 --- /dev/null +++ b/github-electron/github-electron-renderer.d.ts @@ -0,0 +1,105 @@ +// Type definitions for the Electron 0.25.2 renderer process (web page) +// Project: http://electron.atom.io/ +// Definitions by: jedmao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module GitHubElectron { + + class InProcess implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): InProcess; + on(event: string, listener: Function): InProcess; + once(event: string, listener: Function): InProcess; + removeListener(event: string, listener: Function): InProcess; + removeAllListeners(event?: string): InProcess; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + /** + * Send ...args to the renderer via channel in asynchronous message, the main + * process can handle it by listening to the channel event of ipc module. + */ + send(channel: string, ...args: any[]): void; + /** + * Send ...args to the renderer via channel in synchronous message, and returns + * the result sent from main process. The main process can handle it by listening + * to the channel event of ipc module, and returns by setting event.returnValue. + * Note: Usually developers should never use this API, since sending synchronous + * message would block the whole renderer process. + * @returns The result sent from the main process. + */ + sendSync(channel: string, ...args: any[]): string; + /** + * Like ipc.send but the message will be sent to the host page instead of the main process. + * This is mainly used by the page in to communicate with host page. + */ + sendToHost(channel: string, ...args: any[]): void; + } + + module Remote { + export function getCurrentWindow(): BrowserWindow; + } +} + +declare module 'ipc' { + var InProcess: GitHubElectron.InProcess; + export = InProcess; +} + +declare module 'remote' { + /** + * @returns The object returned by require(module) in the main process. + */ + export function require(module: string): any; + /** + * @returns The BrowserWindow object which this web page belongs to. + */ + export var getCurrentWindow: typeof GitHubElectron.Remote.getCurrentWindow; + /** + * @returns The global variable of name (e.g. global[name]) in the main process. + */ + export function getGlobal(name: string): any; + /** + * Returns the process object in the main process. This is the same as + * remote.getGlobal('process'), but gets cached. + */ + export var process: any; +} + +declare module 'web-frame' { + /** + * Changes the zoom factor to the specified factor, zoom factor is + * zoom percent / 100, so 300% = 3.0. + */ + export function setZoomFactor(factor: number): void; + /** + * @returns The current zoom factor. + */ + export function getZoomFactor(): number; + /** + * Changes the zoom level to the specified level, 0 is "original size", and each + * increment above or below represents zooming 20% larger or smaller to default + * limits of 300% and 50% of original size, respectively. + */ + export function setZoomLevel(level: number): void; + /** + * @returns The current zoom level. + */ + export function getZoomLevel(): number; + /** + * Sets a provider for spell checking in input fields and text areas. + */ + export function setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: { + /** + * @returns Whether the word passed is correctly spelled. + */ + spellCheck: (text: string) => boolean; + }): void; + /** + * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content + * warnings. For example, https and data are secure schemes because they cannot be + * corrupted by active network attackers. + */ + export function registerUrlSchemeAsSecure(scheme: string): void; +} diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts new file mode 100644 index 000000000..4e1e289ca --- /dev/null +++ b/github-electron/github-electron.d.ts @@ -0,0 +1,1295 @@ +// Type definitions for Electron 0.25.2 (shared between main and rederer processes) +// Project: http://electron.atom.io/ +// Definitions by: jedmao +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module GitHubElectron { + /** + * This class is used to represent an image. + */ + class NativeImage { + /** + * Creates an empty NativeImage instance. + */ + static createEmpty(): NativeImage; + /** + * Creates a new NativeImage instance from file located at path. + */ + static createFromPath(path: string): NativeImage; + /** + * Creates a new NativeImage instance from buffer. + * @param scaleFactor 1.0 by default. + */ + static createFromBuffer(buffer: Buffer, scaleFactor?: number): NativeImage; + /** + * Creates a new NativeImage instance from dataUrl + */ + static createFromDataUrl(dataUrl: string): NativeImage; + /** + * @returns Buffer Contains the image's PNG encoded data. + */ + toPng(): Buffer; + /** + * @returns Buffer Contains the image's JPEG encoded data. + */ + toJpeg(quality: number): Buffer; + /** + * @returns string The data URL of the image. + */ + toDataUrl(): string; + /** + * @returns boolean Whether the image is empty. + */ + isEmpty(): boolean; + /** + * @returns {} The size of the image. + */ + getSize(): any; + /** + * Marks the image as template image. + */ + setTemplateImage(option: boolean): void; + } + + module Clipboard { + /** + * @returns The contents of the clipboard as a NativeImage. + */ + function readImage(type?: string): NativeImage; + /** + * Writes the image into the clipboard. + */ + function writeImage(image: NativeImage, type?: string): void; + } + + class Screen implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): Screen; + on(event: string, listener: Function): Screen; + once(event: string, listener: Function): Screen; + removeListener(event: string, listener: Function): Screen; + removeAllListeners(event?: string): Screen; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + /** + * @returns The current absolute position of the mouse pointer. + */ + getCursorScreenPoint(): any; + /** + * @returns The primary display. + */ + getPrimaryDisplay(): any; + /** + * @returns An array of displays that are currently available. + */ + getAllDisplays(): any[]; + /** + * @returns The display nearest the specified point. + */ + getDisplayNearestPoint(point: { + x: number; + y: number; + }): any; + /** + * @returns The display that most closely intersects the provided bounds. + */ + getDisplayMatching(rect: Rectangle): any; + } + + /** + * The BrowserWindow class gives you ability to create a browser window. + * You can also create a window without chrome by using Frameless Window API. + */ + class BrowserWindow implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): WebContents; + on(event: string, listener: Function): WebContents; + once(event: string, listener: Function): WebContents; + removeListener(event: string, listener: Function): WebContents; + removeAllListeners(event?: string): WebContents; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + constructor(options?: BrowserWindowOptions); + /** + * @returns All opened browser windows. + */ + static getAllWindows(): BrowserWindow[]; + /** + * @returns The window that is focused in this application. + */ + static getFocusedWindow(): BrowserWindow; + /** + * Find a window according to the webContents it owns. + */ + static fromWebContents(webContents: WebContents): BrowserWindow; + /** + * Find a window according to its ID. + */ + static fromId(id: number): BrowserWindow; + /** + * Adds devtools extension located at path. The extension will be remembered + * so you only need to call this API once, this API is not for programming use. + * @returns The extension's name. + */ + static addDevToolsExtension(path: string): string; + /** + * Remove a devtools extension. + * @param name The name of the devtools extension to remove. + */ + static removeDevToolsExtension(name: string): void; + /** + * The WebContents object this window owns, all web page related events and + * operations would be done via it. + * Note: Users should never store this object because it may become null when + * the renderer process (web page) has crashed. + */ + webContents: WebContents; + /** + * Get the WebContents of devtools of this window. + * Note: Users should never store this object because it may become null when + * the devtools has been closed. + */ + devToolsWebContents: WebContents; + /** + * Get the unique ID of this window. + */ + id: number; + /** + * Force closing the window, the unload and beforeunload event won't be emitted + * for the web page, and close event would also not be emitted for this window, + * but it would guarantee the closed event to be emitted. + * You should only use this method when the renderer process (web page) has crashed. + */ + destroy(): void; + /** + * Try to close the window, this has the same effect with user manually clicking + * the close button of the window. The web page may cancel the close though, + * see the close event. + */ + close(): void; + /** + * Focus on the window. + */ + focus(): void; + /** + * @returns Whether the window is focused. + */ + isFocused(): boolean; + /** + * Shows and gives focus to the window. + */ + show(): void; + /** + * Shows the window but doesn't focus on it. + */ + showInactive(): void; + /** + * Hides the window. + */ + hide(): void; + /** + * @returns Whether the window is visible to the user. + */ + isVisible(): boolean; + /** + * Maximizes the window. + */ + maximize(): void; + /** + * Unmaximizes the window. + */ + unmaximize(): void; + /** + * @returns Whether the window is maximized. + */ + isMaximized(): boolean; + /** + * Minimizes the window. On some platforms the minimized window will be + * shown in the Dock. + */ + minimize(): void; + /** + * Restores the window from minimized state to its previous state. + */ + restore(): void; + /** + * @returns Whether the window is minimized. + */ + isMinimized(): boolean; + /** + * Sets whether the window should be in fullscreen mode. + */ + setFullScreen(flag: boolean): void; + /** + * @returns Whether the window is in fullscreen mode. + */ + isFullScreen(): boolean; + /** + * Resizes and moves the window to width, height, x, y. + */ + setBounds(options: Rectangle): void; + /** + * @returns The window's width, height, x and y values. + */ + getBounds(): Rectangle; + /** + * Resizes the window to width and height. + */ + setSize(width: number, height: number): void; + /** + * @returns The window's width and height. + */ + getSize(): number[]; + /** + * Resizes the window's client area (e.g. the web page) to width and height. + */ + setContentSize(width: number, height: number): void; + /** + * @returns The window's client area's width and height. + */ + getContentSize(): number[]; + /** + * Sets the minimum size of window to width and height. + */ + setMinimumSize(width: number, height: number): void; + /** + * @returns The window's minimum width and height. + */ + getMinimumSize(): number[]; + /** + * Sets the maximum size of window to width and height. + */ + setMaximumSize(width: number, height: number): void; + /** + * @returns The window's maximum width and height. + */ + getMaximumSize(): number[]; + /** + * Sets whether the window can be manually resized by user. + */ + setResizable(resizable: boolean): void; + /** + * @returns Whether the window can be manually resized by user. + */ + isResizable(): boolean; + /** + * Sets whether the window should show always on top of other windows. After + * setting this, the window is still a normal window, not a toolbox window + * which can not be focused on. + */ + setAlwaysOnTop(flag: boolean): void; + /** + * @returns Whether the window is always on top of other windows. + */ + isAlwaysOnTop(): boolean; + /** + * Moves window to the center of the screen. + */ + center(): void; + /** + * Moves window to x and y. + */ + setPosition(x: number, y: number): void; + /** + * @returns The window's current position. + */ + getPosition(): number[]; + /** + * Changes the title of native window to title. + */ + setTitle(title: string): void; + /** + * Note: The title of web page can be different from the title of the native window. + * @returns The title of the native window. + */ + getTitle(): string; + /** + * Starts or stops flashing the window to attract user's attention. + */ + flashFrame(flag: boolean): void; + /** + * Makes the window do not show in Taskbar. + */ + setSkipTaskbar(skip: boolean): void; + /** + * Enters or leaves the kiosk mode. + */ + setKiosk(flag: boolean): void; + /** + * @returns Whether the window is in kiosk mode. + */ + isKiosk(): boolean; + /** + * Sets the pathname of the file the window represents, and the icon of the + * file will show in window's title bar. + * Note: This API is available only on OS X. + */ + setRepresentedFilename(filename: string): void; + /** + * Note: This API is available only on OS X. + * @returns The pathname of the file the window represents. + */ + getRepresentedFilename(): string; + /** + * Specifies whether the window’s document has been edited, and the icon in + * title bar will become grey when set to true. + * Note: This API is available only on OS X. + */ + setDocumentEdited(edited: boolean): void; + /** + * Note: This API is available only on OS X. + * @returns Whether the window's document has been edited. + */ + isDocumentEdited(): boolean; + /** + * Opens the developer tools. + */ + openDevTools(options?: { + /** + * Opens devtools in a new window. + */ + detach?: boolean; + }): void; + /** + * Closes the developer tools. + */ + closeDevTools(): void; + /** + * Toggle the developer tools. + */ + toggleDevTools(): void; + reloadIgnoringCache(): void; + /** + * Starts inspecting element at position (x, y). + */ + inspectElement(x: number, y: number): void; + focusOnWebView(): void; + blurWebView(): void; + /** + * Captures the snapshot of page within rect, upon completion the callback + * will be called. Omitting the rect would capture the whole visible page. + * Note: Be sure to read documents on remote buffer in remote if you are going + * to use this API in renderer process. + * @param callback Supplies the image that stores data of the snapshot. + */ + capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; + capturePage(callback: (image: NativeImage) => void): void; + /** + * Prints the window's web page. Calling window.print() in a web page is + * equivalent to calling BrowserWindow.print({silent: false, printBackground: false}). + */ + print(options?: { + /** + * When false, Electron will pick up system's default printer and default + * settings for printing. + */ + silent?: boolean; + printBackground?: boolean; + }): void; + /** + * Same with webContents.loadUrl(url). + */ + loadUrl(url: string): void; + /** + * Same with webContents.reload. + */ + reload(): void; + /** + * Sets the menu as the window top menu. + * Note: This API is not available on OS X. + */ + setMenu(menu: Menu): void; + /** + * Sets the progress value in the progress bar. + * On Linux platform, only supports Unity desktop environment, you need to + * specify the *.desktop file name to desktopName field in package.json. + * By default, it will assume app.getName().desktop. + * @param progress Valid range is [0, 1.0]. If < 0, the progress bar is removed. + * If greater than 0, it becomes indeterminate. + */ + setProgressBar(progress: number): void; + /** + * Sets a 16px overlay onto the current Taskbar icon, usually used to convey + * some sort of application status or to passively notify the user. + * Note: This API is only available on Windows 7 or above. + * @param overlay The icon to display on the bottom right corner of the Taskbar + * icon. If this parameter is null, the overlay is cleared + * @param description Provided to Accessibility screen readers. + */ + setOverlayIcon(overlay: NativeImage, description: string): void; + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on OS X. + */ + showDefinitionForSelection(): void; + /** + * Sets whether the window menu bar should hide itself automatically. Once set + * the menu bar will only show when users press the single Alt key. + * If the menu bar is already visible, calling setAutoHideMenuBar(true) won't + * hide it immediately. + */ + setAutoHideMenuBar(hide: boolean): void; + /** + * @returns Whether menu bar automatically hides itself. + */ + isMenuBarAutoHide(): boolean; + /** + * Sets whether the menu bar should be visible. If the menu bar is auto-hide, + * users can still bring up the menu bar by pressing the single Alt key. + */ + setMenuBarVisibility(visibile: boolean): void; + /** + * @returns Whether the menu bar is visible. + */ + isMenuBarVisible(): boolean; + /** + * Sets whether the window should be visible on all workspaces. + * Note: This API does nothing on Windows. + */ + setVisibleOnAllWorkspaces(visible: boolean): void; + /** + * Note: This API always returns false on Windows. + * @returns Whether the window is visible on all workspaces. + */ + isVisibleOnAllWorkspaces(): boolean; + } + + interface BrowserWindowOptions extends Rectangle { + show?: boolean; + } + + interface Rectangle { + x?: number; + y?: number; + width?: number; + height?: number; + } + + /** + * A WebContents is responsible for rendering and controlling a web page. + */ + class WebContents implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): WebContents; + on(event: string, listener: Function): WebContents; + once(event: string, listener: Function): WebContents; + removeListener(event: string, listener: Function): WebContents; + removeAllListeners(event?: string): WebContents; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + /** + * Loads the url in the window. + * @param url Must contain the protocol prefix (e.g., the http:// or file://). + */ + loadUrl(url: string): void; + /** + * @returns The URL of current web page. + */ + getUrl(): string; + /** + * @returns The title of web page. + */ + getTitle(): string; + /** + * @returns The favicon of the web page. + */ + getFavicon(): NativeImage; + /** + * @returns Whether web page is still loading resources. + */ + isLoading(): boolean; + /** + * @returns Whether web page is waiting for a first-response for the main + * resource of the page. + */ + isWaitingForResponse(): boolean; + /** + * Stops any pending navigation. + */ + stop(): void; + /** + * Reloads current page. + */ + reload(): void; + /** + * Reloads current page and ignores cache. + */ + reloadIgnoringCache(): void; + /** + * @returns Whether the web page can go back. + */ + canGoBack(): boolean; + /** + * @returns Whether the web page can go forward. + */ + canGoForward(): boolean; + /** + * @returns Whether the web page can go to offset. + */ + canGoToOffset(offset: number): boolean; + /** + * Makes the web page go back. + */ + goBack(): void; + /** + * Makes the web page go forward. + */ + goForward(): void; + /** + * Navigates to the specified absolute index. + */ + goToIndex(index: number): void; + /** + * Navigates to the specified offset from the "current entry". + */ + goToOffset(offset: number): void; + /** + * @returns Whether the renderer process has crashed. + */ + isCrashed(): boolean; + /** + * Overrides the user agent for this page. + */ + setUserAgent(userAgent: string): void; + /** + * Injects CSS into this page. + */ + insertCSS(css: string): void; + /** + * Evaluates code in page. + * @param code Code to evaluate. + */ + executeJavaScript(code: string): void; + /** + * Executes Edit -> Undo command in page. + */ + undo(): void; + /** + * Executes Edit -> Redo command in page. + */ + redo(): void; + /** + * Executes Edit -> Cut command in page. + */ + cut(): void; + /** + * Executes Edit -> Copy command in page. + */ + copy(): void; + /** + * Executes Edit -> Paste command in page. + */ + paste(): void; + /** + * Executes Edit -> Delete command in page. + */ + delete(): void; + /** + * Executes Edit -> Select All command in page. + */ + selectAll(): void; + /** + * Executes Edit -> Unselect command in page. + */ + unselect(): void; + /** + * Executes Edit -> Replace command in page. + */ + replace(text: string): void; + /** + * Executes Edit -> Replace Misspelling command in page. + */ + replaceMisspelling(text: string): void; + /** + * Checks if any serviceworker is registered. + */ + hasServiceWorker(callback: (hasServiceWorker: boolean) => void): void; + /** + * Unregisters any serviceworker if present. + */ + unregisterServiceWorker(callback: + /** + * @param isFulfilled Whether the JS promise is fulfilled. + */ + (isFulfilled: boolean) => void): void; + /** + * Send args.. to the web page via channel in asynchronous message, the web page + * can handle it by listening to the channel event of ipc module. + * Note: + * 1. The IPC message handler in web pages do not have a event parameter, + * which is different from the handlers on the main process. + * 2. There is no way to send synchronous messages from the main process + * to a renderer process, because it would be very easy to cause dead locks. + */ + send(channel: string, ...args: any[]): void; + } + + /** + * The Menu class is used to create native menus that can be used as application + * menus and context menus. Each menu consists of multiple menu items, and each + * menu item can have a submenu. + */ + class Menu { + /** + * Creates a new menu. + */ + constructor(); + /** + * Sets menu as the application menu on OS X. On Windows and Linux, the menu + * will be set as each window's top menu. + */ + static setApplicationMenu(menu: Menu): void; + /** + * Sends the action to the first responder of application, this is used for + * emulating default Cocoa menu behaviors, usually you would just use the + * selector property of MenuItem. + * + * Note: This method is OS X only. + */ + static sendActionToFirstResponder(action: string): void; + /** + * @param template Generally, just an array of options for constructing MenuItem. + * You can also attach other fields to element of the template, and they will + * become properties of the constructed menu items. + */ + static buildFromTemplate(template: MenuItemOptions[]): Menu; + /** + * Popups this menu as a context menu in the browserWindow. You can optionally + * provide a (x,y) coordinate to place the menu at, otherwise it will be placed + * at the current mouse cursor position. + * @param x Horizontal coordinate where the menu will be placed. + * @param y Vertical coordinate where the menu will be placed. + */ + popup(browserWindow: BrowserWindow, x?: number, y?: number): void; + /** + * Appends the menuItem to the menu. + */ + append(menuItem: MenuItem): void; + /** + * Inserts the menuItem to the pos position of the menu. + */ + insert(position: number, menuItem: MenuItem): void; + items: MenuItem[]; + } + + class MenuItem { + constructor(options?: MenuItemOptions); + options: MenuItemOptions; + } + + interface MenuItemOptions { + /** + * Callback when the menu item is clicked. + */ + click?: Function; + /** + * Call the selector of first responder when clicked (OS X only). + */ + selector?: string; + /** + * Can be normal, separator, submenu, checkbox or radio. + */ + type?: string; + label?: string; + sublabel?: string; + /** + * An accelerator is string that represents a keyboard shortcut, it can contain + * multiple modifiers and key codes, combined by the + character. + * + * Examples: + * Command+A + * Ctrl+Shift+Z + * + * Platform notice: On Linux and Windows, the Command key would not have any effect, + * you can use CommandOrControl which represents Command on OS X and Control on + * Linux and Windows to define some accelerators. + * + * Available modifiers: + * Command (or Cmd for short) + * Control (or Ctrl for short) + * CommandOrControl (or CmdOrCtrl for short) + * Alt + * Shift + * + * Available key codes: + * 0 to 9 + * A to Z + * F1 to F24 + * Punctuations like ~, !, @, #, $, etc. + * Plus + * Space + * Backspace + * Delete + * Insert + * Return (or Enter as alias) + * Up, Down, Left and Right + * Home and End + * PageUp and PageDown + * Escape (or Esc for short) + * VolumeUp, VolumeDown and VolumeMute + * MediaNextTrack, MediaPreviousTrack, MediaStop and MediaPlayPause + */ + accelerator?: string; + /** + * In Electron for the APIs that take images, you can pass either file paths + * or NativeImage instances. When passing null, an empty image will be used. + */ + icon?: NativeImage|string; + enabled?: boolean; + visible?: boolean; + checked?: boolean; + /** + * Should be specified for submenu type menu item, when it's specified the + * type: 'submenu' can be omitted for the menu item + */ + submenu?: MenuItemOptions[]; + /** + * Unique within a single menu. If defined then it can be used as a reference + * to this item by the position attribute. + */ + id?: string; + /** + * This field allows fine-grained definition of the specific location within + * a given menu. + */ + position?: string; + } + + class BrowserWindowProxy { + /** + * Removes focus from the child window. + */ + blur(): void; + /** + * Forcefully closes the child window without calling its unload event. + */ + close(): void; + /** + * Set to true after the child window gets closed. + */ + closed: boolean; + /** + * Evaluates the code in the child window. + */ + eval(code: string): void; + /** + * Focuses the child window (brings the window to front). + */ + focus(): void; + /** + * Sends a message to the child window with the specified origin or * for no origin preference. + * In addition to these methods, the child window implements window.opener object with no + * properties and a single method. + */ + postMessage(message: string, targetOrigin: string): void; + } + + class App implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): App; + on(event: string, listener: Function): App; + once(event: string, listener: Function): App; + removeListener(event: string, listener: Function): App; + removeAllListeners(event?: string): App; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + /** + * Try to close all windows. The before-quit event will first be emitted. + * If all windows are successfully closed, the will-quit event will be emitted + * and by default the application would be terminated. + * + * This method guarantees all beforeunload and unload handlers are correctly + * executed. It is possible that a window cancels the quitting by returning + * false in beforeunload handler. + */ + quit(): void; + /** + * Quit the application directly, it will not try to close all windows so + * cleanup code will not run. + */ + terminate(): void; + /** + * @param name One of: home, appData, userData, cache, userCache, temp, userDesktop, exe, module + * @returns The path to a special directory or file associated with name. + * On failure an Error would throw. + */ + getPath(name: string): string; + /** + * Overrides the path to a special directory or file associated with name. + * If the path specifies a directory that does not exist, the directory will + * be created by this method. On failure an Error would throw. + * + * You can only override paths of names defined in app.getPath. + * + * By default web pages' cookies and caches will be stored under userData + * directory, if you want to change this location, you have to override the + * userData path before the ready event of app module gets emitted. + */ + setPath(name: string, path: string): void; + /** + * @returns The version of loaded application, if no version is found in + * application's package.json, the version of current bundle or executable. + */ + getVersion(): string; + /** + * + * @returns The current application's name, the name in package.json would be used. + * Usually the name field of package.json is a short lowercased name, according to + * the spec of npm modules. So usually you should also specify a productName field, + * which is your application's full capitalized name, and it will be preferred over + * name by Electron. + */ + getName(): string; + /** + * Resolves the proxy information for url, the callback would be called with + * callback(proxy) when the request is done. + */ + resolveProxy(url: string, callback: Function): void; + /** + * Adds path to recent documents list. + * + * This list is managed by the system, on Windows you can visit the list from + * task bar, and on Mac you can visit it from dock menu. + */ + addRecentDocument(path: string): void; + /** + * Clears the recent documents list. + */ + clearRecentDocuments(): void; + /** + * Adds tasks to the Tasks category of JumpList on Windows. + * + * Note: This API is only available on Windows. + */ + setUserTasks(tasks: Task[]): void; + dock: BrowserWindow; + commandLine: CommandLine; + } + + interface CommandLine { + /** + * Append a switch [with optional value] to Chromium's command line. + * + * Note: This will not affect process.argv, and is mainly used by developers + * to control some low-level Chromium behaviors. + */ + appendSwitch(_switch: string, value?: string|number): void; + /** + * Append an argument to Chromium's command line. The argument will quoted properly. + * + * Note: This will not affect process.argv. + */ + appendArgument(value: any): void; + } + + interface Task { + /** + * Path of the program to execute, usually you should specify process.execPath + * which opens current program. + */ + program: string; + /** + * The arguments of command line when program is executed. + */ + arguments: string; + /** + * The string to be displayed in a JumpList. + */ + title: string; + /** + * Description of this task. + */ + description: string; + /** + * The absolute path to an icon to be displayed in a JumpList, it can be + * arbitrary resource file that contains an icon, usually you can specify + * process.execPath to show the icon of the program. + */ + iconPath: string; + /** + * The icon index in the icon file. If an icon file consists of two or more + * icons, set this value to identify the icon. If an icon file consists of + * one icon, this value is 0. + */ + iconIndex: number; + commandLine: CommandLine; + dock: { + /** + * When critical is passed, the dock icon will bounce until either the + * application becomes active or the request is canceled. + * + * When informational is passed, the dock icon will bounce for one second. + * The request, though, remains active until either the application becomes + * active or the request is canceled. + * + * Note: This API is only available on Mac. + * @param type Can be critical or informational, the default is informational. + * @returns An ID representing the request + */ + bounce(type?: string): any; + /** + * Cancel the bounce of id. + * + * Note: This API is only available on Mac. + */ + cancelBounce(id: number): void; + /** + * Sets the string to be displayed in the dock’s badging area. + * + * Note: This API is only available on Mac. + */ + setBadge(text: string): void; + /** + * Returns the badge string of the dock. + * + * Note: This API is only available on Mac. + */ + getBadge(): string; + /** + * Hides the dock icon. + * + * Note: This API is only available on Mac. + */ + hide(): void; + /** + * Shows the dock icon. + * + * Note: This API is only available on Mac. + */ + show(): void; + /** + * Sets the application dock menu. + * + * Note: This API is only available on Mac. + */ + setMenu(menu: Menu): void; + } + } + + class AutoUpdater implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): AutoUpdater; + on(event: string, listener: Function): AutoUpdater; + once(event: string, listener: Function): AutoUpdater; + removeListener(event: string, listener: Function): AutoUpdater; + removeAllListeners(event?: string): AutoUpdater; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + /** + * Set the url and initialize the auto updater. + * The url cannot be changed once it is set. + */ + setFeedUrl(url: string): void; + /** + * Ask the server whether there is an update, you have to call setFeedUrl + * before using this API + */ + checkForUpdates(): any; + } + + module Dialog { + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns an array of file paths chosen by the user, + * otherwise returns undefined. + */ + export function showOpenDialog( + browserWindow?: BrowserWindow, + options?: OpenDialogOptions, + callback?: (fileNames: string[]) => void + ): void; + export function showOpenDialog( + options?: OpenDialogOptions, + callback?: (fileNames: string[]) => void + ): void; + + interface OpenDialogOptions { + title?: string; + defaultPath?: string; + /** + * File types that can be displayed or selected. + */ + filters?: { + name: string; + extensions: string[]; + }[]; + /** + * Contains which features the dialog should use, can contain openFile, + * openDirectory, multiSelections and createDirectory + */ + properties?: string|string[]; + } + + /** + * @param browserWindow + * @param options + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns the path of file chosen by the user, otherwise + * returns undefined. + */ + export function showSaveDialog(browserWindow?: BrowserWindow, options?: { + title?: string; + defaultPath?: string; + /** + * File types that can be displayed, see dialog.showOpenDialog for an example. + */ + filters?: string[]; + }, callback?: (fileName: string) => void): void; + + /** + * Shows a message box. It will block until the message box is closed. It returns . + * @param callback If supplied, the API call will be asynchronous. + * @returns The index of the clicked button. + */ + export function showMessageBox( + browserWindow?: BrowserWindow, + options?: ShowMessageBoxOptions, + callback?: (response: any) => void + ): number; + export function showMessageBox( + options: ShowMessageBoxOptions, + callback?: (response: any) => void + ): number; + + export interface ShowMessageBoxOptions { + /** + * Can be "none", "info" or "warning". + */ + type?: string; + /** + * Texts for buttons. + */ + buttons?: string[]; + /** + * Title of the message box (some platforms will not show it). + */ + title?: string; + /** + * Contents of the message box. + */ + message?: string; + /** + * Extra information of the message. + */ + detail?: string; + icon?: NativeImage; + } + } + + class Tray implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): Tray; + on(event: string, listener: Function): Tray; + once(event: string, listener: Function): Tray; + removeListener(event: string, listener: Function): Tray; + removeAllListeners(event?: string): Tray; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + /** + * Creates a new tray icon associated with the image. + */ + constructor(image: NativeImage|string); + /** + * Destroys the tray icon immediately. + */ + destroy(): void; + /** + * Sets the image associated with this tray icon. + */ + setImage(image: NativeImage): void; + /** + * Sets the image associated with this tray icon when pressed. + */ + setPressedImage(image: NativeImage): void; + /** + * Sets the hover text for this tray icon. + */ + setToolTip(toolTip: string): void; + /** + * Sets the title displayed aside of the tray icon in the status bar. + * Note: This is only implemented on OS X. + */ + setTitle(title: string): void; + /** + * Sets whether the tray icon is highlighted when it is clicked. + * Note: This is only implemented on OS X. + */ + setHighlightMode(highlight: boolean): void; + /** + * Displays a tray balloon. + * Note: This is only implemented on Windows. + */ + displayBalloon(options?: { + icon?: NativeImage; + title?: string; + content?: string; + }): void; + /** + * Sets the context menu for this icon. + */ + setContextMenu(menu: Menu): void; + } +} + +declare module 'clipboard' { + /** + * @returns The contents of the clipboard as plain text. + */ + export function readText(type?: string): string; + /** + * Writes the text into the clipboard as plain text. + */ + export function writeText(text: string, type?: string): void; + /** + * @returns The contents of the clipboard as a NativeImage. + */ + export var readImage: typeof GitHubElectron.Clipboard.readImage; + /** + * Writes the image into the clipboard. + */ + export var writeImage: typeof GitHubElectron.Clipboard.writeImage; + /** + * Clears everything in clipboard. + */ + export function clear(type?: string): void; + /** + * Note: This API is experimental and could be removed in future. + * @returns Whether the clipboard has data in the specified format. + */ + export function has(format: string, type?: string): boolean; + /** + * Reads the data in the clipboard of the specified format. + * Note: This API is experimental and could be removed in future. + */ + export function read(format: string, type?: string): any; +} + +declare module 'crash-reporter' { + export function start(options?: { + /** + * Default: Electron + */ + productName?: string; + /** + * Default: GitHub, Inc. + */ + companyName?: string; + /** + * URL that crash reports would be sent to as POST. + * Default: http://54.249.141.255:1127/post + */ + submitUrl?: string; + /** + * Send the crash report without user interaction. + * Default: true. + */ + autoSubmit?: boolean; + /** + * Default: false. + */ + ignoreSystemCrashHandler?: boolean; + /** + * An object you can define which content will be send along with the report. + * Only string properties are send correctly. + * Nested objects are not supported. + */ + extra?: {} + }): void; + + /** + * @returns The date and ID of the last crash report. When there was no crash report + * sent or the crash reporter is not started, null will be returned. + */ + export function getLastCrashReport(): CrashReporterPayload; + + interface CrashReporterPayload extends Object { + /** + * E.g., "electron-crash-service". + */ + rept: string; + /** + * The version of Electron. + */ + ver: string; + /** + * E.g., "win32". + */ + platform: string; + /** + * E.g., "renderer". + */ + process_type: string; + ptime: number; + /** + * The version in package.json. + */ + _version: string; + /** + * The product name in the crashReporter options object. + */ + _productName: string; + /** + * Name of the underlying product. In this case, Electron. + */ + prod: string; + /** + * The company name in the crashReporter options object. + */ + _companyName: string; + /** + * The crashreporter as a file. + */ + upload_file_minidump: File; + } +} + +declare module 'native-image' { + var NativeImage: typeof GitHubElectron.NativeImage; + export = NativeImage; +} + +declare module 'screen' { + var screen: GitHubElectron.Screen; + export = screen; +} + +declare module 'shell' { + /** + * Show the given file in a file manager. If possible, select the file. + */ + export function showItemInFolder(fullPath: string): void; + /** + * Open the given file in the desktop's default manner. + */ + export function openItem(fullPath: string): void; + /** + * Open the given external protocol URL in the desktop's default manner + * (e.g., mailto: URLs in the default mail user agent). + */ + export function openExternal(url: string): void; + /** + * Move the given file to trash and returns boolean status for the operation. + */ + export function moveItemToTrash(fullPath: string): void; + /** + * Play the beep sound. + */ + export function beep(): void; +} + +interface Window { + /** + * Creates a new window. + * @returns An instance of BrowserWindowProxy class. + */ + open(url: string, frameName?: string, features?: string): GitHubElectron.BrowserWindowProxy; +} + +interface File { + /** + * Exposes the real path of the filesystem. + */ + path: string; +} diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts new file mode 100644 index 000000000..ce5251eda --- /dev/null +++ b/gl-matrix/gl-matrix-tests.ts @@ -0,0 +1,357 @@ +/// + +// common +var result: number = glMatrix.toRadian(180); + +var out: GLM.IArray; +var outVal: number; +var outStr: string; + +// vec2 +var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; +var vecArray: GLM.IArray; + +vecA = [1, 2]; +vecB = new Float32Array([3, 4]); +out = [0, 0]; +matA = [1, 2, 3, 4, 5, 6]; +vecArray = [1, 2, 3, 4, 0, 0]; + +out = vec2.create(); +out = vec2.clone(vecA); +out = vec2.fromValues(1, 2); +out = vec2.copy(out, vecA); +out = vec2.set(out, 1, 2); +out = vec2.add(out, vecA, vecB); +out = vec2.subtract(out, vecA, vecB); +out = vec2.sub(out, vecA, vecB); +out = vec2.multiply(out, vecA, vecB); +out = vec2.mul(out, vecA, vecB); +out = vec2.divide(out, vecA, vecB); +out = vec2.div(out, vecA, vecB); +out = vec2.min(out, vecA, vecB); +out = vec2.max(out, vecA, vecB); +out = vec2.scale(out, vecA, 2); +out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec2.distance(vecA, vecB); +outVal = vec2.dist(vecA, vecB); +outVal = vec2.squaredDistance(vecA, vecB); +outVal = vec2.sqrDist(vecA, vecB); +outVal = vec2.length(vecA); +outVal = vec2.len(vecA); +outVal = vec2.squaredLength(vecA); +outVal = vec2.sqrLen(vecA); +out = vec2.negate(out, vecA); +out = vec2.inverse(out, vecA); +out = vec2.normalize(out, vecA); +outVal = vec2.dot(vecA, vecB); +out = vec2.cross(out, vecA, vecB); +out = vec2.lerp(out, vecA, vecB, 0.5); +out = vec2.random(out); +out = vec2.random(out, 5.0); +out = vec2.transformMat2(out, vecA, matA); +out = vec2.transformMat2d(out, vecA, matA); +out = vec2.transformMat3(out, vecA, matA); +out = vec2.transformMat4(out, vecA, matA); +out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vecA); + +// vec3 +var matr: GLM.IArray; +var q: GLM.IArray; + +vecA = [1, 2, 3]; +vecB = new Float32Array([4, 5, 6]); +out = [0, 0, 0]; +vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; +matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + +out = vec3.create(); +out = vec3.clone(vecA); +out = vec3.fromValues(1, 2, 3); +out = vec3.copy(out, vecA); +out = vec3.set(out, 1, 2, 3); +out = vec3.add(out, vecA, vecB); +out = vec3.subtract(out, vecA, vecB); +out = vec3.sub(out, vecA, vecB); +out = vec3.multiply(out, vecA, vecB); +out = vec3.mul(out, vecA, vecB); +out = vec3.divide(out, vecA, vecB); +out = vec3.div(out, vecA, vecB); +out = vec3.min(out, vecA, vecB); +out = vec3.max(out, vecA, vecB); +out = vec3.scale(out, vecA, 2); +out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec3.distance(vecA, vecB); +outVal = vec3.dist(vecA, vecB); +outVal = vec3.squaredDistance(vecA, vecB); +outVal = vec3.sqrDist(vecA, vecB); +outVal = vec3.length(vecA); +outVal = vec3.len(vecA); +outVal = vec3.squaredLength(vecA); +outVal = vec3.sqrLen(vecA); +out = vec3.negate(out, vecA); +out = vec3.inverse(out, vecA); +out = vec3.normalize(out, vecA); +outVal = vec3.dot(vecA, vecB); +out = vec3.cross(out, vecA, vecB); +out = vec3.lerp(out, vecA, vecB, 0.5); +out = vec3.random(out); +out = vec3.random(out, 5.0); +out = vec3.rotateX(out, vecA, vecB, Math.PI); +out = vec3.rotateY(out, vecA, vecB, Math.PI); +out = vec3.rotateZ(out, vecA, vecB, Math.PI); +out = vec3.transformMat3(out, vecA, matr); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; +out = vec3.transformMat4(out, vecA, matr); + +q = [1, 2, 3, 4]; +out = vec3.transformQuat(out, vecA, matr); + +out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vecA, vecB); +outStr = vec3.str(vecA); + +// vec4 +var q: GLM.IArray; + +vecA = [1, 2, 3, 4]; +vecB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +q = [1, 2, 3, 4]; + +out = vec4.create(); +out = vec4.clone(vecA); +out = vec4.fromValues(1, 2, 3, 4); +out = vec4.copy(out, vecA); +out = vec4.set(out, 1, 2, 3, 4); +out = vec4.add(out, vecA, vecB); +out = vec4.subtract(out, vecA, vecB); +out = vec4.sub(out, vecA, vecB); +out = vec4.multiply(out, vecA, vecB); +out = vec4.mul(out, vecA, vecB); +out = vec4.divide(out, vecA, vecB); +out = vec4.div(out, vecA, vecB); +out = vec4.min(out, vecA, vecB); +out = vec4.max(out, vecA, vecB); +out = vec4.scale(out, vecA, 2); +out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec4.distance(vecA, vecB); +outVal = vec4.dist(vecA, vecB); +outVal = vec4.squaredDistance(vecA, vecB); +outVal = vec4.sqrDist(vecA, vecB); +outVal = vec4.length(vecA); +outVal = vec4.len(vecA); +outVal = vec4.squaredLength(vecA); +outVal = vec4.sqrLen(vecA); +out = vec4.negate(out, vecA); +out = vec4.inverse(out, vecA); +out = vec4.normalize(out, vecA); +outVal = vec4.dot(vecA, vecB); +out = vec4.lerp(out, vecA, vecB, 0.5); +out = vec4.random(out); +out = vec4.random(out, 5.0); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] +out = vec4.transformMat4(out, vecA, matr); +out = vec4.transformQuat(out, vecA, q); + +vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; +out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vecA); + +// mat2 +var matB: GLM.IArray, identity: GLM.IArray; + +matA = [1, 2, 3, 4]; +matB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +identity = [1, 0, 0, 1]; + +out = mat2.create(); +out = mat2.clone(matA); +out = mat2.copy(out, matA); +out = mat2.identity(out); +out = mat2.transpose(out, matA); +out = mat2.invert(out, matA); +out = mat2.adjoint(out, matA); +outVal = mat2.determinant(matA); +out = mat2.multiply(out, matA, matB); +out = mat2.mul(out, matA, matB); +out = mat2.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2.scale(out, matA, vecA); +outStr = mat2.str(matA); +outVal = mat2.frob(matA); + +var L = mat2.create(); +var D = mat2.create(); +var U = mat2.create(); +out = mat2.LDU(L, D, U, [4,3,6,3]); + +// mat2d +matA = [1, 2, 3, 4, 5, 6]; +matB = [7, 8, 9, 10, 11, 12]; +out = [0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 1, 0, 0]; + +out = mat2d.create(); +out = mat2d.clone(matA); +out = mat2d.copy(out, matA); +out = mat2d.identity(out); +out = mat2d.invert(out, matA); +outVal = mat2d.determinant(matA); +out = mat2d.multiply(out, matA, matB); +out = mat2d.mul(out, matA, matB); +out = mat2d.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2d.scale(out, matA, vecA); +out = mat2d.translate(out, matA, vecA); +outStr = mat2d.str(matA); +outVal = mat2d.frob(matA); + +// mat3 +matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; +matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; +out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + +out = mat3.create(); +out = mat3.clone(matA); +out = mat3.copy(out, matA); +out = mat3.identity(out); +out = mat3.transpose(out, matA); +out = mat3.invert(out, matA); +out = mat3.adjoint(out, matA); +outVal = mat3.determinant(matA); +out = mat3.multiply(out, matA, matB); +out = mat3.mul(out, matA, matB); +outStr = mat3.str(matA); +outVal = mat3.frob(matA); + +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; +out = mat3.normalFromMat4(out, matA); + +q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; +out = mat3.fromQuat(out, q); + +out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.scale(out, matA, [2,2]); +out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); + +out = mat3.translate(out, matA, [1, 2, 3]); +out = mat3.rotate(out, matA, Math.PI/2); + +// mat4 +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 1, 2, 3, 1]; + +matB = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 4, 5, 6, 1]; + +out = [0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0]; + +identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; + +out = mat4.create(); +out = mat4.clone(matA); +out = mat4.copy(out, matA); +out = mat4.identity(out); +out = mat4.transpose(out, matA); +out = mat4.invert(out, matA); +out = mat4.adjoint(out, matA); +outVal = mat4.determinant(matA); +out = mat4.multiply(out, matA, matB); +out = mat4.mul(out, matA, matB); +out = mat4.translate(out, matA, [4, 5, 6]); +out = mat4.scale(out, matA, [4, 5, 6]); + +var rad = Math.PI * 0.5; +var axis = [1, 0, 0]; +out = mat4.rotate(out, matA, rad, axis); +out = mat4.rotateX(out, matA, rad); +out = mat4.rotateY(out, matA, rad); +out = mat4.rotateZ(out, matA, rad); + +out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); + +var fovy = Math.PI * 0.5; +out = mat4.perspective(out, fovy, 1, 0, 1); +out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); + +var eye = [0, 0, 1]; +var center = [0, 0, -1]; +var up = [0, 1, 0]; +out = mat4.lookAt(out, eye, center, up); + +outStr = mat4.str(matA); +outVal = mat4.frob(matA); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); +out = mat4.fromQuat(out, q); + +// quat +var quatA = [1, 2, 3, 4]; +var quatB = [5, 6, 7, 8]; +out = [0, 0, 0, 0]; +var vec = [1, 1, -1]; +var id = [0, 0, 0, 1]; +var deg90 = Math.PI / 2; + +out = quat.create(); +out = quat.clone(quatA); +out = quat.fromValues(1, 2, 3, 4); +out = quat.copy(out, quatA); +out = quat.set(out, 1, 2, 3, 4); +out = quat.identity(out); +out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); +out = quat.add(out, quatA, quatB); +out = quat.multiply(out, quatA, quatB); +out = quat.mul(out, quatA, quatB); +out = quat.scale(out, quatA, 2); +outVal = quat.length(quatA); +outVal = quat.len(quatA); +outVal = quat.squaredLength(quatA); +outVal = quat.sqrLen(quatA); +out = quat.normalize(out, quatA); +outVal = quat.dot(out, quatA, quatB); +out = quat.lerp(out, quatA, quatB, 0.5); +out = quat.slerp(out, quatA, quatB, 0.5); +out = quat.invert(out, quatA); +out = quat.conjugate(out, quatA); +outStr = quat.str(quatA); +out = quat.rotateX(out, id, deg90); +out = quat.rotateY(out, id, deg90); +out = quat.rotateZ(out, id, deg90); + +matr = [ 1, 0, 0, + 0, 0, -1, + 0, 1, 0 ]; +out = quat.fromMat3(out, matr); + +var view = [-1, 0, 0]; +up = [ 0, 1, 0]; +var right= [ 0, 0,-1]; +out = quat.setAxes([], view, right, up); + +out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); +out = quat.calculateW(out, quatA); + diff --git a/gl-matrix/gl-matrix.d.ts b/gl-matrix/gl-matrix.d.ts new file mode 100644 index 000000000..392a39220 --- /dev/null +++ b/gl-matrix/gl-matrix.d.ts @@ -0,0 +1,2144 @@ +// Type definitions for gl-matrix 2.2.2 +// Project: https://github.com/toji/gl-matrix +// Definitions by: Tat +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module GLM { + interface IArray + { + /** + * Must be indexable like an array + */ + [index: number]: number; + } +} + +// Common +declare module glMatrix { + /** + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + export function toRadian(a: number): number; +} + +// vec2 +declare module vec2 { + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + export function fromValues(x: number, y: number): GLM.IArray; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec3 +declare module vec3 { + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + export function fromValues(x: number, y: number, z: number): GLM.IArray; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + export function angle(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec4 +declare module vec4 { + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// mat2 +declare module mat2 { + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; +} + +// mat2d +declare module mat2d { + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; +} + +// mat3 +declare module mat3 { + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param out the receiving 3x3 matrix + * @param a the source 4x4 matrix + * @returns out + */ + export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; +} + +// mat4 +declare module mat4 { + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(a: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function frustum(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function perspective(out: GLM.IArray, fovy: number, aspect: number, + near: number, far: number): GLM.IArray; + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function ortho(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + export function lookAt(out: GLM.IArray, eye: GLM.IArray, + center: GLM.IArray, up: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, + v: GLM.IArray): GLM.IArray; + + /** + * Creates a matrix from a quaternion + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; +} + +// quat +declare module quat { + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + export function create(): GLM.IArray; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a quatenion + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, + up: GLM.IArray): GLM.IArray; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; +} \ No newline at end of file diff --git a/googlemaps/google.maps-tests.ts b/googlemaps/google.maps-tests.ts new file mode 100644 index 000000000..1079f78b2 --- /dev/null +++ b/googlemaps/google.maps-tests.ts @@ -0,0 +1,107 @@ +// Test file for Google Maps JavaScript API Definition file +/// + +var map = new google.maps.Map(document.querySelector("☺")); + +/***** Data *****/ + +new google.maps.Data(); +new google.maps.Data({ map: map }); + +var latLng = new google.maps.LatLng(52.201203, -1.724370), + feature = new google.maps.Data.Feature(), + geometry = new google.maps.Data.Geometry(); + +var data = map.data; + +data.add(feature); + +data.add({ + geometry: latLng, + id: "Test feature", + properties: {} +}); + +var isIn: boolean = map.data.contains(feature); + +data.forEach((feature: google.maps.Data.Feature) => { + console.log(feature.getId()); +}); + +var map: google.maps.Map = data.getMap(); +data.setMap(map); + +var style = data.getStyle(); +data.setStyle(style); + +data.setStyle({ + clickable: true, + cursor: "pointer", + fillColor: "#79B55B", + fillOpacity: 1, + icon: {}, + shape: { coords: [1, 2, 3], type: "circle" }, + strokeColor: "#79B55B", + strokeOpacity: 1, + strokeWeight: 1, + title: "string", + visible: true, + zIndex: 1 +}); + +data.overrideStyle(feature, { visible: true }); + +data.revertStyle(feature); + +data.addGeoJson({}); +data.addGeoJson({}, { idPropertyName: "Test feature" }); + +data.loadGeoJson("http://magicGeoJsonSource.com"); + +data.loadGeoJson( + "http://magicGeoJsonSource.com", + { idPropertyName: "test" }); + +data.loadGeoJson( + "http://magicGeoJsonSource.com", + { idPropertyName: "test" }, + (features) => { + for (var i = 0, len = features.length; i < len; i++) { + console.log(features[i].getId()); + } + }); + +data.toGeoJson((feature) => { }); + +var dataMouseEvent: google.maps.Data.MouseEvent = { + feature: feature, + latLng: latLng, + stop: (): void => {} +}; + +var addFeatureEvent : google.maps.Data.AddFeatureEvent = { + feature: feature +}; + +var removeFeatureEvent: google.maps.Data.RemoveFeatureEvent = { + feature: feature +}; + +var setGeometryEvent: google.maps.Data.SetGeometryEvent = { + feature: feature, + newGeometry: geometry, + oldGeometry: geometry, +}; + +var setPropertyEvent: google.maps.Data.SetPropertyEvent = { + feature: feature, + name: "test", + newValue: {}, + oldValue: {} +}; + +var removePropertyEvent: google.maps.Data.RemovePropertyEvent = { + feature: feature, + name: "test", + oldValue: {} +}; \ No newline at end of file diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 3ba451c8a..fe4e7459c 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Google Geolocation 0.4.8 +// Type definitions for Google Maps JavaScript API 3.19 // Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S +// Definitions by: Folia A/S , Chris Wrench // Definitions: https://github.com/borisyankov/DefinitelyTyped /* @@ -80,9 +80,10 @@ declare module google.maps { setStreetView(panorama: StreetViewPanorama): void; setTilt(tilt: number): void; setZoom(zoom: number): void; - controls: MVCArray[]; //Array.> + controls: MVCArray[]; //Array> + data: Data; mapTypes: MapTypeRegistry; - overlayMapTypes: MVCArray; // MVCArray. + overlayMapTypes: MVCArray; // MVCArray } export interface MapOptions { @@ -206,6 +207,159 @@ declare module google.maps { ZOOM_PAN } + /***** Data *****/ + export class Data extends MVCObject { + constructor(options?: Data.DataOptions); + add(feature: Data.Feature|Data.FeatureOptions): Data.Feature; + addGeoJson(geoJson: Object, options?: Data.GeoJsonOptions): Data.Feature[]; + contains(feature: Data.Feature): boolean; + forEach(callback: (feature: Data.Feature) => void): void; + getFeatureById(id: number|string): Data.Feature; + getMap(): Map; + getStyle(): Data.StylingFunction|Data.StyleOptions; + loadGeoJson(url: string, options?: Data.GeoJsonOptions, callback?: (features: Data.Feature[]) => void): void; + overrideStyle(feature: Data.Feature, style: Data.StyleOptions): void; + remove(feature: Data.Feature): void; + revertStyle(feature?: Data.Feature): void; + setMap(map: Map): void; + setStyle(style: Data.StylingFunction|Data.StyleOptions): void; + toGeoJson(callback: (feature: Object) => void): void; + } + + export module Data { + export interface DataOptions { + map?: Map; + style?: Data.StylingFunction|Data.StyleOptions; + } + + export interface GeoJsonOptions { + idPropertyName?: string; + } + + export interface StyleOptions { + clickable?: boolean; + cursor?: string; + fillColor?: string; + fillOpacity?: number; + icon?: any; // TODO string|Icon|Symbol; + shape?: MarkerShape; + strokeColor?: string; + strokeOpacity?: number; + strokeWeight?: number; + title?: string; + visible?: boolean; + zIndex?: number; + } + + export type StylingFunction = (feature: Data.Feature) => Data.StyleOptions; + + export class Feature { + constructor(options?: Data.FeatureOptions); + forEachProperty(callback: (value: any, name: string) => void): void; + getGeometry(): Data.Geometry; + getId(): number|string; + getProperty(name: string): any; + removeProperty(name: string): void; + setGeometry(newGeometry: Data.Geometry|LatLng): void; // TODO LatLngLiteral + setProperty(name: string, newValue: any): void + toGeoJson(callback: (feature: Object) => void): void + } + + export interface FeatureOptions { + geometry?: Data.Geometry|LatLng; // TODO LatLngLiteral + id?: number|string; + properties?: Object; + } + + export class Geometry { + getType(): string; + } + + export class Point extends Data.Geometry { + constructor(latLng: LatLng); // TODO LatLngLiteral + get(): LatLng; + } + + export class MultiPoint extends Data.Geometry { + constructor(elements: LatLng[]); // TODO LatLngLiteral + getAt(n: number): LatLng; + getLength(): number; + } + + export class LineString extends Data.Geometry { + constructor(elements: LatLng[]); // TODO LatLngLiteral + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class MultiLineString extends Data.Geometry { + constructor(elements: Data.LineString[]|LatLng[]); // TODO LatLngLiteral + getArray(): Data.LineString[]; + getAt(n: number): Data.LineString; + getLength(): number; + } + + export class LinearRing extends Data.Geometry { + constructor(elements: LatLng[]); // TODO LatLngLiteral + getArray(): LatLng[]; + getAt(n: number): LatLng; + getLength(): number; + } + + export class Polygon extends Data.Geometry { + constructor(elements: LinearRing[]|LatLng[][]); // TODO LatLngLiteral + getArray(): LinearRing[]; + getAt(n: number): LinearRing; + getLength(): number; + } + + export class MultiPolygon extends Data.Geometry { + constructor(elements: Data.Polygon[]|LinearRing[][]|LatLng[][][]); // TODO LatLngLiteral + getArray(): Data.Polygon[]; + getAt(n: number): Data.Polygon; + getLength(): number; + } + + export class GeometryCollection extends Data.Geometry { + constructor(elements: Data.Geometry[]|LatLng[]); // TODO LatLngLiteral + getArray(): Data.Geometry[]; + getAt(n: number): Data.Geometry; + getLength(): number; + } + + export interface MouseEvent extends google.maps.MouseEvent { + feature: Data.Feature; + } + + export interface AddFeatureEvent { + feature: Data.Feature; + } + + export interface RemoveFeatureEvent { + feature: Data.Feature; + } + + export interface SetGeometryEvent { + feature: Data.Feature; + newGeometry: Data.Geometry; + oldGeometry: Data.Geometry; + } + + export interface SetPropertyEvent { + feature: Data.Feature; + name: string; + newValue: any; + oldValue: any; + } + + export interface RemovePropertyEvent { + feature: Data.Feature; + name: string; + oldValue: any; + } + } + /***** Overlays *****/ export class Marker extends MVCObject { static MAX_ZINDEX: number; @@ -470,7 +624,7 @@ declare module google.maps { visible?: boolean; zIndex?: number; } - + export enum StrokePosition { CENTER, INSIDE, @@ -1345,54 +1499,54 @@ declare module google.maps { } export module places { - - export class AutocompleteService extends MVCObject { - constructor(); - getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void; - getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void; - } - - export interface AutocompletionRequest { - input: string; - bounds?: LatLngBounds; - componentRestrictions?: ComponentRestrictions; - location?: LatLng; - offset?: number; - radius?: number; - types?: string[]; - } - - export interface QueryAutocompletionRequest { - input: string; - bounds?: LatLngBounds; - location?: LatLng; - offset?: number; - radius?: number; - } - - export interface AutocompletePrediction { - description: string; - matched_substrings: PredictionSubstring[]; - place_id: string; - terms: PredictionTerm[]; - types: string[] - } - - export interface PredictionTerm { - offset: number; - value: string; - } - - export interface PredictionSubstring { - length: number; - offset: number; - } - - export interface QueryAutocompletePrediction { - description: string; - matched_substrings: PredictionSubstring[]; - place_id: string; - terms: PredictionTerm[]; + + export class AutocompleteService extends MVCObject { + constructor(); + getPlacePredictions(request: AutocompletionRequest, callback: (result: AutocompletePrediction[], status: PlacesServiceStatus) => void): void; + getQueryPredictions(request: QueryAutocompletionRequest, callback: (result: QueryAutocompletePrediction[], status: PlacesServiceStatus) => void): void; + } + + export interface AutocompletionRequest { + input: string; + bounds?: LatLngBounds; + componentRestrictions?: ComponentRestrictions; + location?: LatLng; + offset?: number; + radius?: number; + types?: string[]; + } + + export interface QueryAutocompletionRequest { + input: string; + bounds?: LatLngBounds; + location?: LatLng; + offset?: number; + radius?: number; + } + + export interface AutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + terms: PredictionTerm[]; + types: string[] + } + + export interface PredictionTerm { + offset: number; + value: string; + } + + export interface PredictionSubstring { + length: number; + offset: number; + } + + export interface QueryAutocompletePrediction { + description: string; + matched_substrings: PredictionSubstring[]; + place_id: string; + terms: PredictionTerm[]; } export class Autocomplete extends MVCObject { @@ -1414,8 +1568,19 @@ declare module google.maps { country: string; } + export interface PhotoOptions { + maxHeight?: number; + maxWidth?: number; + } + + export interface PlaceAspectRating { + rating: number; + type: string; + } + export interface PlaceDetailsRequest { - reference: string; + placeId: string; + reference?: string; } export interface PlaceGeometry { @@ -1423,29 +1588,53 @@ declare module google.maps { viewport: LatLngBounds; } + export interface PlacePhoto { + height: number; + html_attributions: string[]; + width: number; + getUrl(opts: PhotoOptions): string; + } + export interface PlaceResult { address_components: GeocoderAddressComponent[]; + aspects: PlaceAspectRating[]; formatted_address: string; formatted_phone_number: string; geometry: PlaceGeometry; html_attributions: string[]; icon: string; - id: string; + id?: string; international_phone_number: string; name: string; + permanently_closed: boolean; + photos: PlacePhoto[]; + place_id: string; + price_level: number; rating: number; - reference: string; + reference?: string; + reviews: PlaceReview[]; types: string[]; url: string; vicinity: string; website: string; } + export interface PlaceReview { + aspects: PlaceAspectRating[]; + author_name: string; + author_url: string; + language: string; + text: string; + } + export interface PlaceSearchRequest { bounds: LatLngBounds; keyword: string; location: LatLng; + maxPriceLevel?: number; + minPriceLevel?: number; name: string; + openNow: boolean; radius: number; rankBy: RankBy; types: string[]; @@ -1461,6 +1650,7 @@ declare module google.maps { constructor (attrContainer: Map); getDetails(request: PlaceDetailsRequest, callback: (result: PlaceResult, status: PlacesServiceStatus) => void ): void; nearbySearch(request: PlaceSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus, pagination: PlaceSearchPagination) => void ): void; + radarSearch(request: RadarSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void ): void; textSearch(request: TextSearchRequest, callback: (results: PlaceResult[], status: PlacesServiceStatus) => void ): void; } @@ -1473,27 +1663,37 @@ declare module google.maps { ZERO_RESULTS } + export interface RadarSearchRequest { + bounds: LatLngBounds; + keyword: string; + location: LatLng; + name: string; + radius: number; + types: string[]; + } + export enum RankBy { DISTANCE, PROMINENCE } - - export class SearchBox { - constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions); - getBounds(): LatLngBounds; - setBounds(bounds: LatLngBounds): void; - getPlaces(): PlaceResult[]; - } - export interface SearchBoxOptions { - bounds: LatLngBounds; - } + export class SearchBox extends MVCObject { + constructor(inputField: HTMLInputElement, opts?: SearchBoxOptions); + getBounds(): LatLngBounds; + setBounds(bounds: LatLngBounds): void; + getPlaces(): PlaceResult[]; + } + + export interface SearchBoxOptions { + bounds: LatLngBounds; + } export interface TextSearchRequest { bounds: LatLngBounds; location: LatLng; query: string; radius: number; + types: string[]; } } @@ -1643,6 +1843,6 @@ declare module google.maps { export class MapsEventListener { - } + } } } diff --git a/greensock/greensock.d.ts b/greensock/greensock.d.ts index a9a46d113..a43c0d77f 100644 --- a/greensock/greensock.d.ts +++ b/greensock/greensock.d.ts @@ -1,167 +1,169 @@ -// Type definitions for GreenSock Animation Platform 1.1 +// Type definitions for GreenSock Animation Platform 1.15.1 // Project: http://www.greensock.com/get-started-js/ // Definitions by: Robert S // Definitions: https://github.com/borisyankov/DefinitelyTyped // JavaScript Docs http://api.greensock.com/js/ -// Version 1.1 (TypeScript 0.9) +// Version 1.15.1 (TypeScript 1.4) interface IDispatcher { addEventListener(type:string, callback:Function, scope?:Object, useParam?:boolean, priority?:number):void; removeEventListener(type:string, callback:Function):void; } +declare type Tween = TweenLite | TweenMax; +declare type Timeline = SimpleTimeline | TimelineLite | TimelineMax; + //com.greensock.core declare class Animation { - data:any; - static ticker:IDispatcher; - timeline:SimpleTimeline; - vars:Object; + static ticker: IDispatcher; + data: any; + timeline: SimpleTimeline; + vars: Object; - constructor(duration?:number, vars?:Object); + constructor(duration?: number, vars?: Object); - delay(value:number):any; - duration(value:number):any; - eventCallback(type:string, callback?:Function, params?:any[], scope?:any):any; - invalidate():any; - isActive():boolean; - kill(vars?:Object, target?:Object):any; - pause(atTime?:any, suppressEvents?:boolean):any; - paused(value?:boolean):any; - play(from?:any, suppressEvents?:boolean):any; - restart(includeDelay?:boolean, suppressEvents?:boolean):any; - resume(from?:any, suppressEvents?:boolean):any; - reverse(from?:any, suppressEvents?:boolean):any; - reversed(value?:boolean):any; - seek(time:any, suppressEvents?:boolean):any; - startTime(value:number):any; - time(value:number, suppressEvents?:boolean):any; - timeScale(value:number):any; - totalDuration(value:number):any; - totalTime(time:number, suppressEvents?:boolean):any; + delay(): number; + delay(value: number): Animation; + duration(): number; + duration(value: number): Animation; + eventCallback(type: string): Function; + eventCallback(type: string, callback: Function, params?: any[], scope?: any): Animation; + invalidate(): Animation; + isActive(): boolean; + kill(vars?: Object, target?: Object): Animation; + pause(atTime?: any, suppressEvents?: boolean): Animation; + paused(): boolean; + paused(value: boolean): Animation; + play(from?: any, suppressEvents?: boolean): Animation; + progress(): number; + progress(value: number, supressEvents?: boolean): Animation; + restart(includeDelay?: boolean, suppressEvents?: boolean): Animation; + resume(from?: any, suppressEvents?: boolean): Animation; + reverse(from?: any, suppressEvents?: boolean): Animation; + reversed(): boolean; + reversed(value: boolean): Animation; + seek(time: any, suppressEvents?: boolean): Animation; + startTime(): number; + startTime(value: number): Animation; + time(): number; + time(value: number, suppressEvents?: boolean): Animation; + timeScale(): number; + timeScale(value: number): Animation; + totalDuration(): number; + totalDuration(value: number): Animation; + totalProgress(): number; + totalProgress(value: number): Animation; + totalTime(): number; + totalTime(time: number, suppressEvents?: boolean): Animation; } declare class SimpleTimeline extends Animation { - autoRemoveChildren:boolean; - smoothChildTiming:boolean; + autoRemoveChildren: boolean; + smoothChildTiming: boolean; - constructor(vars?:Object); + constructor(vars?: Object); - add(value:any, position?:any, align?:string, stagger?:number):any; - insert(tween:any, time:any):any; - render(time:number, suppressEvents?:boolean, force?:boolean):void; + add(value: any, position?: any, align?: string, stagger?: number): SimpleTimeline; + render(time: number, suppressEvents?: boolean, force?: boolean): void; } //com.greensock declare class TweenLite extends Animation { - static defaultEase:Ease; - static defaultOverwrite:string; - static selector:any; - target:Object; - static ticker:IDispatcher; - timeline:SimpleTimeline; - vars:Object; + static defaultEase: Ease; + static defaultOverwrite: string; + static selector: any; + target: Object; - constructor(target:Object, duration:number, vars:Object); + constructor(target: Object, duration: number, vars: Object); - static delayedCall(delay:number, callback:Function, params?:any[], scope?:any, useFrames?:boolean):TweenLite; - static from(target:Object, duration:number, vars:Object):TweenLite; - static fromTo(target:Object, duration:number, fromVars:Object, toVars:Object):TweenLite; - static getTweensOf(target:Object):any[]; - invalidate():any; - static killDelayedCallsTo(func:Function):void; - static killTweensOf(target:Object, vars?:Object):void; - static set(target:Object, vars:Object):TweenLite; - static to(target:Object, duration:number, vars:Object):TweenLite; + static delayedCall(delay: number, callback: Function, params?: any[], scope?: any, useFrames?: boolean): TweenLite; + endTime(includeRepeats?: boolean): number; + static from(target: Object | Object[], duration: number, vars: Object): TweenLite; + static fromTo(target: Object | Object[], duration: number, fromVars: Object, toVars: Object): TweenLite; + static getTweensOf(target: Object, onlyActive: boolean): Tween[]; + static killDelayedCallsTo(func: Function): void; + static killTweensOf(target: Object, onlyActive?: boolean, vars?: Object): void; + static lagSmoothing(threshold: number, adjustedLag: number): void; + static set(target: Object, vars: Object): TweenLite; + static to(target: Object, duration: number, vars: Object): TweenLite; } declare class TweenMax extends TweenLite { - static ticker:IDispatcher; + constructor(target: Object, duration: number, vars: Object); - constructor(target:Object, duration:number, vars:Object); - - static delayedCall(delay:number, callback:Function, params?:any[], scope?:any, useFrames?:boolean):TweenMax; - static from(target:Object, duration:number, vars:Object):TweenMax; - static fromTo(target:Object, duration:number, fromVars:Object, toVars:Object):TweenMax; - static getAllTweens(includeTimelines?:boolean):any[]; - static getTweensOf(target:Object):any[]; - invalidate():any; - static isTweening(target:Object):boolean; - static killAll(complete?:boolean, tweens?:boolean, delayedCalls?:boolean, timelines?:boolean):void; - static killChildTweensOf(parent:any, complete?:boolean):void; - static killDelayedCallsTo(func:Function):void; - static killTweensOf(target:Object, vars?:Object):void; - static pauseAll(tweens?:boolean, delayedCalls?:boolean, timelines?:boolean):void; - progress(value:number):any; - repeat(value:number):any; - repeatDelay(value:number):any; - static resumeAll(tweens?:boolean, delayedCalls?:boolean, timelines?:boolean):void; - static set(target:Object, vars:Object):TweenMax; - static staggerFrom(targets:any, duration:number, vars:Object, stagger:number, onCompleteAll?:Function, onCompleteAllParams?:any[], onCompleteAllScope?:any):any[]; - static staggerFromTo(targets:any, duration:number, fromVars:Object, toVars:Object, stagger:number, onCompleteAll?:Function, onCompleteAllParams?:any[], onCompleteAllScope?:any):any[]; - static staggerTo(targets:any, duration:number, vars:Object, stagger:number, onCompleteAll?:Function, onCompleteAllParams?:any[], onCompleteAllScope?:any):any[]; - time(value:number, suppressEvents?:boolean):any; + static delayedCall(delay: number, callback: Function, params?: any[], scope?: Object, useFrames?: boolean): TweenMax; + static from(target: Object, duration: number, vars: Object): TweenMax; + static fromTo(target: Object, duration: number, fromVars: Object, toVars: Object): TweenMax; + static getAllTweens(includeTimelines?: boolean): Tween[]; + static getTweensOf(target: Object): Tween[]; + static isTweening(target: Object): boolean; + static killAll(complete?: boolean, tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; + static killChildTweensOf(parent: any, complete?: boolean): void; + static killDelayedCallsTo(func: Function): void; + static killTweensOf(target: Object, vars?: Object): void; + static pauseAll(tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; + repeat(): number; + repeat(value: number): TweenMax; + repeatDelay(): number; + repeatDelay(value: number): TweenMax; + static resumeAll(tweens?: boolean, delayedCalls?: boolean, timelines?: boolean): void; + static set(target: Object, vars: Object): TweenMax; + static staggerFrom(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + static staggerFromTo(targets: any, duration: number, fromVars: Object, toVars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; + static staggerTo(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; static to(target:Object, duration:number, vars:Object):TweenMax; - totalDuration(value:number):any; - totalProgress(value:number):any; - updateTo(vars:Object, resetDuration?:boolean):any; - yoyo(value?:boolean):any; + updateTo(vars: Object, resetDuration?: boolean): TweenMax; + yoyo(): boolean; + yoyo(value?: boolean): TweenMax; } declare class TimelineLite extends SimpleTimeline { - constructor(vars?:Object); + constructor(vars?: Object); - add(value:any, position?:any, align?:string, stagger?:number):any; - addLabel(label:string, position:any):any; - addPause(position?:any, callback?:Function, params?:any[], scope?:any):any; - append(value:any, offsetOrLabel?:any):any; - appendMultiple(tweens:any[], offsetOrLabel?:any, align?:string, stagger?:number):any; - call(callback:Function, params?:any[], scope?:any, position?:any):any; - clear(labels?:boolean):any; - duration(value:number):any; - exportRoot(vars?:Object, omitDelayedCalls?:boolean):TimelineLite; - from(target:Object, duration:number, vars:Object, position?:any):any; - fromTo(target:Object, duration:number, fromVars:Object, toVars:Object, position?:any):any; - getChildren(nested?:boolean, tweens?:boolean, timelines?:boolean, ignoreBeforeTime?:number):any[]; - getLabelTime(label:string):number; - getTweensOf(target:Object, nested?:boolean):any[]; - insert(value:any, timeOrLabel?:any):any; - insertMultiple(tweens:any[], timeOrLabel?:any, align?:string, stagger?:number):any; - invalidate():any; - progress(value:number):any; - remove(value:any):any; - removeLabel(label:string):any; - set(target: Object, vars: Object, position?:any):any; - seek(position:any, suppressEvents?:boolean):any; - shiftChildren(amount:number, adjustLabels?:boolean, ignoreBeforeTime?:number):any; - staggerFrom(targets:any, duration:number, vars:Object, stagger?:number, position?:any, onCompleteAll?:Function, onCompleteAllParams?:any[], onCompleteScope?:any):any; - staggerFromTo(targets:any, duration:number, fromVars:Object, toVars:Object, stagger?:number, position?:any, onCompleteAll?:Function, onCompleteAllParams?:any[], onCompleteAllScope?:any):any; - staggerTo(targets:any, duration:number, vars:Object, stagger:number, position?:any, onCompleteAll?:Function, onCompleteAllParams?:any[], onCompleteAllScope?:any):any; - stop():any; - to(target:Object, duration:number, vars:Object, position?:any):any; - usesFrames():Boolean; + add(value: any, position?: any, align?: string, stagger?: number): TimelineLite; + addLabel(label: string, position: any): TimelineLite; + addPause(position?: any, callback?: Function, params?: any[], scope?: any): TimelineLite; + call(callback: Function, params?: any[], scope?: any, position?: any): TimelineLite; + clear(labels?: boolean): TimelineLite; + endTime(includeRepeats?: boolean): number; + static exportRoot(vars?: Object, omitDelayedCalls?: boolean): TimelineLite; + from(target: Object, duration: number, vars: Object, position?: any): TimelineLite; + fromTo(target: Object, duration: number, fromVars: Object, toVars: Object, position?: any): TimelineLite; + getChildren(nested?: boolean, tweens?: boolean, timelines?: boolean, ignoreBeforeTime?: number): Tween | Timeline[]; + getLabelTime(label: string): number; + getTweensOf(target: Object, nested?: boolean): Tween[]; + recent(): Animation; + remove(value: any): TimelineLite; + removeLabel(label: string): any; + set(target: Object, vars: Object, position?: any): TimelineLite; + shiftChildren(amount: number, adjustLabels?: boolean, ignoreBeforeTime?: number): TimelineLite; + staggerFrom(targets: any, duration: number, vars: Object, stagger?: number, position?: any, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteScope?: any): TimelineLite; + staggerFromTo(targets: any, duration: number, fromVars: Object, toVars: Object, stagger?: number, position?: any, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; + staggerTo(targets: any, duration: number, vars: Object, stagger: number, position?: any, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): TimelineLite; + to(target: Object, duration: number, vars: Object, position?: any): TimelineLite; + usesFrames(): boolean; } declare class TimelineMax extends TimelineLite { - constructor(vars?:Object); + constructor(vars?: Object); - addCallback(callback:Function, position:any, params?:any[], scope?:any):TimelineMax; - currentLabel(value?:string):any; - getActive(nested?:boolean, tweens?:boolean, timelines?:boolean):any[]; - getLabelAfter(time:number):string; - getLabelBefore(time:number):string; - getLabelsArray():any[]; - invalidate():any; - progress(value:number):any; - removeCallback(callback:Function, timeOrLabel?:any):TimelineMax; - repeat(value?:number):any; - repeatDelay(value?:number):any; - time(value:number, suppressEvents?:boolean):any; - totalDuration(value:number):any; - totalProgress(value:number):any; - tweenFromTo(fromPosition:any, toPosition:any, vars?:Object):TweenLite; - tweenTo(position:any, vars?:Object):TweenLite; - yoyo(value?:boolean):any; + addCallback(callback: Function, position: any, params?: any[], scope?: any): TimelineMax; + currentLabel(): string; + currentLabel(value: string): TimelineMax; + getActive(nested?: boolean, tweens?: boolean, timelines?: boolean): Tween | Timeline[]; + getLabelAfter(time: number): string; + getLabelBefore(time: number): string; + getLabelsArray(): any[]; + removeCallback(callback: Function, timeOrLabel?: any): TimelineMax; + repeat(): number; + repeat(value: number): TimelineMax; + repeatDelay(): number; + repeatDelay(value: number): TimelineMax; + tweenFromTo(fromPosition: any, toPosition: any, vars?: Object): TweenLite; + tweenTo(position: any, vars?: Object): TweenLite; + yoyo(): boolean; + yoyo(value: boolean): TimelineMax; } //com.greensock.easing diff --git a/irc/irc-tests.ts b/irc/irc-tests.ts new file mode 100644 index 000000000..edda5e14f --- /dev/null +++ b/irc/irc-tests.ts @@ -0,0 +1,54 @@ +/// +// https://github.com/martynsmith/node-irc/blob/master/example/bot.js + +import irc = require('irc'); + +var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', { + debug: true, + channels: ['#blah', '#test'] +}); + +bot.addListener('error', ((message: irc.IMessage) => { + console.error('ERROR: %s: %s', message.command, message.args.join(' ')); +})); + +bot.addListener('message#blah', ((from: string, message: string) => { + console.log('<%s> %s', from, message); +})); + +bot.addListener('message', ((from: string, to: string, message: string) => { + console.log('%s => %s: %s', from, to, message); + + if (to.match(/^[#&]/)) { + // channel message + if (message.match(/hello/i)) { + bot.say(to, 'Hello there ' + from); + } + if (message.match(/dance/)) { + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000); + } + } + else { + // private message + console.log('private message'); + } +})); + +bot.addListener('pm', ((nick: string, message: string) => { + console.log('Got private message from %s: %s', nick, message); +})); + +bot.addListener('join', ((channel: string, who: string) => { + console.log('%s has joined %s', who, channel); +})); + +bot.addListener('part', ((channel: string, who: string, reason: string) => { + console.log('%s has left %s: %s', who, channel, reason); +})); + +bot.addListener('kick', ((channel: string, who: string, by: string, reason: string) => { + console.log('%s was kicked from %s by %s: %s', who, channel, by, reason); +})); diff --git a/irc/irc.d.ts b/irc/irc.d.ts new file mode 100644 index 000000000..11f14ab6f --- /dev/null +++ b/irc/irc.d.ts @@ -0,0 +1,879 @@ +// Type definitions for irc v0.3.12 +// Project: https://github.com/martynsmith/node-irc +// Definitions by: phillips1012 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** This library provides IRC client functionality. */ +declare module 'irc' { + import events = require('events'); + import crypto = require('crypto'); + import net = require('net'); + + /** This library provides IRC client functionality. */ + module NodeIRC { + /** A nick connect to an IRC server. */ + export class Client extends events.EventEmitter { + /** + * Socket to the server. Rarely, if ever needed. Use Client#send + * instead. + */ + public conn: net.Socket + + /** + * Channels joined. Includes channel modes, user list, and topic + * information. Only updated after the server recognizes the join. + */ + public chans: { + [index: string]: { + key: string; + serverName: string; + users: { + [index: string]: string; + }; + mode: string; + created: string; + } + } + + /** Features supported by the server */ + public supported: { + channel: { + idlength: string[]; + length: number; + limit: string[]; + modes: { + [index: string]: string; + } + types: string; + }; + + kicklength: number; + maxlist: number[]; + maxtargets: string[]; + modes: number; + nicklength: number + topiclength: number; + usermodes: string; + } + + /** + * The current nick of the client. Updated if the nick changes + */ + public nick: string; + + /** Channel listing data. */ + public channellist: IChannel[]; + + /** IRC server MOTD */ + public motd: string; + + /** Maximum line length */ + public maxLineLength: number; + + /** Bot options */ + public opt: IClientOpts; + + /** Host mask */ + public hostMask: string; + + /** + * Connect to an IRC server + * @param server - server hostname + * @param nick - nickname + * @param opts + */ + constructor( + server: string, + nick: string, + opts?: IClientOpts + ); + + /** + * Send a raw message to the server; generally speaking, it’s best + * not to use this method unless you know what you’re doing. + * @param command - irc command + * @param args - command arguments (splat) + */ + public send( + command: string, + ...args: string[] + ): void; + + /** + * Join the specified channel + * @param channel - channel to join + * @param callback + */ + public join( + channel: string, + callback?: handlers.IJoinChannel + ): void; + + /** + * Part the specified channel + * @param channel - channel to part + * @param message - optional message to send + * @param callback + */ + public part( + channel: string, + message: string, + callback: handlers.IPartChannel + ): void; + + /** + * Send a message to the specified target + * @param target - nick or channel + * @param message - message to send + */ + public say( + target: string, + message: string + ): void; + + /** + * Send a CTCP message to the specified target + * @param target - nick or channel + * @param type - "privmsg" for PRIVMSG, anything else for NOTICE + * @param text - CTCP message + */ + public ctcp( + target: string, + type: string, + text: string + ): void; + + /** + * Send an action to the specified target + * @param target - target + * @param message - message + */ + public action( + target: string, + message: string + ): void; + + /** + * Send a notice to the specified target. + * @param target - nick or channel + * @param message - message to send + */ + public notice( + target: string, + message: string + ): void; + + /** + * Request a whois for the specified nick + * @param nick - nickname + * @param callback + */ + public whois( + nick: string, + callback: handlers.IWhois + ): void; + + /** + * Request a channel listing from the server. The arguments for this + * are farily server specific, this method passes them as specified. + * + * Responses from the server are available via `channellist_start`, + * `channellist_item`, and `channellist` events. + * + * @param args - arguments + */ + public list( + ...args: string[] + ): void; + + /** + * Connect to the server. Use when `autoConnect` is false. + * @param retryCount - times to retry + * @param callback + */ + public connect( + retryCount?: number, + callback?: handlers.IRaw + ): void; + + /** + * Disconnect from the IRC server + * @param message - message to send + * @param callback + */ + public disconnect( + message: string, + callback: () => void + ): void; + + /** + * Activate flood protection “after the fact”. You can also use + * floodProtection while instantiating the Client to enable flood + * protection, and floodProtectionDelay to set the default message + * interval. + * @param interval - ms to wait between messages + */ + public activateFloodProtection( + interval: number + ): void; + } + + /** Client options object */ + export interface IClientOpts { + /** + * IRC username + * @default 'nodebot' + */ + userName?: string; + + /** + * IRC "real name" + * @default 'nodeJS IRC client' + */ + realName?: string; + + /** + * IRC connection port. See + * https://nodejs.org/api/net.html#net_socket_remoteport + * @default 6667 + */ + port?: number; + + /** + * Local interface to bind to for network connections. See + * https://nodejs.org/api/net.html#net_socket_localaddress + */ + localAddress?: string; + + /** + * Should we output debug messages to STDOUT? + * @default false + */ + debug?: boolean; + + /** + * Should we output IRC errors? + * @default false + */ + showErrors?: boolean; + + /** + * Should we auto-rejoin channels? + * @default false + */ + autoRejoin?: boolean; + + /** + * Should we auto-reconnect to networks? + * @default true + */ + autoConnect?: boolean; + + /** + * Channels to join + * @default [] + */ + channels?: string[]; + + /** + * Should SSL be used? Can either be true or crypto credentials. + * @default false + */ + secure?: boolean | crypto.Credentials; + + /** + * Should we accept self-signed certificates? + * @default false + */ + selfSigned?: boolean; + + + /** + * Should we accept expired certificates? + * @default false + */ + certExpired?: boolean; + + /** + * Should we queue our messages to ensure we don't get kicked? + * @default false + */ + floodProtection?: boolean; + + /** + * Delay between messages when flood protection is active + * @default 1000 + */ + floodProtectionDelay?: number; + + /** + * Should we use SASL authentication? + * @default false + */ + sasl?: boolean; + + /** + * Should we strip mIRC colors from the output messages? + * @default false + */ + stripColors?: boolean; + + /** + * Channel prefix + * @default '&#' + */ + channelPrefixes?: string; + + /** + * Characters to split a message at. + * @default 512 + */ + messageSplit?: number; + + /** + * Encoding to use. See + * https://nodejs.org/api/stream.html#stream_readable_setencoding_encoding + * @default 'utf-8' + */ + encoding?: string; + } + + /** Command types */ + export enum CommandType { + normal, reply, error + } + + /** Parsed IRC message. */ + export interface IMessage { + /** Prefix */ + prefix?: string; + + /** Mapped IRC command */ + command: string; + + /** Raw IRC command */ + rawCommand: string; + + /** Command type */ + commandType: CommandType; + + /** Command arguments */ + args: string[]; + } + + /** Whois data */ + export interface IWhoisData { + /** Nickname */ + nick: string; + + /** Username */ + user: string; + + /** Hostnamej */ + host: string; + + /** Real name" */ + realname: string; + + /** Channels */ + channels: string[]; + + /** Server */ + server: string; + + /** Server description string */ + serverinfo: string; + + /** Is this user an operator? */ + operator: string; + } + + /** A channel returned by a channel listing. */ + export interface IChannel { + /** Channel name */ + name: string; + + /** User count */ + users: string; + + /** Topic string */ + topic: string; + } + + /** + * Handler functions for Client. + */ + module handlers { + /** + * 'registered': Emitted when the server sends the initial 001 line, + * indicating you’ve connected to the server. See the raw event for + * details on the message object. + */ + export interface IRegistered { + /** + * @param message - raw message + */ + (message: IMessage): void; + } + + /** + * 'motd': Emitted when the server sends the message of the day to + * clients. + */ + export interface IMotd { + /** + * @param motd - motd string + */ + (motd: string): void; + } + + /** + * 'names': Emitted when the server sends a list of nicks for a channel + * (which happens immediately after joining and on request. The nicks + * object passed to the callback is keyed by nick names, and has + * values ‘’, ‘+’, or ‘@’ depending on the level of that nick in the + * channel. + */ + export interface INames { + /** + * @param channel - channel name + * @param nicks - nicks list + */ + (channel: string, nicks: string[]): void; + } + + /** + * 'names#*' As per ‘names’ event but only emits for the subscribed + * channel. + */ + export interface INamesChannel { + /** + * @param channel - channel name + * @param nicks - nicks list + */ + (nicks: string[]): void; + } + + /** + * 'topic': Emitted when the server sends the channel topic on joining + * a channel, or when a user changes the topic on a channel. See the + * raw event for details on the message object. + */ + export interface ITopic { + /** + * @param channel - channel name + * @param topic - topic + * @param nick - nick + * @param message - raw message + */ + ( + channel: string, + topic: string, + nick: string, + message: IMessage + ): void; + } + + /** + * 'join': Emitted when a user joins a channel (including when the + * client itself joins a channel). See the raw event for details on the + * message object. + */ + export interface IJoin { + /** + * @param channel - channel name + * @param nick - who joined + * @param message - raw message + */ + (channel: string, nick: string, message: IMessage): void; + } + + /** + * 'join#*': As per ‘join’ event but only emits for the subscribed + * channel. See the raw event for details on the message object. + */ + export interface IJoinChannel { + /** + * @param nick - who joined + * @param message - raw message + */ + (nick: string, message: IMessage): void; + } + + /** + * 'part': Emitted when a user parts a channel (including when the + * client itself parts a channel). See the raw event for details on the + * message object. + */ + export interface IPart { + /** + * @param channel - channel name + * @param nick - who parted + * @param reason - part reason + * @param message - raw message + */ + ( + channel: string, + nick: string, + reason: string, + message: IMessage + ): void + } + + /** + * 'part': As per ‘part’ event but only emits for the subscribed + * channel. See the raw event for details on the message object. + */ + export interface IPartChannel { + /** + * @param nick - who parted + * @param reason - part reason + * @param message - raw message + */ + ( + nick: string, + reason: string, + message: IMessage + ): void + } + + /** + * 'kick': Emitted when a user is kicked from a channel. See the raw + * event for details on the message object. + */ + export interface IKick { + /** + * @param channel - channel name + * @param nick - who was kicked + * @param by - kicker + * @param reason - kick reason + * @param message - raw message + */ + ( + channel: string, + nick: string, + by: string, + reason: string, + message: IMessage + ): void; + } + + /** + * 'kick#*': Emitted when a user is kicked from a channel. See the raw + * event for details on the message object. + */ + export interface IKickChannel { + /** + * @param nick - who was kicked + * @param by - kicker + * @param reason - kick reason + * @param message - raw message + */ + ( + nick: string, + by: string, + reason: string, + message: IMessage + ): void; + } + + /** + * 'message': Emitted when a message is sent. to can be either a nick + * (which is most likely this clients nick and means a private message), + * or a channel (which means a message to that channel). See the raw + * event for details on the message object. + */ + export interface IRecievedMessage { + /** + * @param nick - who sent the message + * @param to - to whom was the message sent + * @param text - message text + * @param message - raw message + */ + ( + nick: string, to: string, text: string, message: IMessage + ): void; + } + + /** + * 'message#': Emitted when a message is sent to any channel (i.e. + * exactly the same as the message event but excluding private + * messages. See the raw event for details on the message object. + */ + export interface IMessageAllChannels { + /** + * @param nick - who sent the message + * @param to - to whom was the message sent + * @param text - message text + * @param message - raw message + */ + ( + nick: string, to: string, text: string, message: IMessage + ): void; + } + + /** + * 'message#*': As per ‘message’ event but only emits for the + * subscribed channel. See the raw event for details on the message + * object. + */ + export interface IMessageChannel { + /** + * @param nick - who sent the message + * @param text - message text + * @param message - raw message + */ + (nick: string, text: string, message: IMessage): void; + } + + /** + * 'selfMessage': Emitted when a message is sent from the client. + * `to` is who the message was sent to. It can be either a nick + * (which most likely means a private message), or a channel (which + * means a message to that channel). + */ + export interface ISelfMessage { + (to: string, text: string): void; + } + + /** + * 'notice': Emitted when a notice is sent. to can be either a nick + * (which is most likely this clients nick and means a private + * message), or a channel (which means a message to that channel). nick + * is either the senders nick or null which means that the notice comes + * from the server. See the raw event for details on the message object. + */ + export interface INotice { + /** + * @param nick - from + * @param to - to + * @param text - text + * @param message - raw message + */ + (nick: string, to: string, text: string, message: IMessage): void; + } + + /** + * 'ping': Emitted when a server PINGs the client. The client will + * automatically send a PONG request just before this is emitted. + */ + export interface IPing { + /** + * @param server - server that adiministered the ping + */ + (server: string): void; + } + + /** + * 'pm': As per ‘message’ event but only emits when the message is + * direct to the client. See the raw event for details on the message + * object. + */ + export interface IPm { + /** + * @param nick - sender + * @param text - message text + * @param message - raw message + */ + (nick: string, text: string, message: IMessage): void; + } + + /** + * 'ctcp': Emitted when a CTCP notice or privmsg was received (type + * is either ‘notice’ or ‘privmsg’). See the raw event for details + * on the message object. + */ + export interface ICtcp { + /** + * @param from - sender + * @param to - recievier + * @param text - ctcp text + * @param type - ctcp type + * @param message - raw message + */ + ( + from: string, + to: string, + text: string, + type: string, + message: IMessage + ): void; + } + + + /** + * 'ctcp-*': Emitted when a specific type of CTCP request was + * recieved. + */ + export interface ICtcpSpecific { + /** + * @param from - sender + * @param to - recievier + * @param message - raw message + */ + ( + from: string, + to: string, + text: string, + message: IMessage + ): void; + + ( + from: string, + to: string, + text: string, + type: string, + message: IMessage + ): void; + } + + /** + * 'nick': Emitted when a user changes nick along with the channels + * the user is in. See the raw event for details on the message + * object. + */ + export interface INick { + /** + * @param oldnick - old nickname + * @param newnick - new nickname + * @param channels - channels the nick changed in + * @param message - raw message + */ + ( + oldnick: string, + newnick: string, + channels: string[], + message: IMessage + ): void; + } + + /** + * 'invite': Emitted when the client receives an /invite. See the + * raw event for details on the message object. + */ + export interface IInvite { + /** + * @param channel - channel user was invited to + * @param from - user who invited + * @param message - raw message + */ + (channel: string, from: string, message: IMessage): void; + } + + /** + * '+mode'/'-mode': Emitted when a mode is added or removed from a user or + * channel. channel is the channel which the mode is being set on/in + * . by is the user setting the mode. mode is the single character + * mode identifier. If the mode is being set on a user, argument is + * the nick of the user. If the mode is being set on a channel, + * argument is the argument to the mode. If a channel mode doesn’t + * have any arguments, argument will be ‘undefined’. See the raw + * event for details on the message object. + */ + export interface IModeChange { + /** + * @param channel - channel + * @param by - nick that changed mode + * @param mode - single character mode identifier + * @param argument - mode argument + * @param message - raw message + */ + ( + channel: string, + by: string, + mode: string, + argument: string, + message: IMessage + ): void; + } + + /** + * 'whois': Emitted whenever the server finishes outputting a WHOIS + * response. + */ + export interface IWhois { + (info: IWhoisData): void; + } + + /** + * 'channellist': Emitted when the server has finished returning a + * channel list. The channel_list array is simply a list of the + * objects that were returned in the intervening channellist_item + * events. + * + * This data is also available via the Client.channellist property + * after this event has fired. + */ + export interface IChannelList { + /** + * @param list - channels + */ + ( + list: IChannel[] + ): void; + } + + /** + * 'raw': Emitted when ever the client receives a “message” from + * the server. A message is a parsed line from the server. + */ + export interface IRaw { + /** + * @param message - raw message + */ + (message: IMessage): void; + } + + /** + * 'error': Emitted when ever the server responds with an error-type message. The message parameter is exactly as in the ‘raw’ event. + */ + export interface IError { + /** + * @param message - raw message + */ + (message: IMessage): void; + } + + /** + * 'action': Emitted whenever a user performs an action + * (e.g. /me waves). + */ + export interface IAction { + /** + * @param from - sender + * @param to - reciever + * @param text - text + * @param message - raw message + */ + ( + from: string, to: string, text: string, message: IMessage + ): void; + } + } + } + + /** Colors */ + module NodeIRC.colors { + /** + * Takes a color by name, text, and optionally what color to return. + * @param color - name of color + * @param text - text to color + * @param reset_color - color to set after text + */ + export function wrap( + color: string, text: string, reset_color?: string + ): string; + + /** + * This contains the set of colors available and a function to wrap + * text in a color. + */ + export var codes: { + [index: string]: string; + }; + } + + export = NodeIRC; +} diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index 8e3365eaf..1bdf964dd 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -748,6 +748,82 @@ describe("Fail", function () { }); +// test based on http://jasmine.github.io/2.2/custom_equality.html +describe("custom equality", function() { + var myCustomEquality: jasmine.CustomEqualityTester = function(first: any, second: any): boolean { + if (typeof first == "string" && typeof second == "string") { + return first[0] == second[1]; + } + }; + + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); + + + it("should be custom equal", function() { + expect("abc").toEqual("aaa"); + }); + + it("should be custom not equal", function() { + expect("abc").not.toEqual("abc"); + }); +}); + +// test based on http://jasmine.github.io/2.2/custom_matcher.html +var customMatchers: jasmine.CustomMatcherFactories = { + toBeGoofy: function (util: jasmine.MatchersUtil, customEqualityTesters: Array) { + return { + compare: function (actual: any, expected: any): jasmine.CustomMatcherResult { + if (expected === undefined) { + expected = ''; + } + var result: jasmine.CustomMatcherResult = { pass: false, message: ''}; + + result.pass = util.equals(actual.hyuk, "gawrsh" + expected, customEqualityTesters); + + if (result.pass) { + result.message = "Expected " + actual + " not to be quite so goofy"; + } else { + result.message = "Expected " + actual + " to be goofy, but it was not very goofy"; + } + + return result; + } + }; + } +}; +// add the custom matchers to interface jasmine.Matchers via TypeScript declaration merging +declare module jasmine { + interface Matchers { + toBeGoofy(expected?: any): boolean; + } +} + +describe("Custom matcher: 'toBeGoofy'", function () { + beforeEach(function () { + jasmine.addMatchers(customMatchers); + }); + + it("is available on an expectation", function () { + expect({ + hyuk: 'gawrsh' + }).toBeGoofy(); + }); + + it("can take an 'expected' parameter", function () { + expect({ + hyuk: 'gawrsh is fun' + }).toBeGoofy(' is fun'); + }); + + it("can be negated", function () { + expect({ + hyuk: 'this is fun' + }).not.toBeGoofy(); + }); +}); + (() => { // from boot.js var env = jasmine.getEnv(); diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index 64936f442..43831c68a 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -52,7 +52,8 @@ declare module jasmine { function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; function getEnv(): Env; - function addMatchers(matchers: any): Any; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; interface Any { @@ -62,6 +63,12 @@ declare module jasmine { jasmineToString(): string; } + // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface ArrayLike { + length: number; + [n: number]: T; + } + interface ObjectContaining { new (sample: any): any; @@ -91,6 +98,34 @@ declare module jasmine { tick(ms: number): void; } + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherResult { + pass: boolean; + message: string; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + interface Env { setTimeout: any; clearTimeout: void; @@ -122,7 +157,8 @@ declare module jasmine { compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; contains_(haystack: any, needle: any): boolean; - addEqualityTester(equalityTester: (a: any, b: any, env: Env, mismatchKeys: string[], mismatchValues: string[]) => boolean): void; + addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + addMatchers(matchers: CustomMatcherFactories): void; specFilter(spec: Spec): boolean; } @@ -320,7 +356,7 @@ declare module jasmine { waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; fail(e?: any): void; getMatchersClass_(): Matchers; - addMatchers(matchersPrototype: any): void; + addMatchers(matchersPrototype: CustomMatcherFactories): void; finishCallback(): void; finish(onComplete?: () => void): void; after(doAfter: SpecFunction): void; diff --git a/jquery-sortable/jquery-sortable-tests.ts b/jquery-sortable/jquery-sortable-tests.ts new file mode 100644 index 000000000..67dcf01b4 --- /dev/null +++ b/jquery-sortable/jquery-sortable-tests.ts @@ -0,0 +1,225 @@ +/// + + +/** + * http://johnny.github.io/jquery-sortable/#connected + */ +function connectedListsWithDropAnimation() { + var adjustment: any; + + $('ol.simple_with_animation').sortable({ + group: 'simple_with_animation', + pullPlaceholder: false, + // animation on drop + onDrop: function (item, targetContainer, _super) { + var clonedItem = $('
  • ').css({height: 0}) + item.before(clonedItem) + clonedItem.animate({'height': item.height()}) + + item.animate(clonedItem.position(), function () { + clonedItem.detach(); + _super(item); + }) + }, + + // set item relative to cursor position + onDragStart: function ($item, container, _super) { + var offset = $item.offset(), + pointer = container.rootGroup.pointer; + + adjustment = { + left: pointer.left - offset.left, + top: pointer.top - offset.top + }; + + _super($item, container); + }, + onDrag: function ($item, position) { + $item.css({ + left: position.left - adjustment.left, + top: position.top - adjustment.top + }) + } + }); +} + + +/** + * http://johnny.github.io/jquery-sortable/#handle + */ +function sortHandleAndLimitedDragDrop() { + $('ol.simple_with_drop').sortable({ + group: 'no-drop', + handle: 'i.icon-move', + onDragStart: function (item, container, _super) { + // Duplicate items of the no drop area + if(!container.options.drop) + item.clone().insertAfter(item) + _super(item) + } + }); + + $('ol.simple_with_no_drop').sortable({ + group: 'no-drop', + drop: false + }); + + $('ol.simple_with_no_drag').sortable({ + group: 'no-drop', + drag: false + }); +} + + +/** + * http://johnny.github.io/jquery-sortable/#nested + */ +function toggleNestedLists() { + var oldContainer: any; + + $('ol.nested_with_switch').sortable({ + group: 'nested', + afterMove: function (placeholder, container) { + if(oldContainer != container){ + if(oldContainer) + oldContainer.el.removeClass('active') + container.el.addClass('active') + + oldContainer = container + } + }, + onDrop: function (item, container, _super) { + container.el.removeClass('active') + _super(item) + } + }); + + $('.switch-container').on('click', '.switch', function (e) { + var method = $(this).hasClass('active') ? 'enable' : 'disable' + $(e.delegateTarget).next().sortable(method) + }); +} + + +/** + * http://johnny.github.io/jquery-sortable/#limited-target + */ +function connectedListsWithLimitedDropTargets() { + var group = $('ol.limited_drop_targets').sortable({ + group: 'limited_drop_targets', + isValidTarget: function (item, container) { + if(item.is('.highlight')) + return true + else { + return item.parent('ol')[0] == container.el[0] + } + }, + onDrop: function (item, container, _super) { + $('#serialize_output').text(group.sortable('serialize').get().join('\n')); + _super(item, container); + }, + serialize: function (parent, children, isContainer) { + return isContainer ? children.join() : 24; + }, + tolerance: 6, + distance: 10 + }); +} + + +/** + * http://johnny.github.io/jquery-sortable/#bootstrap + */ +function sortingABootstrapMenu() { + $('ol.nav').sortable({ + group: 'nav', + nested: false, + vertical: false, + exclude: '.divider-vertical', + onDragStart: function($item, container, _super) { + $item.find('ol.dropdown-menu').sortable('disable'); + _super($item, container); + }, + onDrop: function($item, container, _super) { + $item.find('ol.dropdown-menu').sortable('enable'); + _super($item, container); + } + }); + + $('ol.dropdown-menu').sortable({ + group: 'nav' + }); +} + + +/** + * http://johnny.github.io/jquery-sortable#serialization + */ +function serializationAndDelay() { + var group = $('ol.serialization').sortable({ + group: 'serialization', + delay: 500, + onDrop: function (item, container, _super) { + var data = group.sortable('serialize').get(); + + var jsonString = JSON.stringify(data, null, ' '); + + $('#serialize_output2').text(jsonString); + _super(item, container); + } + }); +} + + +/** + * http://johnny.github.io/jquery-sortable/#table + */ +function sortTables() { + // Sortable rows + $('.sorted_table').sortable({ + containerSelector: 'table', + itemPath: '> tbody', + itemSelector: 'tr', + placeholder: '' + }); + + // Sortable column heads + var oldIndex: any; + + $('.sorted_head tr').sortable({ + containerSelector: 'tr', + itemSelector: 'th', + placeholder: '', + vertical: false, + onDragStart: function (item, group, _super) { + oldIndex = item.index(); + item.appendTo(item.parent()); + _super(item); + }, + onDrop: function (item, container, _super) { + var field: any, + newIndex = item.index() + + if (newIndex != oldIndex) + item.closest('table').find('tbody tr').each(function (i, row) { + var $row = $(row); + field = $row.children().eq(oldIndex); + if(newIndex) + field.before($row.children()[newIndex]); + else + $row.prepend(field); + }); + + _super(item); + } + }); +} + + +/** + * http://johnny.github.io/jquery-sortable/#docs + */ +function api() { + $('.horatio').sortable().sortable('disable').sortable('enable') + .sortable('refresh').sortable('serialize').sortable('destroy'); +} \ No newline at end of file diff --git a/jquery-sortable/jquery-sortable.d.ts b/jquery-sortable/jquery-sortable.d.ts new file mode 100644 index 000000000..82f4e8aa0 --- /dev/null +++ b/jquery-sortable/jquery-sortable.d.ts @@ -0,0 +1,104 @@ +// Type definitions for jQuery Sortable v0.9.12 +// Project: http://johnny.github.io/jquery-sortable/ +// Definitions by: Nathan Pitman +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQuerySortable { + + interface Position { + top: number; + left: number; + } + + type Dimensions = number[]; + + interface ContainerGroup { + $document: JQuery; + containerDimensions: Dimensions[] + containers: Container[]; + delayMet: boolean; + dragInitDone: boolean; + dragProxy: any; + dragging: boolean; + dropProxy: any; + item: JQuery; + itemContainer: Container; + lastAppendedItem: JQuery; + lastPointer: Position; + lastRelativePointer: Position; + offsetParent: JQuery; + options: Options; + placeholder: JQuery; + pointer: Position; + relativePointer: Position; + sameResultBox: { bottom: number; left: number; right: number; top: number; }; + scrollProxy: any; + } + + interface Container { + el: JQuery; + options: Options; + group: ContainerGroup; + rootGroup: ContainerGroup; + handle: string; + target: JQuery; + itemDimensions: Dimensions[]; + items: HTMLElement[]; + } + + + type GenericEventHandler = ($item?: JQuery, container?: Container, _super?: GenericEventHandler, event?: Event) => void; + type OnDragEventHandler = ($item?: JQuery, position?: Position, _super?: OnDragEventHandler, event?: Event) => void; + type OnMousedownHandler = ($item?: JQuery, _super?: OnMousedownHandler, event?: Event) => void; + type OnCancelHandler = ($item?: JQuery, container?: Container, _super?: OnCancelHandler, event?: Event) => void; + + // Deliberately typing $children as an any here as it makes it much easier to use. Actual type is JQuery | any[] + type SerializeFunc = ($parent: JQuery, $children: any, parentIsContainer: boolean) => void; + + interface GroupOptions { + afterMove?: ($placeholder: JQuery, container: Container, $closestItemOrContainer: JQuery) => void; + containerPath?: string; + containerSelector?: string; + distance?: number; + delay?: number; + handle?: string; + itemPath?: string; + itemSelector?: string; + isValidTarget?: ($item: JQuery, container: Container) => boolean; + onCancel?: OnCancelHandler; + onDrag?: OnDragEventHandler; + onDragStart?: GenericEventHandler; + onDrop?: GenericEventHandler; + onMousedown?: OnMousedownHandler; + placeholder?: JQuery | any[] | Element | string; + pullPlaceholder?: boolean; + serialize?: SerializeFunc; + tolerance?: number; + } + + + interface ContainerOptions { + drag?: boolean; + drop?: boolean; + exclude?: string; + nested?: boolean; + vertical?: boolean; + } + + interface Options extends GroupOptions, ContainerOptions { + } +} + + +interface JQuery { + sortable(options?: JQuerySortable.Options): JQuery; + + sortable(methodName: 'enable'): JQuery; + sortable(methodName: 'disable'): JQuery; + sortable(methodName: 'refresh'): JQuery; + sortable(methodName: 'destroy'): JQuery; + sortable(methodName: 'serialize'): JQuery; + sortable(methodName: string): JQuery; +} diff --git a/jquery.pickadate/jquery.pickadate-tests.ts b/jquery.pickadate/jquery.pickadate-tests.ts deleted file mode 100644 index fde52f3e3..000000000 --- a/jquery.pickadate/jquery.pickadate-tests.ts +++ /dev/null @@ -1,420 +0,0 @@ -/// - -/* -* Date picker tests -* From http://amsul.ca/pickadate.js/date.htm -*/ - -$('.datepicker').pickadate(); - -$('.datepicker').pickadate({ - weekdaysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], - showMonthsShort: true -}); - -$('.datepicker').pickadate({ - today: '', - clear: 'Clear selection' -}); - -// Extend the default picker options for all instances. -$.extend($.fn.pickadate.defaults, { - monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], - weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], - today: 'aujourd\'hui', - clear: 'effacer', - formatSubmit: 'yyyy/mm/dd' -}); - -// Or, pass the months and weekdays as an array for each invocation. -$('.datepicker').pickadate({ - monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], - weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], - today: 'aujourd\'hui', - clear: 'effacer', - formatSubmit: 'yyyy/mm/dd' -}); - -$('.datepicker').pickadate({ - // Escape any "rule" characters with an exclamation mark (!). - format: 'You selecte!d: dddd, dd mmm, yyyy', - formatSubmit: 'yyyy/mm/dd', - hiddenPrefix: 'prefix__', - hiddenSuffix: '__suffix' -}); - -$('.datepicker').pickadate({ - selectYears: true, - selectMonths: true -}); - -$('.datepicker').pickadate({ - // `true` defaults to 10. - selectYears: 4 -}); - -$('.datepicker').pickadate({ - firstDay: 1 -}); - -$('.datepicker').pickadate({ - min: new Date(2013, 3, 20), - max: new Date(2013, 7, 14) -}); - -$('.datepicker').pickadate({ - min: [2013, 3, 20], - max: [2013, 7, 14] -}); - -$('.datepicker').pickadate({ - // An integer (positive/negative) sets it relative to today. - min: -15, - // `true` sets it to today. `false` removes any limits. - max: true -}); - -$('.datepicker').pickadate({ - disable: [ - [2013, 3, 3], - [2013, 3, 12], - [2013, 3, 20], - [2013, 3, 29] - ] -}); - -$('.datepicker').pickadate({ - disable: [ - 1, 4, 7 - ] -}); - -$('.datepicker').pickadate({ - disable: [ - new Date(2013, 3, 13), - new Date(2013, 3, 29) - ] -}); - -$('.datepicker').pickadate({ - disable: [ - true, - 1, 4, 7, - [2013, 3, 3], - [2013, 3, 12], - [2013, 3, 20], - [2013, 3, 29] - ] -}); - -$('.datepicker').pickadate({ - container: '#root-outlet' -}); - -$('.datepicker').pickadate({ - onStart: function () { - console.log('Hello there :)') - }, - onRender: function () { - console.log('Whoa.. rendered anew') - }, - onOpen: function () { - console.log('Opened up') - }, - onClose: function () { - console.log('Closed now') - }, - onStop: function () { - console.log('See ya.') - }, - onSet: function (event) { - console.log('Just set stuff:', event) - } -}); - -/* -* Time picker tests -* From http://amsul.ca/pickadate.js/time.htm -*/ - -$('.timepicker').pickatime(); - -$('.timepicker').pickatime({ - clear: '' -}); - -$('.timepicker').pickatime({ - // Escape any "rule" characters with an exclamation mark (!). - format: 'T!ime selected: h:i a', - formatLabel: 'h:i a', - formatSubmit: 'HH:i', - hiddenPrefix: 'prefix__', - hiddenSuffix: '__suffix' -}); - -$('.timepicker').pickatime({ - formatLabel: function (time: TimePickerItemObject) { - var hours = (time.pick - this.get('now').pick) / 60, - label = hours < 0 ? ' !hours to now' : hours > 0 ? ' !hours from now' : 'now' - return 'h:i a ' + (hours ? Math.abs(hours).toString() : '') + label + '' - } -}); - -$('.datepicker').pickadate({ - interval: 150 -}); - -$('.timepicker').pickatime({ - min: [7, 30], - max: [14, 0] -}); - -$('.timepicker').pickatime({ - // An integer (positive/negative) sets it as intervals relative from now. - min: -5, - // `true` sets it to now. `false` removes any limits. - max: true -}); - -$('.timepicker').pickatime({ - disable: [ - [0, 30], - [2, 0], - [8, 30], - [9, 0] - ] -}); - -$('.timepicker').pickatime({ - disable: [ - 3, 5, 7 - ] -}); - -$('.timepicker').pickatime({ - disable: [ - true, - 3, 5, 7, - [0, 30], - [2, 0], - [8, 30], - [9, 0] - ] -}); - -$('.timepicker').pickatime({ - container: '#root-outlet' -}); - -$('.timepicker').pickatime({ - onStart: function () { - console.log('Hello there :)') - }, - onRender: function () { - console.log('Whoa.. rendered anew') - }, - onOpen: function () { - console.log('Opened up') - }, - onClose: function () { - console.log('Closed now') - }, - onStop: function () { - console.log('See ya.') - }, - onSet: function (event) { - console.log('Just set stuff:', event) - } -}); - -/* -* API tests -* From http://amsul.ca/pickadate.js/api.htm -*/ - -var $input = $('.datepicker').pickadate(); - -// Use the picker object directly. -var picker = $input.pickadate('picker'); - -picker.open().clear().close(); - -picker.open(); -picker.close(); -picker.close(true); - -picker.open(false) -$(document).on('click', function () { - picker.close() -}); - -picker.start(); -picker.stop(); -picker.render(); -picker.clear(); - -picker.get() // Short for `picker.get('value')` - -picker.get('select'); -picker.get('select', 'yyyy/mm/dd'); - -picker.get('highlight'); -picker.get('highlight', 'yyyy/mm/dd'); - -picker.get('view'); - -picker.get('min'); -picker.get('min', 'yyyy/mm/dd'); -picker.get('max'); -picker.get('max', 'yyyy/mm/dd'); - -picker.get('open'); -picker.get('start'); -picker.get('id'); -picker.get('disable'); - -picker.set('clear'); - -// reset disabled dates -picker.set('disable', undefined); - -// Using arrays formatted as [YEAR,MONTH,DATE]. -picker.set('select', [2013, 3, 20]); - -// Using JavaScript Date objects. -picker.set('select', new Date(2013,03,20)); - -// Using positive integers as UNIX timestamps. -picker.set('select', 1365961912346); - -// Using arrays formatted as [HOUR,MINUTE]. -picker.set('select', [3, 0]); - -// Using positive integers as minutes. -picker.set('select', 540); - -// Using arrays formatted as [YEAR,MONTH,DATE]. -picker.set('highlight', [2013, 3, 20]); - -// Using JavaScript Date objects. -picker.set('highlight', new Date(2013,7,14)); - -// Using positive integers as UNIX timestamps. -picker.set('highlight', 1365961912346); - -// Using arrays formatted as [HOUR,MINUTE]. -picker.set('highlight', [15, 30]); - -// Using positive integers as minutes. -picker.set('highlight', 1080); - -// Using arrays formatted as [YEAR,MONTH,DATE]. -picker.set('view', [2000, 3, 20]); - -// Using JavaScript Date objects. -picker.set('view', new Date(1988,7,14)); - -// Using positive integers as UNIX timestamps. -picker.set('view', 1587355200000); - -// Using arrays formatted as [HOUR,MINUTE]. -picker.set('view', [15, 30]); - -// Using positive integers as minutes. -picker.set('view', 1080); - -// Using arrays formatted as [YEAR,MONTH,DATE]. -picker.set('min', [2013, 3, 20]); - -// Using JavaScript Date objects. -picker.set('min', new Date(2013,7,14)); - -// Using integers as days relative to today. -picker.set('min', -4); - -// Using `true` for "today". -picker.set('min', true); - -// Using `false` to remove. -picker.set('min', false); - -// Using arrays formatted as [HOUR,MINUTE]. -picker.set('min', [15, 30]); - -// Using integers as intervals relative from now. -picker.set('min', -4); - -// Using `true` for "now". -picker.set('min', true); - -// Using `false` to remove. -picker.set('min', false); - -// Using arrays formatted as [YEAR,MONTH,DATE]. -picker.set('max', [2013, 3, 20]); - -// Using JavaScript Date objects. -picker.set('max', new Date(2013,7,14)); - -// Using integers as days relative to today. -picker.set('max', 4); - -// Using `true` for "today". -picker.set('max', true); - -// Using `false` to remove. -picker.set('max', false); - -// Using arrays formatted as [HOUR,MINUTE]. -picker.set('max', [15, 30]); - -// Using integers as intervals relative from now. -picker.set('max', 4); - -// Using `true` for "now". -picker.set('max', true); - -// Using `false` to remove. -picker.set('max', false); - -picker.on('open', function () { - console.log('Opened.. and here I am!'); -}); - -picker.on({ - open: function () { - console.log('Opened.. and here I am!'); - }, - close: function () { - console.log('Closed.. and here I am!'); - } -}); - -$('.datepicker').pickadate({ - onOpen: function () { - console.log('Opened up!') - }, - onClose: function () { - console.log('Closed now') - }, - onRender: function () { - console.log('Just rendered anew') - }, - onStart: function () { - console.log('Hello there :)') - }, - onStop: function () { - console.log('See ya') - }, - onSet: function (event) { - console.log('Set stuff:', event) - } -}); - -picker.on('open', function () { - console.log('Didn\'t open.. yet here I am!'); -}) -picker.trigger('open'); - -picker.$node; -picker.$root; \ No newline at end of file diff --git a/jquery.pickadate/jquery.pickadate-tests.ts.tscparams b/jquery.pickadate/jquery.pickadate-tests.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/jquery.pickadate/jquery.pickadate-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.pickadate/jquery.pickadate.d.ts b/jquery.pickadate/jquery.pickadate.d.ts deleted file mode 100644 index 62b20bb22..000000000 --- a/jquery.pickadate/jquery.pickadate.d.ts +++ /dev/null @@ -1,319 +0,0 @@ -// Type definitions for pickadate.js 3.3.0 -// Project: https://github.com/amsul/pickadate.js -// Definitions by: Theodore Brown -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -/** Options shared between date and time pickers */ -interface pickerOptions { - /** Set clear button text */ - clear?: string; // default 'Clear' - - /** Specify where to insert the picker's root element by passing any valid CSS selector to this option */ - container?: any; - - // Events - onStart?: (event: any) => void; - onRender?: (event: any) => void; - onOpen?: (event: any) => void; - onClose?: (event: any) => void; - onSet?: (event: any) => void; - onStop?: (event: any) => void; -} - -interface pickadateOptions extends pickerOptions { - // Strings and translations - monthsFull?: string[]; // default 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' - monthsShort?: string[]; // default 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' - weekdaysFull?: string[]; // default 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' - weekdaysShort?: string[]; // default 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' - showMonthsShort?: boolean; - showWeekdaysFull?: boolean; - - // Buttons - today?: string; // default 'Today' - - // Formats - format?: string; // default 'd mmmm, yyyy' - formatSubmit?: string; // e.g. 'yyyy/mm/dd' - hiddenPrefix?: string; // default undefined - hiddenSuffix?: string; // default '_submit' - hiddenName?: boolean; // default undefined - - // Dropdown selectors - selectYears?: any; // Specify the number of years selectable using an even integer - half before and half after the year in focus: - selectMonths?: boolean; - - // First day of the week - firstDay?: any; // The first day of the week can be set to either Sunday or Monday. Anything truth-y sets it as Monday and anything false-y as Sunday - - // Date limits - min?: any; // date object, array formatted as [YEAR,MONTH,DATE], or dates relative to today using integers or a boolean (`true` sets it to today. `false` removes any limits). - max?: any; - - // Disable dates - disable?: any[]; // Date objects, arrays formatted as [YEAR,MONTH,DATE], or integers representing days of the week (from 1 to 7). Switch to whitelist by setting first item in collection to `true`. - - // Classes - klass?: { - - // The element states - input?: string; // default 'picker__input' - active?: string; // default 'picker__input--active' - - // The root picker and states - picker?: string; // default 'picker' - opened?: string; // default 'picker--opened' - focused?: string; // default 'picker--focused' - - // The picker holder - holder?: string; // default 'picker__holder' - - // The picker frame, wrapper, and box - frame?: string; // default 'picker__frame' - wrap?: string; // default 'picker__wrap' - box?: string; // default 'picker__box' - - // The picker header - header?: string; // default 'picker__header' - - // Month navigation - navPrev?: string; // default 'picker__nav--prev' - navNext?: string; // default 'picker__nav--next' - navDisabled?: string; // default 'picker__nav--disabled' - - // Month & year labels - month?: string; // default 'picker__month' - year?: string; // default 'picker__year' - - // Month & year dropdowns - selectMonth?: string; // default 'picker__select--month' - selectYear?: string; // default 'picker__select--year' - - // Table of dates - table?: string; // default 'picker__table' - - // Weekday labels - weekdays?: string; // default 'picker__weekday' - - // Day states - day?: string; // default 'picker__day' - disabled?: string; // default 'picker__day--disabled' - selected?: string // default 'picker__day--selected' - highlighted?: string // default 'picker__day--highlighted' - now?: string; // default 'picker__day--today' - infocus?: string; // default 'picker__day--infocus' - outfocus?: string; // default 'picker__day--outfocus' - - // The picker footer - footer?: string; // default 'picker__footer' - - // Today & clear buttons - buttonClear?: string; // default 'picker__button--clear' - buttonToday?: string; // default 'picker__button--today' - } -} - -interface pickatimeOptions extends pickerOptions { - - // Formats - format?: string; // default 'h:i A' - formatLabel?: any; - formatSubmit?: string; - hiddenPrefix?: string; // default undefined - hiddenSuffix?: string; // default '_submit' - - // Time intervals - interval?: number; // interval in minutes. default 30. - - // Time limits - min?: any; // array formatted as [HOUR,MINUTE], or as times relative to now using integers or a boolean (`true` sets it to now, `false` removes any limits). - max?: any; - - // Disable times - disable?: any[]; // arrays formatted as [HOUR,MINUTE] or integers representing hours (from 0 to 23). Switch to whitelist by setting true as the first item in the collection. - - // Classes - klass?: { - - // The element states - input?: string; // default 'picker__input' - active?: string; // default 'picker__input--active' - - // The root picker and states - picker?: string; // default 'picker picker--time' - opened?: string; // default 'picker--opened' - focused?: string; // default 'picker--focused' - - // The picker holder - holder?: string; // default 'picker__holder' - - // The picker frame, wrapper, and box - frame?: string; // default 'picker__frame' - wrap?: string; // default 'picker__wrap' - box?: string; // default 'picker__box' - - // List of times - list?: string; // default 'picker__list' - listItem?: string; // default 'picker__list-item' - - // Time states - disabled?: string; // default 'picker__list-item--disabled' - selected?: string; // default 'picker__list-item--selected' - highlighted?: string; // default 'picker__list-item--highlighted' - viewset?: string; // default 'picker__list-item--viewset' - now?: string; // default 'picker__list-item--now' - - // Clear button - buttonClear?: string; // default 'picker__button--clear' - } -} - -interface PickerItemObject { - /** The "pick" value used for comparisons. */ - pick: number; -} - -interface DatePickerItemObject extends PickerItemObject { - /** The full year. */ - year: number; - - /** The month with zero-as-index. */ - month: number; - - /** The date of the month. */ - date: number; - - /** The day of the week with zero-as-index. */ - day: number; - - /** The underlying JavaScript Date object. */ - obj: Date; -} - -interface TimePickerItemObject extends PickerItemObject { - /** Hour of the day from 0 to 23. */ - hour: number; - - /** The minutes of the hour from 0 to 59 (based on the interval). */ - mins: number; -} - -interface CallbackObject { - open?: () => void; - close?: () => void; - render?: () => void; - start?: () => void; - stop?: () => void; - set?: () => void; -} - -interface SetThings { - clear?; - select?: any; - highlight?: any; - view?: any; - min?: any; - max?: any; - disable?: any; - enable?: any; -} - -interface TimePickerSetThings extends SetThings { - interval?: any; -} - -interface PickerObject { - /** The picker's relative input element wrapped as a jQuery object. */ - $node: JQuery; - - /** The picker's relative root holder element wrapped as a jQuery object. */ - $root: JQuery; - - open(withoutFocus?: boolean): TPickerObject; - close(withFocus?: boolean): TPickerObject; - - /** Rebuild the picker. */ - start(): TPickerObject; - - /** Destroy the picker. */ - stop(): TPickerObject; - - /** - * Refresh the picker box after adding something to the holder. - * By default, only the "face" of the picker (i.e. the box element) - * has it’s contents re-rendered. To render the entire picker from - * the root up, pass true as the first argument. - */ - render(entirePicker?: boolean): TPickerObject; - - /** Clear the value in the picker's input element. */ - clear(): TPickerObject; - - /** Short for picker.get('value') */ - get(): string; - - /** Get the properties, objects, and states that make up the current state of the picker. */ - get(thing: string): any; - - /** Returns the string value of the picker's input element. */ - get(thing: 'value'): string; - - /** Returns the item object that is visually selected. */ - get(thing: 'select'): TItemObject; - - /** Returns the item object that is visually highlighted. */ - get(thing: 'highlight'): TItemObject; - - /** Returns the item object that sets the current view. */ - get(thing: 'view'): TItemObject; - - /** Returns the item object that limits the picker's lower range. */ - get(thing: 'min'): TItemObject; - - /** Returns the item object that limits the picker's upper range. */ - get(thing: 'max'): TItemObject; - - /** Returns a boolean value of whether the picker is open or not. */ - get(thing: 'open'): boolean; - - /** Returns a boolean value of whether the picker has started or not. */ - get(thing: 'start'): boolean; - - /** Returns a unique 9-digit integer that is the ID of the picker. */ - get(thing: 'id'): number; - - /** Returns an array of items that determine which item objects to disable on the picker. */ - get(thing: 'disable'): any[]; - - /** Returns a formatted string for the item object specified by `thing` */ - get(thing: string, format: string): string; - - /** Set the properties, objects, and states to change the state of the picker. */ - set(thing: string, value?: any, options?: any): TPickerObject; - set(things: TOptions, options?: any): TPickerObject; - - /** Bind callbacks to get fired off when the relative picker method is called. */ - on(methodName, callback: () => void): TPickerObject; - - /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ - on(callbackObject: CallbackObject): TPickerObject; - - /** Trigger callbacks that have been queued up using the the on method. */ - trigger(event: string): TPickerObject; -} - -interface DatePickerObject extends PickerObject { } -interface TimePickerObject extends PickerObject { } - -interface JQuery { - pickadate(methodName: "picker"): DatePickerObject; - pickadate(methodName: string): any; - pickadate(options?: pickadateOptions): JQuery; - - pickatime(methodName: "picker"): TimePickerObject; - pickatime(methodName: string): any; - pickatime(options?: pickatimeOptions): JQuery; -} - diff --git a/jquery.pickadate/jquery.pickadate.d.ts.tscparams b/jquery.pickadate/jquery.pickadate.d.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/jquery.pickadate/jquery.pickadate.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jquery.ui.layout/jquery.ui.layout.d.ts b/jquery.ui.layout/jquery.ui.layout.d.ts index b15dd3386..dae9dc067 100644 --- a/jquery.ui.layout/jquery.ui.layout.d.ts +++ b/jquery.ui.layout/jquery.ui.layout.d.ts @@ -27,12 +27,12 @@ interface JQueryLayout { resizeContent(pane: any): any; resizeAll(): any; - addToggleBtn(selector: string, pane: any) - addCloseBtn(selector: string, pane: any) - addOpenBtn(selector: string, pane: any) - addPinBtn(selector: string, pane: any) - allowOverflow(elemOrPane: any) - resetOverflow(elemOrPane: any) + addToggleBtn(selector: string, pane: any): any; + addCloseBtn(selector: string, pane: any): any; + addOpenBtn(selector: string, pane: any): any; + addPinBtn(selector: string, pane: any): any; + allowOverflow(elemOrPane: any): any; + resetOverflow(elemOrPane: any): any; } interface JQuery { diff --git a/js-signals/js-signals.d.ts b/js-signals/js-signals.d.ts index ebc8f72ae..c396bf490 100644 --- a/js-signals/js-signals.d.ts +++ b/js-signals/js-signals.d.ts @@ -5,6 +5,10 @@ declare var signals: SignalWrapper; +declare module "signals" { + export = signals; +} + interface SignalWrapper { Signal: Signal } diff --git a/jsnox/jsnox-tests.ts b/jsnox/jsnox-tests.ts index 4e990766b..e34d71b4a 100644 --- a/jsnox/jsnox-tests.ts +++ b/jsnox/jsnox-tests.ts @@ -9,8 +9,8 @@ interface PersonProps { age: number } -var Person = React.createClass({ - render(): React.ReactHTMLElement { return null } +var Person = React.createClass({ + render():React.ReactElement { return null; } }); var PersonTag = React.createFactory(Person); @@ -19,7 +19,7 @@ var clickHandler: React.MouseEventHandler // Tests with spec string function spec_string () { - var result: React.ReactHTMLElement + var result: React.HTMLComponent // just spec string result = $('div') @@ -38,7 +38,7 @@ function spec_string () { // Tests with react component function react_component() { - var result: React.ReactHTMLElement + var result: React.ReactElement<{}> // with nothing more result = $(Person) @@ -54,4 +54,4 @@ function react_component() { result = $(Person, props, 'hello') // one string child result = $(Person, props, $('span', 'world')) // one element child result = $(Person, props, ['hello', PersonTag()]) // mixed array of children -} \ No newline at end of file +} diff --git a/jsnox/jsnox.d.ts b/jsnox/jsnox.d.ts index 72584563b..dfb59e280 100644 --- a/jsnox/jsnox.d.ts +++ b/jsnox/jsnox.d.ts @@ -1,12 +1,14 @@ -// Type definitions for JSnoX +// Type definitions for JSnoX // Project: https://github.com/af/jsnox // Definitions by: Steve Baker // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module 'jsnox' { + import React = require("react"); + /* * JSnoX requires an object with a createElement method. * This will normally be the React object but could be something else @@ -29,7 +31,7 @@ declare module 'jsnox' { * @param children A single React node (string or ReactElement) or array of nodes. * Note that unlike with React itself, multiple children must be placed into an array. */ - (specString: string, children: React.ReactNode): React.ReactHTMLElement + (specString: string, children: React.ReactNode): React.HTMLComponent /** * Renders an HTML element from the given spec string, with optional props @@ -40,7 +42,7 @@ declare module 'jsnox' { * @param children A single React node (string or ReactElement) or array of nodes. * Note that unlike with React itself, multiple children must be placed into an array. */ - (specString: string, props?: React.HTMLAttributes, children?: React.ReactNode): React.ReactHTMLElement + (specString: string, props?: React.HTMLAttributes, children?: React.ReactNode): React.HTMLComponent /** diff --git a/jsuri/jsuri-tests.ts b/jsuri/jsuri-tests.ts new file mode 100644 index 000000000..73ecbc50d --- /dev/null +++ b/jsuri/jsuri-tests.ts @@ -0,0 +1,82 @@ +/// + +function test_createUri() { + var uri = new jsuri.Uri('http://user:pass@www.test.com:81/index.html?q=books#fragment'); + + var getTests = { + protocol: 'http' == uri.protocol(), + userInfo: 'user:pass' == uri.userInfo(), + host: 'www.test.com' == uri.host(), + port: 81 == uri.port(), + path: '/index.html' == uri.path(), + query: 'q=books' == uri.query(), + anchor: 'fragment' == uri.anchor() + }; + + uri.protocol('https'); + var setProtocolTest = uri.toString() == 'https://user:pass@www.test.com:81/index.html?q=books#fragment'; + + uri.host('mydomain.com'); + var setHostTest = uri.toString() == 'https://user:pass@mydomain.com:81/index.html?q=books#fragment'; +} + +function test_chainable() { + new jsuri.Uri() + .setPath('/archives/1979/') + .setQuery('?page=1'); // /archives/1979?page=1 + + new jsuri.Uri() + .setPath('/index.html') + .setAnchor('content') + .setHost('www.test.com') + .setPort(8080) + .setUserInfo('username:password') + .setProtocol('https') + .setQuery('this=that&some=thing'); // https://username:password@www.test.com:8080/index.html?this=that&some=thing#content + + new jsuri.Uri('http://www.test.com') + .setHost('www.yahoo.com') + .setProtocol('https'); // https://www.yahoo.com +} + +function test_queryParams() { + new jsuri.Uri('?cat=1&cat=2&cat=3').getQueryParamValue('cat'); // 1 + + new jsuri.Uri('?cat=1&cat=2&cat=3').getQueryParamValues('cat'); // [1, 2, 3] + + new jsuri.Uri().addQueryParam('q', 'books'); // ?q=books + + new jsuri.Uri('http://www.github.com') + .addQueryParam('testing', '123') + .addQueryParam('one', 1); // http://www.github.com/?testing=123&one=1 + + // insert param at index 0 + new jsuri.Uri('?b=2&c=3&d=4').addQueryParam('a', '1', 0); // ?a=1&b=2&c=3&d=4 + + new jsuri.Uri().replaceQueryParam('page', 2); // ?page=2 + + new jsuri.Uri('?a=1&b=2&c=3') + .replaceQueryParam('a', 'eh'); // ?a=eh&b=2&c=3 + + new jsuri.Uri('?a=1&b=2&c=3&c=4&c=5&c=6') + .replaceQueryParam('c', 'five', '5'); // ?a=1&b=2&c=3&c=4&c=five&c=6 + + new jsuri.Uri('?a=1&b=2&c=3') + .deleteQueryParam('a'); // ?b=2&c=3 + + new jsuri.Uri('test.com?a=1&b=2&c=3&a=eh') + .deleteQueryParam('a', 'eh'); // test.com/?a=1&b=2&c=3 + + new jsuri.Uri('?a=1&b=2&c=3') + .hasQueryParam('a'); // true + + new jsuri.Uri('?a=1&b=2&c=3') + .hasQueryParam('d'); // false +} + +function test_clone() { + var baseUri = new jsuri.Uri('http://localhost/'); + + baseUri.clone().setProtocol('https'); // https://localhost/ + baseUri; // http://localhost/ +} diff --git a/jsuri/jsuri.d.ts b/jsuri/jsuri.d.ts new file mode 100644 index 000000000..a50002140 --- /dev/null +++ b/jsuri/jsuri.d.ts @@ -0,0 +1,139 @@ +// Type definitions for jsUri 1.3+ +// Project: https://github.com/derek-watson/jsUri +// Definitions by: Chris Charabaruk +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module jsuri { + type Primitive = string | number | boolean; + + export class Uri { + /** + * Creates a new Uri object + * @constructor + * @param {string} str + */ + constructor(str?: string); + + /** + * Define getter/setter methods + */ + protocol(val?: string): string; + userInfo(val?: string): string; + host(val?: string): string; + port(val?: number): number; + path(val?: string): string; + anchor(val?: string): string; + + /** + * if there is no protocol, the leading // can be enabled or disabled + * @param {Boolean} val + * @return {Boolean} + */ + hasAuthorityPrefix(val?: boolean): boolean; + + isColonUri(val?: boolean): boolean; + + /** + * Serializes the internal state of the query pairs + * @param {string} [val] set a new query string + * @return {string} query string + */ + query(val?: string): string; + + /** + * returns the first query param value found for the key + * @param {string} key query key + * @return {string} first value found for key + */ + getQueryParamValue(key: string): string; + + /** + * returns an array of query param values for the key + * @param {string} key query key + * @return {array} array of values + */ + getQueryParamValues(key: string): string[]; + + /** + * removes query parameters + * @param {string} key remove values for key + * @param {val} [val] remove a specific value, otherwise removes all + * @return {Uri} returns self for fluent chaining + */ + deleteQueryParam(key: string, val?: string): Uri; + + /** + * adds a query parameter + * @param {string} key add values for key + * @param {string} val value to add + * @param {integer} [index] specific index to add the value at + * @return {Uri} returns self for fluent chaining + */ + addQueryParam(key: string, val: Primitive, index?: number): Uri; + + /** + * test for the existence of a query parameter + * @param {string} key check values for key + * @return {Boolean} true if key exists, otherwise false + */ + hasQueryParam(key: string): boolean; + + /** + * replaces query param values + * @param {string} key key to replace value for + * @param {string} newVal new value + * @param {string} [oldVal] replace only one specific value (otherwise replaces all) + * @return {Uri} returns self for fluent chaining + */ + replaceQueryParam(key: string, newVal: Primitive, oldVal?: Primitive): Uri; + + /** + * Define fluent setter methods (setProtocol, setHasAuthorityPrefix, etc) + */ + setProtocol(val: string): Uri; + setHasAuthorityPrefix(val: boolean): Uri; + setIsColonUri(val: boolean): Uri; + setUserInfo(val: string): Uri; + setHost(val: string): Uri; + setPort(val: number): Uri; + setPath(val: string): Uri; + setQuery(val: string): Uri; + setAnchor(val: string): Uri; + + /** + * Scheme name, colon and doubleslash, as required + * @return {string} http:// or possibly just // + */ + scheme(): string; + + /** + * Same as Mozilla nsIURI.prePath + * @return {string} scheme://user:password@host:port + * @see https://developer.mozilla.org/en/nsIURI + */ + origin(): string; + + /** + * Adds a trailing slash to the path + */ + addTrailingSlash(): Uri; + + /** + * Serializes the internal state of the Uri object + * @return {string} + */ + toString(): string; + + /** + * Clone a Uri object + * @return {Uri} duplicate copy of the Uri + */ + clone(): Uri; + } +} + +declare type Uri = jsuri.Uri; + +declare module 'jsuri' { + export = Uri; +} diff --git a/jszip/jszip-tests.ts b/jszip/jszip-tests.ts index 97fd10450..514beb501 100644 --- a/jszip/jszip-tests.ts +++ b/jszip/jszip-tests.ts @@ -33,18 +33,18 @@ function testJSZip() { var folder = newJszip.folder("test"); if(folder.file("test.txt").asText() == "test string") { log(SEVERITY.INFO, "all ok"); - } + } else { log(SEVERITY.ERROR, "wrong file"); } var folders = newJszip.folder(new RegExp("^test")); - + if(folders.length == 1) { log(SEVERITY.INFO, "all ok"); if(folders[0].dir == true) { log(SEVERITY.INFO, "all ok"); - } + } else { log(SEVERITY.ERROR, "wrong file"); } @@ -59,14 +59,14 @@ function testJSZip() { log(SEVERITY.INFO, "all ok"); } else { - log(SEVERITY.ERROR, "wrong data in files"); + log(SEVERITY.ERROR, "wrong data in files"); } - } + } else { log(SEVERITY.ERROR, "wrong number of files"); } - var filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => { + var filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => { if (file.asText() == "test string") { return true; } @@ -82,7 +82,7 @@ function testJSZip() { newJszip.remove("test/test.txt"); - filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => { + filterFiles = newJszip.filter((relativePath: string, file: JSZipObject) => { if (file.asText() == "test string") { return true; } @@ -95,24 +95,43 @@ function testJSZip() { else { log(SEVERITY.ERROR, "wrong number of files"); } + + var uncompressedStr = JSZip.compressions.DEFLATE.uncompress( + JSZip.compressions.DEFLATE.compress("\0\1\2\3\4\5\6\7",{level:9})); + var uncompressedArr = JSZip.compressions.DEFLATE.uncompress( + JSZip.compressions.DEFLATE.compress([0,1,2,3,4,5,6,7],{level:9})); + var uncompressedUint8Arr = JSZip.compressions.DEFLATE.uncompress( + JSZip.compressions.DEFLATE.compress(new Uint8Array([0,1,2,3,4,5,6,7]),{level:9})); + + var every_match = [0,1,2,3,4,5,6,7].every(function(val, i){ + return uncompressedStr[i] === val && + uncompressedArr[i] === val && + uncompressedUint8Arr[i] === val; + }); + if(every_match) { + log(SEVERITY.INFO, "compress and uncompress ok."); + }else{ + log(SEVERITY.ERROR, "compress or uncompress failed."); + } + } function log(severity:number, message: any) { var log = ""; switch(severity) { - case 0: + case 0: log += "[DEBUG] "; break; - case 1: + case 1: log += "[INFO] "; break; - case 2: + case 2: log += "[WARN] "; break; - case 3: + case 3: log += "[ERROR] "; break; - case 4: + case 4: log += "[FATAL] "; break; default: @@ -122,4 +141,4 @@ function log(severity:number, message: any) { console.log(log += message); } -testJSZip(); \ No newline at end of file +testJSZip(); diff --git a/jszip/jszip.d.ts b/jszip/jszip.d.ts index df571793b..651a26da5 100644 --- a/jszip/jszip.d.ts +++ b/jszip/jszip.d.ts @@ -32,7 +32,7 @@ interface JSZip { /** * Return an new JSZip instance with the given folder as root - * + * * @param name Name of the folder * @return New JSZip object with the given folder as root or null */ @@ -40,7 +40,7 @@ interface JSZip { /** * Returns new JSZip instances with the matching folders as root - * + * * @param name RegExp to match * @return New array of JSZipFile objects which match the RegExp */ @@ -56,7 +56,7 @@ interface JSZip { /** * Removes the file or folder from the archive - * + * * @param path Relative path of file or folder * @return Returns the JSZip instance */ @@ -140,6 +140,18 @@ interface JSZipSupport { nodebuffer: boolean; } +interface DEFLATE { + /** pako.deflateRaw, level:0-9 */ + compress(input: string, compressionOptions: {level:number}): Uint8Array; + compress(input: number[], compressionOptions: {level:number}): Uint8Array; + compress(input: Uint8Array, compressionOptions: {level:number}): Uint8Array; + + /** pako.inflateRaw */ + uncompress(input: string): Uint8Array; + uncompress(input: number[]): Uint8Array; + uncompress(input: Uint8Array): Uint8Array; +} + declare var JSZip: { /** * Create JSZip instance @@ -169,6 +181,9 @@ declare var JSZip: { prototype: JSZip; support: JSZipSupport; + compressions: { + DEFLATE: DEFLATE; + } } declare module "jszip" { diff --git a/kendo-ui/kendo-ui-tests.ts b/kendo-ui/kendo-ui-tests.ts new file mode 100644 index 000000000..a9944b6af --- /dev/null +++ b/kendo-ui/kendo-ui-tests.ts @@ -0,0 +1 @@ +/// \ No newline at end of file diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts new file mode 100644 index 000000000..3f5cb5d4f --- /dev/null +++ b/kendo-ui/kendo-ui.d.ts @@ -0,0 +1,15682 @@ +// Type definitions for Kendo UI +// Project: http://www.telerik.com/kendo-ui +// Definitions by: Stefan Rahnev +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module kendo { + function culture(): { + name: string; + calendar: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + calendars: { + standard: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + }; + numberFormat: { + currency: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; + decimals: number; + groupSize: number[]; + pattern: string[]; + percent: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; + }; + }; + + var cultures: {[culture:string] : { + name?: string; + calendar?: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + calendars?: { + standard: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + }; + numberFormat?: { + currency: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; + decimals: number; + groupSize: number[]; + pattern: string[]; + percent: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; + }; + }}; + + function format(format: string, ...values: any[]): string; + + function fx(selector: string): effects.Element; + function fx(element: Element): effects.Element; + function fx(element: JQuery): effects.Element; + + function init(selector: string, ...namespaces: any[]): void; + function init(element: JQuery, ...namespaces: any[]): void; + function init(element: Element, ...namespaces: any[]): void; + + function observable(data: any): kendo.data.ObservableObject; + function observableHierarchy(array: any[]): kendo.data.ObservableArray; + + function render(template:(data: any) => string, data: any[]): string; + function template(template: string, options?: TemplateOptions): (data: any) => string; + + function guid(): string; + + function widgetInstance(element: JQuery, suite: typeof kendo.ui): kendo.ui.Widget; + function widgetInstance(element: JQuery, suite: typeof kendo.mobile.ui): kendo.ui.Widget; + function widgetInstance(element: JQuery, suite: typeof kendo.dataviz.ui): kendo.ui.Widget; + + + var ns: string; + + var keys: { + INSERT: number; + DELETE: number; + BACKSPACE: number; + TAB: number; + ENTER: number; + ESC: number; + LEFT: number; + UP: number; + RIGHT: number; + DOWN: number; + END: number; + HOME: number; + SPACEBAR: number; + PAGEUP: number; + PAGEDOWN: number; + F2: number; + F10: number; + F12: number; + } + + var support: { + touch: boolean; + pointers: boolean; + scrollbar(): number; + hasHW3D: boolean; + hasNativeScrolling: boolean; + devicePixelRatio: number; + placeHolder: boolean; + zoomLevel: number; + mobileOS: { + device: string; + tablet: any; + browser: string; + name: string; + majorVersion: string; + minorVersion: string; + flatVersion: number; + appMode: boolean; + }; + browser: { + msie: boolean; + webkit: boolean; + safari: boolean; + opera: boolean; + version: string; + }; + } + + interface TemplateOptions { + paramName?: string; + useWithBlock?: boolean; + } + + class Class { + static fn: Class; + static extend(prototype: Object): Class; + } + + class Observable extends Class { + static fn: Observable; + static extend(prototype: Object): Observable; + + bind(eventName: string, handler: Function): Observable; + one(eventName: string, handler: Function): Observable; + trigger(eventName: string, e?: any): boolean; + unbind(eventName: string, handler?: any): Observable; + } + + interface ViewOptions { + tagName?: string; + wrap?: boolean; + model?: Object; + init?: (e: ViewEvent) => void; + show?: (e: ViewEvent) => void; + hide?: (e: ViewEvent) => void; + } + + interface ViewEvent { + sender: View; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + class View extends Observable { + constructor(element: Element, options?: ViewOptions); + constructor(element: string, options?: ViewOptions); + init(element: Element, options?: ViewOptions): void; + init(element: string, options?: ViewOptions): void; + render(container?: any): JQuery; + destroy(): void; + element: JQuery; + content: any; + tagName: string; + model: Object; + } + + class ViewContainer extends Observable { + view: View; + } + + class Layout extends View { + showIn(selector: string, view: View): void; + containers: { [selector: string]: ViewContainer; }; + } + + class History extends Observable { + start(options: Object): void; + stop(): void; + current: string; + root: string; + change(callback: Function): void; + navigate(location: string, silent?: boolean): void; + } + + var history: History; + + interface RouterOptions { + init?: (e: RouterEvent) => void; + routeMissing?: (e: RouterEvent) => void; + change?: (e: RouterEvent) => void; + } + + interface RouterEvent { + sender: Router; + isDefaultPrevented(): boolean; + preventDefault: Function; + url: string; + } + + class Route extends Class { + route: RegExp; + callback(url: string): void; + worksWith(url: string): void; + } + + class Router extends Observable { + constructor(options?: RouterOptions); + init(options?: RouterOptions): void; + start(): void; + destroy(): void; + route(route: string, callback: Function): void; + navigate(location: string, silent?: boolean): void; + routes: Route[]; + } + +} + +declare module kendo.effects { + interface Element { + expand(direction: string): effects.Expand; + expandHorizontal(): effects.Expand; + expandVertical(): effects.Expand; + fade(direction: string): effects.Fade; + fadeIn(): effects.Fade; + fadeOut(): effects.Fade; + flip(axis: string, face: JQuery, back: JQuery): effects.Flip; + flipHorizontal(face: JQuery, back: JQuery): effects.Flip; + flipVertical(face: JQuery, back: JQuery): effects.Flip; + pageturn(axis: string, face: JQuery, back: JQuery): effects.PageTurn; + pageturnHorizontal(face: JQuery, back: JQuery): effects.PageTurn; + pageturnVertical(face: JQuery, back: JQuery): effects.PageTurn; + slideIn(direction: string): effects.SlideIn; + slideInDown(): effects.SlideIn; + slideInLeft(): effects.SlideIn; + slideInRight(): effects.SlideIn; + slideInUp(): effects.SlideIn; + tile(direction: string, previous: JQuery): effects.Tile; + tileDown(previous: JQuery): effects.Tile; + tileLeft(previous: JQuery): effects.Tile; + tileRight(previous: JQuery): effects.Tile; + tileUp(previous: JQuery): effects.Tile; + transfer(target: JQuery): effects.Transfer; + zoom(direction: string): effects.Zoom; + zoomIn(): effects.Zoom; + zoomOut(): effects.Zoom; + } + + interface Effect { + play(): JQueryPromise; + reverse(): JQueryPromise; + duration(value: number): Effect; + add(effect: Effect): Effect; + stop(): Effect; + } + + interface Expand extends Effect { + duration(value: number): Expand; + direction(value: string): Expand; + stop(): Expand; + add(effect: Effect): Expand; + } + + interface Fade extends Effect { + duration(value: number): Fade; + direction(value: string): Fade; + stop(): Fade; + add(effect: Effect): Fade; + startValue(value: number): Fade; + endValue(value: number): Fade; + } + + interface Flip extends Effect { + duration(value: number): Flip; + direction(value: string): Flip; + stop(): Flip; + add(effect: Effect): Flip; + } + + interface PageTurn extends Effect { + duration(value: number): PageTurn; + direction(value: string): PageTurn; + stop(): PageTurn; + add(effect: Effect): PageTurn; + } + + interface SlideIn extends Effect { + duration(value: number): SlideIn; + direction(value: string): SlideIn; + stop(): SlideIn; + add(effect: Effect): SlideIn; + } + + interface Tile extends Effect { + duration(value: number): Tile; + direction(value: string): Tile; + stop(): Tile; + add(effect: Effect): Tile; + } + + interface Transfer extends Effect { + duration(value: number): Transfer; + stop(): Transfer; + add(effect: Effect): Transfer; + } + + interface Zoom extends Effect { + duration(value: number): Zoom; + direction(value: string): Zoom; + stop(): Zoom; + add(effect: Effect): Zoom; + startValue(value: number): Zoom; + endValue(value: number): Zoom; + } +} + +declare module kendo.data { + interface ObservableObjectEvent { + sender?: ObservableObject; + field?: string; + } + + interface ObservableObjectSetEvent extends ObservableObjectEvent { + value?: any; + preventDefault?: Function; + } + + + class Binding extends Observable { + source: any; + parents: any[]; + path: string; + dependencies: { [path: string]: boolean; }; + observable: boolean; + constructor(parents: any[], path: string); + change(e: Object): void; + start(source: kendo.Observable): void; + stop(source: kendo.Observable): void; + get (): any; + set (value: any): void; + destroy(): void; + } + + class BindingTarget { + target: any; + options: any; + source: any; + } + + class EventBinding extends Binding { + get (): void; + } + + class TemplateBinding extends Binding { + constructor(source: kendo.Observable, path: string, template: Function); + render(value: Object): string; + } + + module binders { } + + interface Bindings { + [key: string]: Binding; + } + + class Binder extends Class { + static fn: Binder; + static extend(prototype: Object): Binder; + + element: any; + bindings: Bindings; + constructor(element: any, bindings: Bindings, options?: BinderOptions); + init(element: any, bindings: Bindings, options?: BinderOptions): void; + bind(binding: Binding, attribute: string): void; + destroy(): void; + refresh(): void; + refresh(attribute: string): void; + options: BinderOptions; + } + + interface BinderOptions { + } + + class ObservableObject extends Observable{ + constructor(value?: any); + init(value?: any): void; + get(name: string): any; + parent(): ObservableObject; + set(name: string, value: any): void; + toJSON(): Object; + uid: string; + } + + class Model extends ObservableObject { + idField: string; + _defaultId: any; + fields: DataSourceSchemaModelFields; + defaults: { + [field: string]: any; + }; + constructor(data?: any); + init(data?: any):void; + accept(data?: any): void; + dirty: boolean; + id: any; + editable(field: string): boolean; + isNew(): boolean; + static idField: string; + static fields: DataSourceSchemaModelFields; + static define(options: DataSourceSchemaModelWithFieldsObject): typeof Model; + static define(options: DataSourceSchemaModelWithFieldsArray): typeof Model; + } + + interface SchedulerEventData { + description?: string; + end?: Date; + endTimezone?: string; + isAllDay?: boolean; + id?: any; + start?: Date; + startTimezone?: string; + recurrenceId?: any; + recurrenceRule?: string; + recurrenceException?: string; + title?: string; + } + + class SchedulerEvent extends Model { + constructor(data?: SchedulerEventData); + init(data?: SchedulerEventData): void; + + description: string; + end: Date; + endTimezone: string; + isAllDay: boolean; + id: any; + start: Date; + startTimezone: string; + recurrenceId: any; + recurrenceRule: string; + recurrenceException: string; + title: string; + static idField: string; + static fields: DataSourceSchemaModelFields; + static define(options: DataSourceSchemaModelWithFieldsObject): typeof SchedulerEvent; + static define(options: DataSourceSchemaModelWithFieldsArray): typeof SchedulerEvent; + clone(options: any, updateUid: boolean): SchedulerEvent; + duration(): number; + expand(start: Date, end: Date, zone: any): SchedulerEvent[]; + update(eventInfo: SchedulerEventData): void; + isMultiDay(): boolean; + isException(): boolean; + isOccurrence(): boolean; + isRecurring(): boolean; + isRecurrenceHead(): boolean; + toOccurrence(options: any): SchedulerEvent; + } + + class TreeListModel extends Model { + constructor(data?: any); + init(data?: any): void; + + id: any; + parentId: any; + + loaded(value: boolean): void; + loaded(): boolean; + + static idField: string; + static fields: DataSourceSchemaModelFields; + static define(options: DataSourceSchemaModelWithFieldsObject): typeof TreeListModel; + static define(options: DataSourceSchemaModelWithFieldsArray): typeof TreeListModel; + } + + class TreeListDataSource extends DataSource { + load(model: kendo.data.TreeListModel): JQueryPromise; + childNodes(model: kendo.data.TreeListModel): kendo.data.TreeListModel[]; + rootNodes(): kendo.data.TreeListModel[]; + parentNode(model: kendo.data.TreeListModel): kendo.data.TreeListModel; + level(model: kendo.data.TreeListModel): number; + level(model: any): number; + + add(model: Object): kendo.data.TreeListModel; + add(model: kendo.data.TreeListModel): kendo.data.TreeListModel; + at(index: number): kendo.data.TreeListModel; + cancelChanges(model?: kendo.data.TreeListModel): void; + get(id: any): kendo.data.TreeListModel; + getByUid(uid: string): kendo.data.TreeListModel; + indexOf(value: kendo.data.TreeListModel): number; + insert(index: number, model: kendo.data.TreeListModel): kendo.data.TreeListModel; + insert(index: number, model: Object): kendo.data.TreeListModel; + remove(model: kendo.data.TreeListModel): void; + } + + class GanttTask extends Model { + constructor(data?: any); + init(data?: any): void; + + id: any; + parentId: number; + orderId: number; + title: string; + start: Date; + end: Date; + percentComplete: number; + summary: boolean; + expanded: boolean; + static idField: string; + static fields: DataSourceSchemaModelFields; + static define(options: DataSourceSchemaModelWithFieldsObject): typeof GanttTask; + static define(options: DataSourceSchemaModelWithFieldsArray): typeof GanttTask; + } + + class GanttDependency extends Model { + constructor(data?: any); + init(data?: any): void; + + id: any; + predecessorId: number; + successorId: number; + type: number; + static idField: string; + static fields: DataSourceSchemaModelFields; + static define(options: DataSourceSchemaModelWithFieldsObject): typeof GanttDependency; + static define(options: DataSourceSchemaModelWithFieldsArray): typeof GanttDependency; + } + + class Node extends Model { + children: HierarchicalDataSource; + + append(model: any): void; + level(): number; + load(id: any): void; + loaded(value: boolean): void; + loaded(): boolean; + parentNode(): Node; + } + + class SchedulerDataSource extends DataSource { + add(model: Object): kendo.data.SchedulerEvent; + add(model: kendo.data.SchedulerEvent): kendo.data.SchedulerEvent; + at(index: number): kendo.data.SchedulerEvent; + cancelChanges(model?: kendo.data.SchedulerEvent): void; + get(id: any): kendo.data.SchedulerEvent; + getByUid(uid: string): kendo.data.SchedulerEvent; + indexOf(value: kendo.data.SchedulerEvent): number; + insert(index: number, model: kendo.data.SchedulerEvent): kendo.data.SchedulerEvent; + insert(index: number, model: Object): kendo.data.SchedulerEvent; + remove(model: kendo.data.SchedulerEvent): void; + } + + class GanttDataSource extends DataSource { + add(model: Object): kendo.data.GanttTask; + add(model: kendo.data.GanttTask): kendo.data.GanttTask; + at(index: number): kendo.data.GanttTask; + cancelChanges(model?: kendo.data.GanttTask): void; + get(id: any): kendo.data.GanttTask; + getByUid(uid: string): kendo.data.GanttTask; + indexOf(value: kendo.data.GanttTask): number; + insert(index: number, model: Object): kendo.data.GanttTask; + insert(index: number, model: kendo.data.GanttTask): kendo.data.GanttTask; + remove(model: kendo.data.GanttTask): void; + } + + class GanttDependencyDataSource extends DataSource { + add(model: Object): kendo.data.GanttDependency; + add(model: kendo.data.GanttDependency): kendo.data.GanttDependency; + at(index: number): kendo.data.GanttDependency; + cancelChanges(model?: kendo.data.GanttDependency): void; + get(id: any): kendo.data.GanttDependency; + getByUid(uid: string): kendo.data.GanttDependency; + indexOf(value: kendo.data.GanttDependency): number; + insert(index: number, model: Object): kendo.data.GanttDependency; + insert(index: number, model: kendo.data.GanttDependency): kendo.data.GanttDependency; + remove(model: kendo.data.GanttDependency): void; + } + + class HierarchicalDataSource extends DataSource { + constructor(options?: HierarchicalDataSourceOptions); + init(options?: HierarchicalDataSourceOptions): void; + } + + interface HierarchicalDataSourceOptions extends DataSourceOptions { + schema?: HierarchicalDataSourceSchema; + } + + + interface HierarchicalDataSourceSchema extends DataSourceSchemaWithOptionsModel { + model?: HierarchicalDataSourceSchemaModel; + } + + interface HierarchicalDataSourceSchemaModel extends DataSourceSchemaModel { + hasChildren?: any; + children?: any; + } + + interface PivotDiscoverRequestRestrictionOptions { + catalogName: string; + cubeName: string; + } + + interface PivotDiscoverRequestDataOptions { + command: string; + restrictions: PivotDiscoverRequestRestrictionOptions; + } + + interface PivotDiscoverRequestOptions { + data: PivotDiscoverRequestDataOptions; + } + + interface PivotTransportConnection { + catalog?: string; + cube?: string; + } + + interface PivotTransportDiscover { + cache?: boolean; + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface PivotTransport { + discover?: any; + read?: any; + } + + interface PivotTransportWithObjectOperations extends PivotTransport { + connection: PivotTransportConnection; + discover?: PivotTransportDiscover; + read?: DataSourceTransportRead; + } + + interface PivotTransportWithFunctionOperations extends PivotTransport { + discover?: (options: DataSourceTransportOptions) => void; + read?: (options: DataSourceTransportOptions) => void; + } + + interface PivotDataSourceAxisOptions { + name: string; + expand?: boolean; + } + + interface PivotDataSourceMeasureOptions { + values: string[]; + axis?: string; + } + + interface PivotDataSourceOptions extends DataSourceOptions { + columns?: PivotDataSourceAxisOptions[]; + measures?: PivotDataSourceMeasureOptions[]; + rows?: PivotDataSourceAxisOptions[]; + transport?: PivotTransport; + schema?: PivotSchema; + } + + interface PivotTupleModel { + children: PivotTupleModel[]; + caption?: string; + name: string; + levelName?: string; + levelNum: number; + hasChildren?: boolean; + hierarchy?: string; + } + + interface PivotSchemaRowAxis { + tuples: PivotTupleModel[]; + } + + interface PivotSchemaColumnAxis { + tuples: PivotTupleModel[]; + } + + interface PivotSchemaAxes { + rows: PivotSchemaRowAxis; + columns: PivotSchemaColumnAxis; + } + + interface PivotSchema extends DataSourceSchema{ + axes?: any; + catalogs?: any; + cubes?: any; + data?: any; + dimensions?: any; + hierarchies?: any; + levels?: any; + measures?: any; + } + + class PivotDataSource extends DataSource { + axes(): PivotSchemaAxes; + constructor(options?: PivotDataSourceOptions); + init(options?: PivotDataSourceOptions): void; + catalog(val: string): void; + columns(val: string[]): string[]; + cube(val: string): void; + discover(options: PivotDiscoverRequestOptions): JQueryPromise; + measures(val: string[]): string[]; + measuresAxis(): string; + rows(val: string[]): string[]; + schemaCatalogs(): JQueryPromise; + schemaCubes(): JQueryPromise; + schemaDimensions(): JQueryPromise; + schemaHierarchies(): JQueryPromise; + schemaLevels(): JQueryPromise; + schemaMeasures(): JQueryPromise; + } + + interface DataSourceTransport { + parameterMap?(data: DataSourceTransportParameterMapData, type: string): any; + create?: DataSourceTransportCreate; + destroy?: DataSourceTransportDestroy; + push?: Function; + read?: DataSourceTransportRead; + signalr?: DataSourceTransportSignalr; + update?: DataSourceTransportUpdate; + } + + interface DataSourceTransportSignalrClient { + create?: string; + destroy?: string; + read?: string; + update?: string; + } + + interface DataSourceTransportSignalrServer { + create?: string; + destroy?: string; + read?: string; + update?: string; + } + + interface DataSourceTransportSignalr { + client?: DataSourceTransportSignalrClient; + hub?: any; + promise?: any; + server?: DataSourceTransportSignalrServer; + } + + + interface DataSourceParameterMapDataAggregate { + field?: string; + aggregate?: string; + } + + interface DataSourceParameterMapDataGroup { + aggregate?: DataSourceParameterMapDataAggregate[]; + field?: string; + dir?: string; + } + + interface DataSourceParameterMapDataFilter { + field?: string; + filters?: DataSourceParameterMapDataFilter[]; + logic?: string; + operator?: string; + value?: any; + } + + interface DataSourceParameterMapDataSort { + field?: string; + dir?: string; + } + + interface DataSourceTransportParameterMapData { + aggregate?: DataSourceParameterMapDataAggregate[]; + group?: DataSourceParameterMapDataGroup[]; + filter?: DataSourceParameterMapDataFilter; + models?: Model[]; + page?: number; + pageSize?: number; + skip?: number; + sort?: DataSourceParameterMapDataSort[]; + take?: number; + } + + interface DataSourceSchema { + model?: any; + } + + interface DataSourceSchemaWithOptionsModel extends DataSourceSchema { + model?: DataSourceSchemaModel; + } + + interface DataSourceSchemaWithConstructorModel extends DataSourceSchema { + model?: typeof Model; + } + + interface DataSourceSchemaModel { + id?: string; + fields?: any; + } + + interface DataSourceSchemaModelWithFieldsArray extends DataSourceSchemaModel { + fields?: DataSourceSchemaModelField[]; + } + + interface DataSourceSchemaModelWithFieldsObject extends DataSourceSchemaModel { + fields?: DataSourceSchemaModelFields; + } + + interface DataSourceSchemaModelFields { + [index: string]: DataSourceSchemaModelField; + } + + interface DataSourceSchemaModelField { + field?: string; + from?: string; + defaultValue?: any; + editable?: boolean; + nullable?: boolean; + parse?: Function; + type?: string; + validation?: DataSourceSchemaModelFieldValidation; + } + + interface DataSourceSchemaModelFieldValidation { + required?: boolean; + min?: any; + max?: any; + } + + class ObservableArray extends Observable { + constructor(array: any[]); + init(array: any[]): void; + [index: number]: any; + + empty(): void; + every(callback: (item: Object, index: number, source: ObservableArray) => boolean): boolean; + filter(callback: (item: Object, index: number, source: ObservableArray) => boolean): any[]; + find(callback: (item: Object, index: number, source: ObservableArray) => boolean): any; + forEach(callback: (item: Object, index: number, source: ObservableArray) => void ): void; + indexOf(item: any): number; + join(separator: string): string; + length: number; + map(callback: (item: Object, index: number, source: ObservableArray) => any): any[]; + parent(): ObservableObject; + pop(): ObservableObject; + push(...items: any[]): number; + remove(item: Object): void; + shift(): any; + slice(begin: number, end?: number): any[]; + some(callback: (item: Object, index: number, source: ObservableArray) => boolean): boolean; + splice(start: number): any[]; + splice(start: number, deleteCount: number, ...items: any[]): any[]; + toJSON(): any[]; + unshift(...items: any[]): number; + wrap(object: Object, parent: Object): any; + wrapAll(source: Object, target: Object): any; + } + + interface ObservableArrayEvent { + field?: string; + action?: string; + index?: number; + items?: kendo.data.Model[]; + } + + class DataSource extends Observable{ + constructor(options?: DataSourceOptions); + init(options?: DataSourceOptions): void; + static create(options?: DataSourceOptions): DataSource; + options: DataSourceOptions; + add(model: Object): kendo.data.Model; + add(model: kendo.data.Model): kendo.data.Model; + aggregate(val: any): void; + aggregate(): any; + aggregates(): any; + at(index: number): kendo.data.ObservableObject; + cancelChanges(model?: kendo.data.Model): void; + data(): kendo.data.ObservableArray; + data(value: any): void; + fetch(callback?: Function): JQueryPromise; + filter(filters: DataSourceFilterItem): void; + filter(filters: DataSourceFilterItem[]): void; + filter(filters: DataSourceFilters): void; + filter(): DataSourceFilters; + get(id: any): kendo.data.Model; + getByUid(uid: string): kendo.data.Model; + group(groups: any): void; + group(): any; + hasChanges(): boolean; + indexOf(value: kendo.data.ObservableObject): number; + insert(index: number, model: kendo.data.Model): kendo.data.Model; + insert(index: number, model: Object): kendo.data.Model; + online(value: boolean): void; + online(): boolean; + offlineData(data: any[]): void; + offlineData(): any[]; + page(): number; + page(page: number): void; + pageSize(): number; + pageSize(size: number): void; + query(options?: any): JQueryPromise; + read(data?: any): JQueryPromise; + remove(model: kendo.data.ObservableObject): void; + sort(sort: DataSourceSortItem): void; + sort(sort: DataSourceSortItem[]): void; + sort(): DataSourceSortItem[]; + sync(): JQueryPromise; + total(): number; + totalPages(): number; + view(): kendo.data.ObservableArray; + } + + interface DataSourceAggregateItem { + field?: string; + aggregate?: string; + } + + interface DataSourceFilter { + } + + interface DataSourceFilterItem extends DataSourceFilter { + operator?: string; + field?: string; + value?: any; + } + + interface DataSourceFilters extends DataSourceFilter { + logic?: string; + filters?: DataSourceFilter[]; + } + + interface DataSourceGroupItemAggregate { + field?: string; + aggregate?: string; + } + + interface DataSourceGroupItem { + field?: string; + dir?: string; + aggregates?: DataSourceGroupItemAggregate[]; + } + + interface DataSourceSchema { + aggregates?: any; + data?: any; + errors?: any; + groups?: any; + parse?: Function; + total?: any; + type?: string; + } + + interface DataSourceSortItem { + field?: string; + dir?: string; + } + + interface DataSourceTransportCreate { + cache?: boolean; + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface DataSourceTransportDestroy { + cache?: boolean; + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface DataSourceTransportRead { + cache?: boolean; + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface DataSourceTransportUpdate { + cache?: boolean; + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface DataSourceTransportWithObjectOperations extends DataSourceTransport { + create?: DataSourceTransportCreate; + destroy?: DataSourceTransportDestroy; + read?: DataSourceTransportRead; + update?: DataSourceTransportUpdate; + } + + interface DataSourceTransportWithFunctionOperations extends DataSourceTransport { + create?: (options: DataSourceTransportOptions) => void; + destroy?: (options: DataSourceTransportOptions) => void; + read?: (options: DataSourceTransportReadOptions) => void; + update?: (options: DataSourceTransportOptions) => void; + } + + interface DataSourceTransportOptions { + success: (data?: any) => void; + error: (error?: any) => void; + data: any; + } + + interface DataSourceTransportReadOptionsData { + sort?: DataSourceSortItem[]; + filter?: DataSourceFilters; + group?: DataSourceGroupItem[]; + take?: number; + skip?: number; + } + + interface DataSourceTransportReadOptions extends DataSourceTransportOptions { + data: DataSourceTransportReadOptionsData; + } + + interface DataSourceTransportBatchOptionsData { + models: any[]; + } + + interface DataSourceTransportBatchOptions extends DataSourceTransportOptions { + data: DataSourceTransportBatchOptionsData; + } + + interface DataSourceOptions { + aggregate?: DataSourceAggregateItem[]; + autoSync?: boolean; + batch?: boolean; + data?: any; + filter?: any; + group?: DataSourceGroupItem[]; + offlineStorage?: any; + page?: number; + pageSize?: number; + schema?: DataSourceSchema; + serverAggregates?: boolean; + serverFiltering?: boolean; + serverGrouping?: boolean; + serverPaging?: boolean; + serverSorting?: boolean; + sort?: any; + transport?: DataSourceTransport; + type?: string; + change? (e: DataSourceChangeEvent): void; + error?(e: DataSourceErrorEvent): void; + sync?(e: DataSourceEvent): void; + requestStart?(e: DataSourceRequestStartEvent): void; + requestEnd?(e: DataSourceRequestEndEvent): void; + } + + interface DataSourceEvent { + sender?: DataSource; + } + + interface DataSourceItemOrGroup { + } + + interface DataSourceGroup extends DataSourceItemOrGroup { + aggregates: any[]; + field: string; + hasSubgroups: boolean; + items: DataSourceItemOrGroup[]; + value: any; + } + + interface DataSourceChangeEvent extends DataSourceEvent { + field?: string; + value?: Model; + action?: string; + index?: number; + items?: DataSourceItemOrGroup[]; + node?: any; + } + + interface DataSourceErrorEvent extends DataSourceEvent { + xhr: JQueryXHR; + status: string; + errorThrown: any; + errors?: any; + } + + interface DataSourceRequestStartEvent extends DataSourceEvent { + type?: string; + } + + interface DataSourceRequestEndEvent extends DataSourceEvent { + response?: any; + type?: string; + } +} + +declare module kendo.data.transports { + var odata : DataSourceTransport; +} + +declare module kendo.ui { + function progress(container: JQuery, toggle: boolean): void; + + class Widget extends Observable { + static fn: Widget; + static extend(prototype: Object): Widget; + + constructor(element: Element, options?: Object); + constructor(element: JQuery, options?: Object); + constructor(selector: String, options?: Object); + init(element: Element, options?: Object): void; + init(element: JQuery, options?: Object): void; + init(selector: String, options?: Object): void; + destroy(): void; + element: JQuery; + setOptions(options: Object): void; + resize(force?: boolean): void; + options: Object; + events: string[]; + } + + function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.ui, prefix?: String): void; + function plugin(widget: any, register?: typeof kendo.ui, prefix?: String): void; + function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.mobile.ui, prefix?: String): void; + function plugin(widget: any, register?: typeof kendo.mobile.ui, prefix?: String): void; + function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.dataviz.ui, prefix?: String): void; + function plugin(widget: any, register?: typeof kendo.dataviz.ui, prefix?: String): void; + + class Draggable extends kendo.ui.Widget{ + element: JQuery; + currentTarget: JQuery; + constructor(element: Element, options?: DraggableOptions); + options: DraggableOptions; + } + + interface DraggableEvent { + sender?: Draggable; + } + + class DropTarget extends kendo.ui.Widget{ + element: JQuery; + constructor(element: Element, options?: DropTargetOptions); + options: DropTargetOptions; + static destroyGroup(groupName: string): void; + } + + interface DropTargetOptions { + group?: string; + dragenter?(e: DropTargetDragenterEvent): void; + dragleave?(e: DropTargetDragleaveEvent): void; + drop?(e: DropTargetDropEvent): void; + } + + interface DropTargetEvent { + sender?: DropTarget; + } + + interface DropTargetDragenterEvent extends DropTargetEvent { + draggable?: kendo.ui.Draggable; + } + + interface DropTargetDragleaveEvent extends DropTargetEvent { + draggable?: kendo.ui.Draggable; + } + + interface DropTargetDropEvent extends DropTargetEvent { + draggable?: kendo.ui.Draggable; + } + + class DropTargetArea extends kendo.ui.Widget{ + element: JQuery; + constructor(element: Element, options?: DropTargetAreaOptions); + options: DropTargetAreaOptions; + } + + interface DropTargetAreaOptions { + group?: string; + filter?: string; + dragenter?(e: DropTargetAreaDragenterEvent): void; + dragleave?(e: DropTargetAreaDragleaveEvent): void; + drop?(e: DropTargetAreaDropEvent): void; + } + + interface DropTargetAreaEvent { + sender: DropTargetArea; + } + + interface DropTargetAreaDragenterEvent extends DropTargetAreaEvent { + draggable?: JQuery; + dropTarget?: JQuery; + } + + interface DropTargetAreaDragleaveEvent extends DropTargetAreaEvent { + draggable?: JQuery; + dropTarget?: JQuery; + } + + interface DropTargetAreaDropEvent extends DropTargetAreaEvent { + draggable?: kendo.ui.Draggable; + dropTarget?: JQuery; + } + + interface DraggableOptions { + axis?: string; + container?: JQuery; + cursorOffset?: any; + distance?: number; + filter?: string; + group?: string; + hint?: Function; + ignore?: string; + drag?(e: DraggableEvent): void; + dragcancel?(e: DraggableEvent): void; + dragend?(e: DraggableEvent): void; + dragstart?(e: DraggableEvent): void; + } + + interface GridColumnEditorOptions { + field?: string; + format?: string; + model?: kendo.data.Model; + values?: any[]; + } + + interface GridColumn { + editor?(container: JQuery, options: GridColumnEditorOptions): void; + } +} + +declare module kendo.mobile { + function init(selector: string): void; + function init(element: JQuery): void; + function init(element: Element): void; + + class Application extends Observable { + constructor(element?: any, options?: ApplicationOptions); + init(element?: any, options?: ApplicationOptions): void; + options: ApplicationOptions; + hideLoading(): void; + navigate(url: string, transition?: string): void; + scroller(): kendo.mobile.ui.Scroller; + showLoading(): void; + view(): kendo.mobile.ui.View; + router: kendo.Router; + pane: kendo.mobile.ui.Pane; + } + + interface ApplicationOptions { + hideAddressBar?: boolean; + updateDocumentTitle?: boolean; + initial?: string; + layout?: string; + loading?: string; + platform?: string; + serverNavigation?: boolean; + transition?: string; + } + + interface ApplicationEvent { + sender: Application; + } +} + +declare module kendo.mobile.ui { + + class Widget extends kendo.ui.Widget { + } + + interface TouchAxis { + location?: number; + startLocation?: number; + client?: number; + delta?: number; + velocity?: number; + } + + interface TouchEventOptions { + target?: JQuery; + x?: TouchAxis; + y?: TouchAxis; + } + + interface Point { + x?: number; + y?: number; + } +} +declare module kendo.dataviz.ui { + function registerTheme(name: string, options: any): void; + + function plugin(widget: typeof kendo.ui.Widget): void; + function plugin(widget: any): void; +} + +declare module kendo.dataviz.map { + class Marker { + } +} + +declare module kendo.dataviz.map.layer { + class Shape { + } +} + +declare module kendo.drawing { + class Arc extends kendo.drawing.Element { + constructor(options?: ArcOptions); + options: ArcOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + geometry(): kendo.geometry.Arc; + geometry(value: kendo.geometry.Arc): void; + fill(color: string, opacity?: number): kendo.drawing.Arc; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Arc; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface ArcOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface ArcEvent { + sender: Arc; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Circle extends kendo.drawing.Element { + constructor(options?: CircleOptions); + options: CircleOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + geometry(): kendo.geometry.Circle; + geometry(value: kendo.geometry.Circle): void; + fill(color: string, opacity?: number): kendo.drawing.Circle; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Circle; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface CircleOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface CircleEvent { + sender: Circle; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Element extends kendo.Class { + constructor(options?: ElementOptions); + options: ElementOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + opacity(): number; + opacity(opacity: number): void; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface ElementOptions { + name?: string; + clip?: kendo.drawing.Path; + opacity?: number; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface ElementEvent { + sender: Element; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + interface FillOptions { + color: string; + opacity: number; + } + + + + class Gradient extends kendo.Class { + constructor(options?: GradientOptions); + options: GradientOptions; + addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop; + removeStop(stop: kendo.drawing.GradientStop): void; + stops: any; + } + + interface GradientOptions { + name?: string; + stops?: any; + } + interface GradientEvent { + sender: Gradient; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class GradientStop extends kendo.Class { + constructor(options?: GradientStopOptions); + options: GradientStopOptions; + } + + interface GradientStopOptions { + name?: string; + offset?: number; + color?: string; + opacity?: number; + } + interface GradientStopEvent { + sender: GradientStop; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Group extends kendo.drawing.Element { + constructor(options?: GroupOptions); + options: GroupOptions; + append(element: kendo.drawing.Element): void; + clear(): void; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + opacity(): number; + opacity(opacity: number): void; + remove(element: kendo.drawing.Element): void; + removeAt(index: number): void; + visible(): boolean; + visible(visible: boolean): void; + children: any; + } + + interface GroupOptions { + name?: string; + clip?: kendo.drawing.Path; + opacity?: number; + pdf?: kendo.drawing.PDFOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface GroupEvent { + sender: Group; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Image extends kendo.drawing.Element { + constructor(options?: ImageOptions); + options: ImageOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + opacity(): number; + opacity(opacity: number): void; + src(): string; + src(value: string): void; + rect(): kendo.geometry.Rect; + rect(value: kendo.geometry.Rect): void; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface ImageOptions { + name?: string; + clip?: kendo.drawing.Path; + opacity?: number; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface ImageEvent { + sender: Image; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Layout extends kendo.drawing.Group { + constructor(options?: LayoutOptions); + options: LayoutOptions; + rect(): kendo.geometry.Rect; + rect(rect: kendo.geometry.Rect): void; + reflow(): void; + } + + interface LayoutOptions { + name?: string; + alignContent?: string; + alignItems?: string; + justifyContent?: string; + lineSpacing?: number; + spacing?: number; + orientation?: string; + wrap?: boolean; + } + interface LayoutEvent { + sender: Layout; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class LinearGradient extends kendo.drawing.Gradient { + constructor(options?: LinearGradientOptions); + options: LinearGradientOptions; + addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop; + end(): kendo.geometry.Point; + end(end: any): void; + end(end: kendo.geometry.Point): void; + start(): kendo.geometry.Point; + start(start: any): void; + start(start: kendo.geometry.Point): void; + removeStop(stop: kendo.drawing.GradientStop): void; + stops: any; + } + + interface LinearGradientOptions { + name?: string; + stops?: any; + } + interface LinearGradientEvent { + sender: LinearGradient; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class MultiPath extends kendo.drawing.Element { + constructor(options?: MultiPathOptions); + options: MultiPathOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + close(): kendo.drawing.MultiPath; + curveTo(controlOut: any, controlIn: any): kendo.drawing.MultiPath; + curveTo(controlOut: any, controlIn: kendo.geometry.Point): kendo.drawing.MultiPath; + curveTo(controlOut: kendo.geometry.Point, controlIn: any): kendo.drawing.MultiPath; + curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point): kendo.drawing.MultiPath; + fill(color: string, opacity?: number): kendo.drawing.MultiPath; + lineTo(x: number, y?: number): kendo.drawing.MultiPath; + lineTo(x: any, y?: number): kendo.drawing.MultiPath; + lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath; + moveTo(x: number, y?: number): kendo.drawing.MultiPath; + moveTo(x: any, y?: number): kendo.drawing.MultiPath; + moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.MultiPath; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + paths: any; + } + + interface MultiPathOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface MultiPathEvent { + sender: MultiPath; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class OptionsStore extends kendo.Class { + options: OptionsStoreOptions; + get(field: string): any; + set(field: string, value: any): void; + observer: any; + } + + interface OptionsStoreOptions { + name?: string; + } + interface OptionsStoreEvent { + sender: OptionsStore; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + interface PDFOptions { + creator: string; + date: Date; + keywords: string; + landscape: boolean; + margin: any; + paperSize: any; + subject: string; + title: string; + } + + + + class Path extends kendo.drawing.Element { + constructor(options?: PathOptions); + options: PathOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + close(): kendo.drawing.Path; + curveTo(controlOut: any, controlIn: any): kendo.drawing.Path; + curveTo(controlOut: any, controlIn: kendo.geometry.Point): kendo.drawing.Path; + curveTo(controlOut: kendo.geometry.Point, controlIn: any): kendo.drawing.Path; + curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point): kendo.drawing.Path; + fill(color: string, opacity?: number): kendo.drawing.Path; + lineTo(x: number, y?: number): kendo.drawing.Path; + lineTo(x: any, y?: number): kendo.drawing.Path; + lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path; + moveTo(x: number, y?: number): kendo.drawing.Path; + moveTo(x: any, y?: number): kendo.drawing.Path; + moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Path; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + static fromPoints(points: any): kendo.drawing.Path; + static fromRect(rect: kendo.geometry.Rect): kendo.drawing.Path; + static parse(svgPath: string, options?: any): kendo.drawing.Path; + segments: any; + } + + interface PathOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface PathEvent { + sender: Path; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class RadialGradient extends kendo.drawing.Gradient { + constructor(options?: RadialGradientOptions); + options: RadialGradientOptions; + addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop; + center(): kendo.geometry.Point; + center(center: any): void; + center(center: kendo.geometry.Point): void; + radius(): number; + radius(value: number): void; + removeStop(stop: kendo.drawing.GradientStop): void; + stops: any; + } + + interface RadialGradientOptions { + name?: string; + center?: any; + radius?: number; + stops?: any; + } + interface RadialGradientEvent { + sender: RadialGradient; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Segment extends kendo.Class { + options: SegmentOptions; + anchor(): kendo.geometry.Point; + anchor(value: kendo.geometry.Point): void; + controlIn(): kendo.geometry.Point; + controlIn(value: kendo.geometry.Point): void; + controlOut(): kendo.geometry.Point; + controlOut(value: kendo.geometry.Point): void; + } + + interface SegmentOptions { + name?: string; + } + interface SegmentEvent { + sender: Segment; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + interface StrokeOptions { + color: string; + dashType: string; + lineCap: string; + lineJoin: string; + opacity: number; + width: number; + } + + + + class Surface extends kendo.Observable { + constructor(options?: SurfaceOptions); + options: SurfaceOptions; + clear(): void; + draw(element: kendo.drawing.Element): void; + eventTarget(e: any): kendo.drawing.Element; + resize(force?: boolean): void; + static create(element: JQuery, options?: any): kendo.drawing.Surface; + static create(element: Element, options?: any): kendo.drawing.Surface; + } + + interface SurfaceOptions { + name?: string; + type?: string; + height?: string; + width?: string; + click?(e: SurfaceClickEvent): void; + mouseenter?(e: SurfaceMouseenterEvent): void; + mouseleave?(e: SurfaceMouseleaveEvent): void; + } + interface SurfaceEvent { + sender: Surface; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SurfaceClickEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + originalEvent?: any; + } + + interface SurfaceMouseenterEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + originalEvent?: any; + } + + interface SurfaceMouseleaveEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + originalEvent?: any; + } + + + class Text extends kendo.drawing.Element { + constructor(options?: TextOptions); + options: TextOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + content(): string; + content(value: string): void; + fill(color: string, opacity?: number): kendo.drawing.Text; + opacity(): number; + opacity(opacity: number): void; + position(): kendo.geometry.Point; + position(value: kendo.geometry.Point): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Text; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface TextOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + font?: string; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface TextEvent { + sender: Text; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} +declare module kendo.geometry { + class Arc extends Observable { + options: ArcOptions; + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Circle extends Observable { + options: CircleOptions; + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + center: kendo.geometry.Point; + radius: number; + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Matrix extends Observable { + options: MatrixOptions; + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Point extends Observable { + options: PointOptions; + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + x: number; + y: number; + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Rect extends Observable { + options: RectOptions; + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; + static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Size extends Observable { + options: SizeOptions; + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + width: number; + height: number; + } + + interface SizeOptions { + name?: string; + } + interface SizeEvent { + sender: Size; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Transformation extends Observable { + options: TransformationOptions; + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} +declare module kendo.ui { + class AutoComplete extends kendo.ui.Widget { + static fn: AutoComplete; + static extend(proto: Object): AutoComplete; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: AutoCompleteOptions); + options: AutoCompleteOptions; + dataSource: kendo.data.DataSource; + close(): void; + dataItem(index: number): any; + destroy(): void; + enable(enable: boolean): void; + focus(): void; + readonly(readonly: boolean): void; + refresh(): void; + search(word: string): void; + select(item: string): void; + select(item: Element): void; + select(item: JQuery): void; + setDataSource(dataSource: kendo.data.DataSource): void; + suggest(value: string): void; + value(): string; + value(value: string): void; + list: JQuery; + ul: JQuery; + } + + interface AutoCompleteAnimationClose { + duration?: number; + effects?: string; + } + + interface AutoCompleteAnimationOpen { + duration?: number; + effects?: string; + } + + interface AutoCompleteAnimation { + close?: AutoCompleteAnimationClose; + open?: AutoCompleteAnimationOpen; + } + + interface AutoCompleteVirtual { + itemHeight?: number; + valueMapper?: Function; + } + + interface AutoCompleteOptions { + name?: string; + animation?: AutoCompleteAnimation; + dataSource?: any; + dataTextField?: string; + delay?: number; + enable?: boolean; + filter?: string; + fixedGroupTemplate?: any; + groupTemplate?: any; + height?: number; + highlightFirst?: boolean; + ignoreCase?: boolean; + minLength?: number; + placeholder?: string; + separator?: string; + suggest?: boolean; + headerTemplate?: any; + template?: any; + valuePrimitive?: boolean; + virtual?: AutoCompleteVirtual; + change?(e: AutoCompleteChangeEvent): void; + close?(e: AutoCompleteCloseEvent): void; + dataBound?(e: AutoCompleteDataBoundEvent): void; + filtering?(e: AutoCompleteFilteringEvent): void; + open?(e: AutoCompleteOpenEvent): void; + select?(e: AutoCompleteSelectEvent): void; + } + interface AutoCompleteEvent { + sender: AutoComplete; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface AutoCompleteChangeEvent extends AutoCompleteEvent { + } + + interface AutoCompleteCloseEvent extends AutoCompleteEvent { + } + + interface AutoCompleteDataBoundEvent extends AutoCompleteEvent { + } + + interface AutoCompleteFilteringEvent extends AutoCompleteEvent { + filter?: any; + } + + interface AutoCompleteOpenEvent extends AutoCompleteEvent { + } + + interface AutoCompleteSelectEvent extends AutoCompleteEvent { + item?: JQuery; + } + + + class Button extends kendo.ui.Widget { + static fn: Button; + static extend(proto: Object): Button; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ButtonOptions); + options: ButtonOptions; + enable(toggle: boolean): void; + } + + interface ButtonOptions { + name?: string; + enable?: boolean; + icon?: string; + imageUrl?: string; + spriteCssClass?: string; + click?(e: ButtonClickEvent): void; + } + interface ButtonEvent { + sender: Button; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ButtonClickEvent extends ButtonEvent { + event?: any; + } + + + class Calendar extends kendo.ui.Widget { + static fn: Calendar; + static extend(proto: Object): Calendar; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: CalendarOptions); + options: CalendarOptions; + current(): Date; + destroy(): void; + max(): Date; + max(value: Date): void; + max(value: string): void; + min(): Date; + min(value: Date): void; + min(value: string): void; + navigate(value: Date, view: string): void; + navigateDown(value: Date): void; + navigateToFuture(): void; + navigateToPast(): void; + navigateUp(): void; + value(): Date; + value(value: Date): void; + value(value: string): void; + view(): any; + } + + interface CalendarMonth { + content?: string; + empty?: string; + } + + interface CalendarOptions { + name?: string; + culture?: string; + dates?: any; + depth?: string; + footer?: any; + format?: string; + max?: Date; + min?: Date; + month?: CalendarMonth; + start?: string; + value?: Date; + change?(e: CalendarEvent): void; + navigate?(e: CalendarEvent): void; + } + interface CalendarEvent { + sender: Calendar; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class ColorPalette extends kendo.ui.Widget { + static fn: ColorPalette; + static extend(proto: Object): ColorPalette; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ColorPaletteOptions); + options: ColorPaletteOptions; + value(): string; + value(color?: string): void; + color(): kendo.Color; + color(color?: kendo.Color): void; + enable(enable?: boolean): void; + } + + interface ColorPaletteTileSize { + width?: number; + height?: number; + } + + interface ColorPaletteOptions { + name?: string; + palette?: any; + columns?: number; + tileSize?: ColorPaletteTileSize; + value?: string; + change?(e: ColorPaletteEvent): void; + } + interface ColorPaletteEvent { + sender: ColorPalette; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class ColorPicker extends kendo.ui.Widget { + static fn: ColorPicker; + static extend(proto: Object): ColorPicker; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ColorPickerOptions); + options: ColorPickerOptions; + close(): void; + open(): void; + toggle(): void; + value(): string; + value(color?: string): void; + color(): kendo.Color; + color(color?: kendo.Color): void; + enable(enable?: boolean): void; + } + + interface ColorPickerMessages { + apply?: string; + cancel?: string; + } + + interface ColorPickerTileSize { + width?: number; + height?: number; + } + + interface ColorPickerOptions { + name?: string; + buttons?: boolean; + columns?: number; + tileSize?: ColorPickerTileSize; + messages?: ColorPickerMessages; + palette?: any; + opacity?: boolean; + preview?: boolean; + toolIcon?: string; + value?: string; + change?(e: ColorPickerChangeEvent): void; + select?(e: ColorPickerSelectEvent): void; + open?(e: ColorPickerEvent): void; + close?(e: ColorPickerEvent): void; + } + interface ColorPickerEvent { + sender: ColorPicker; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ColorPickerChangeEvent extends ColorPickerEvent { + value?: string; + } + + interface ColorPickerSelectEvent extends ColorPickerEvent { + value?: string; + } + + + class ComboBox extends kendo.ui.Widget { + static fn: ComboBox; + static extend(proto: Object): ComboBox; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ComboBoxOptions); + options: ComboBoxOptions; + dataSource: kendo.data.DataSource; + close(): void; + dataItem(index?: number): any; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + focus(): void; + open(): void; + refresh(): void; + search(word: string): void; + select(): number; + select(li: JQuery): void; + select(li: number): void; + select(li: Function): void; + setDataSource(dataSource: kendo.data.DataSource): void; + suggest(value: string): void; + text(): string; + text(text: string): void; + toggle(toggle: boolean): void; + value(): string; + value(value: string): void; + input: JQuery; + list: JQuery; + ul: JQuery; + } + + interface ComboBoxAnimationClose { + effects?: string; + duration?: number; + } + + interface ComboBoxAnimationOpen { + effects?: string; + duration?: number; + } + + interface ComboBoxAnimation { + close?: ComboBoxAnimationClose; + open?: ComboBoxAnimationOpen; + } + + interface ComboBoxVirtual { + itemHeight?: number; + valueMapper?: Function; + } + + interface ComboBoxOptions { + name?: string; + animation?: ComboBoxAnimation; + autoBind?: boolean; + cascadeFrom?: string; + cascadeFromField?: string; + dataSource?: any; + dataTextField?: string; + dataValueField?: string; + delay?: number; + enable?: boolean; + filter?: string; + fixedGroupTemplate?: any; + groupTemplate?: any; + height?: number; + highlightFirst?: boolean; + ignoreCase?: string; + index?: number; + minLength?: number; + placeholder?: string; + suggest?: boolean; + headerTemplate?: any; + template?: any; + text?: string; + value?: string; + valuePrimitive?: boolean; + virtual?: ComboBoxVirtual; + change?(e: ComboBoxChangeEvent): void; + close?(e: ComboBoxCloseEvent): void; + dataBound?(e: ComboBoxDataBoundEvent): void; + filtering?(e: ComboBoxFilteringEvent): void; + open?(e: ComboBoxOpenEvent): void; + select?(e: ComboBoxSelectEvent): void; + cascade?(e: ComboBoxCascadeEvent): void; + } + interface ComboBoxEvent { + sender: ComboBox; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ComboBoxChangeEvent extends ComboBoxEvent { + } + + interface ComboBoxCloseEvent extends ComboBoxEvent { + } + + interface ComboBoxDataBoundEvent extends ComboBoxEvent { + } + + interface ComboBoxFilteringEvent extends ComboBoxEvent { + filter?: any; + } + + interface ComboBoxOpenEvent extends ComboBoxEvent { + } + + interface ComboBoxSelectEvent extends ComboBoxEvent { + item?: JQuery; + } + + interface ComboBoxCascadeEvent extends ComboBoxEvent { + } + + + class ContextMenu extends kendo.ui.Widget { + static fn: ContextMenu; + static extend(proto: Object): ContextMenu; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ContextMenuOptions); + options: ContextMenuOptions; + append(item: any, referenceItem: string): kendo.ui.ContextMenu; + append(item: any, referenceItem: JQuery): kendo.ui.ContextMenu; + close(element: Element): kendo.ui.ContextMenu; + close(element: JQuery): kendo.ui.ContextMenu; + destroy(): void; + enable(element: string, enable: boolean): kendo.ui.ContextMenu; + enable(element: Element, enable: boolean): kendo.ui.ContextMenu; + enable(element: JQuery, enable: boolean): kendo.ui.ContextMenu; + insertAfter(item: string, referenceItem: string): kendo.ui.ContextMenu; + insertAfter(item: string, referenceItem: Element): kendo.ui.ContextMenu; + insertAfter(item: string, referenceItem: JQuery): kendo.ui.ContextMenu; + insertAfter(item: Element, referenceItem: string): kendo.ui.ContextMenu; + insertAfter(item: Element, referenceItem: Element): kendo.ui.ContextMenu; + insertAfter(item: Element, referenceItem: JQuery): kendo.ui.ContextMenu; + insertAfter(item: JQuery, referenceItem: string): kendo.ui.ContextMenu; + insertAfter(item: JQuery, referenceItem: Element): kendo.ui.ContextMenu; + insertAfter(item: JQuery, referenceItem: JQuery): kendo.ui.ContextMenu; + insertBefore(item: string, referenceItem: string): kendo.ui.ContextMenu; + insertBefore(item: string, referenceItem: Element): kendo.ui.ContextMenu; + insertBefore(item: string, referenceItem: JQuery): kendo.ui.ContextMenu; + insertBefore(item: Element, referenceItem: string): kendo.ui.ContextMenu; + insertBefore(item: Element, referenceItem: Element): kendo.ui.ContextMenu; + insertBefore(item: Element, referenceItem: JQuery): kendo.ui.ContextMenu; + insertBefore(item: JQuery, referenceItem: string): kendo.ui.ContextMenu; + insertBefore(item: JQuery, referenceItem: Element): kendo.ui.ContextMenu; + insertBefore(item: JQuery, referenceItem: JQuery): kendo.ui.ContextMenu; + open(x: number, y: number): kendo.ui.ContextMenu; + open(x: Element, y: number): kendo.ui.ContextMenu; + open(x: JQuery, y: number): kendo.ui.ContextMenu; + remove(element: string): kendo.ui.ContextMenu; + remove(element: Element): kendo.ui.ContextMenu; + remove(element: JQuery): kendo.ui.ContextMenu; + } + + interface ContextMenuAnimationClose { + effects?: string; + duration?: number; + } + + interface ContextMenuAnimationOpen { + effects?: string; + duration?: number; + } + + interface ContextMenuAnimation { + close?: ContextMenuAnimationClose; + open?: ContextMenuAnimationOpen; + } + + interface ContextMenuOptions { + name?: string; + alignToAnchor?: boolean; + animation?: ContextMenuAnimation; + closeOnClick?: boolean; + dataSource?: any; + direction?: string; + filter?: string; + hoverDelay?: number; + orientation?: string; + popupCollision?: string; + showOn?: string; + target?: any; + close?(e: ContextMenuCloseEvent): void; + open?(e: ContextMenuOpenEvent): void; + activate?(e: ContextMenuActivateEvent): void; + deactivate?(e: ContextMenuDeactivateEvent): void; + select?(e: ContextMenuSelectEvent): void; + } + interface ContextMenuEvent { + sender: ContextMenu; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ContextMenuCloseEvent extends ContextMenuEvent { + item?: Element; + type?: string; + target?: Element; + event?: JQueryEventObject; + } + + interface ContextMenuOpenEvent extends ContextMenuEvent { + item?: Element; + type?: string; + target?: Element; + event?: JQueryEventObject; + } + + interface ContextMenuActivateEvent extends ContextMenuEvent { + item?: Element; + type?: string; + target?: Element; + } + + interface ContextMenuDeactivateEvent extends ContextMenuEvent { + item?: Element; + type?: string; + target?: Element; + } + + interface ContextMenuSelectEvent extends ContextMenuEvent { + item?: Element; + type?: string; + target?: Element; + } + + + class DatePicker extends kendo.ui.Widget { + static fn: DatePicker; + static extend(proto: Object): DatePicker; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: DatePickerOptions); + options: DatePickerOptions; + close(): void; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + max(): Date; + max(value: Date): void; + max(value: string): void; + min(): Date; + min(value: Date): void; + min(value: string): void; + open(): void; + setOptions(options: any): void; + value(): Date; + value(value: Date): void; + value(value: string): void; + } + + interface DatePickerAnimationClose { + effects?: string; + duration?: number; + } + + interface DatePickerAnimationOpen { + effects?: string; + duration?: number; + } + + interface DatePickerAnimation { + close?: DatePickerAnimationClose; + open?: DatePickerAnimationOpen; + } + + interface DatePickerMonth { + content?: string; + empty?: string; + } + + interface DatePickerOptions { + name?: string; + animation?: DatePickerAnimation; + ARIATemplate?: string; + culture?: string; + dates?: any; + depth?: string; + footer?: any; + format?: string; + max?: Date; + min?: Date; + month?: DatePickerMonth; + parseFormats?: any; + start?: string; + value?: Date; + change?(e: DatePickerChangeEvent): void; + close?(e: DatePickerCloseEvent): void; + open?(e: DatePickerOpenEvent): void; + } + interface DatePickerEvent { + sender: DatePicker; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface DatePickerChangeEvent extends DatePickerEvent { + } + + interface DatePickerCloseEvent extends DatePickerEvent { + } + + interface DatePickerOpenEvent extends DatePickerEvent { + } + + + class DateTimePicker extends kendo.ui.Widget { + static fn: DateTimePicker; + static extend(proto: Object): DateTimePicker; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: DateTimePickerOptions); + options: DateTimePickerOptions; + close(view: string): void; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + max(): Date; + max(value: Date): void; + max(value: string): void; + min(): Date; + min(value: Date): void; + min(value: string): void; + open(view: string): void; + setOptions(options: any): void; + toggle(view: string): void; + value(): Date; + value(value: Date): void; + value(value: string): void; + } + + interface DateTimePickerAnimationClose { + effects?: string; + duration?: number; + } + + interface DateTimePickerAnimationOpen { + effects?: string; + duration?: number; + } + + interface DateTimePickerAnimation { + close?: DateTimePickerAnimationClose; + open?: DateTimePickerAnimationOpen; + } + + interface DateTimePickerMonth { + content?: string; + empty?: string; + } + + interface DateTimePickerOptions { + name?: string; + animation?: DateTimePickerAnimation; + ARIATemplate?: string; + culture?: string; + dates?: any; + depth?: string; + footer?: string; + format?: string; + interval?: number; + max?: Date; + min?: Date; + month?: DateTimePickerMonth; + parseFormats?: any; + start?: string; + timeFormat?: string; + value?: Date; + change?(e: DateTimePickerChangeEvent): void; + close?(e: DateTimePickerCloseEvent): void; + open?(e: DateTimePickerOpenEvent): void; + } + interface DateTimePickerEvent { + sender: DateTimePicker; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface DateTimePickerChangeEvent extends DateTimePickerEvent { + } + + interface DateTimePickerCloseEvent extends DateTimePickerEvent { + view?: string; + } + + interface DateTimePickerOpenEvent extends DateTimePickerEvent { + view?: string; + } + + + class DropDownList extends kendo.ui.Widget { + static fn: DropDownList; + static extend(proto: Object): DropDownList; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: DropDownListOptions); + options: DropDownListOptions; + dataSource: kendo.data.DataSource; + close(): void; + dataItem(index?: number): any; + destroy(): void; + focus(): void; + open(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + refresh(): void; + search(word: string): void; + select(): number; + select(li: JQuery): void; + select(li: number): void; + select(li: Function): void; + setDataSource(dataSource: kendo.data.DataSource): void; + text(): string; + text(text: string): void; + toggle(toggle: boolean): void; + value(): string; + value(value: string): void; + span: JQuery; + filterInput: JQuery; + list: JQuery; + ul: JQuery; + } + + interface DropDownListAnimationClose { + effects?: string; + duration?: number; + } + + interface DropDownListAnimationOpen { + effects?: string; + duration?: number; + } + + interface DropDownListAnimation { + close?: DropDownListAnimationClose; + open?: DropDownListAnimationOpen; + } + + interface DropDownListVirtual { + itemHeight?: number; + valueMapper?: Function; + } + + interface DropDownListOptions { + name?: string; + animation?: DropDownListAnimation; + autoBind?: boolean; + cascadeFrom?: string; + cascadeFromField?: string; + dataSource?: any; + dataTextField?: string; + dataValueField?: string; + delay?: number; + enable?: boolean; + filter?: string; + fixedGroupTemplate?: any; + groupTemplate?: any; + height?: number; + ignoreCase?: string; + index?: number; + minLength?: number; + optionLabel?: any; + optionLabelTemplate?: any; + headerTemplate?: any; + template?: any; + valueTemplate?: any; + text?: string; + value?: string; + valuePrimitive?: boolean; + virtual?: DropDownListVirtual; + change?(e: DropDownListChangeEvent): void; + close?(e: DropDownListCloseEvent): void; + dataBound?(e: DropDownListDataBoundEvent): void; + filtering?(e: DropDownListFilteringEvent): void; + open?(e: DropDownListOpenEvent): void; + select?(e: DropDownListSelectEvent): void; + cascade?(e: DropDownListCascadeEvent): void; + } + interface DropDownListEvent { + sender: DropDownList; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface DropDownListChangeEvent extends DropDownListEvent { + } + + interface DropDownListCloseEvent extends DropDownListEvent { + } + + interface DropDownListDataBoundEvent extends DropDownListEvent { + } + + interface DropDownListFilteringEvent extends DropDownListEvent { + filter?: any; + } + + interface DropDownListOpenEvent extends DropDownListEvent { + } + + interface DropDownListSelectEvent extends DropDownListEvent { + item?: JQuery; + } + + interface DropDownListCascadeEvent extends DropDownListEvent { + } + + + class Editor extends kendo.ui.Widget { + static fn: Editor; + static extend(proto: Object): Editor; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: EditorOptions); + options: EditorOptions; + createRange(document?: Document): Range; + destroy(): void; + encodedValue(): void; + exec(name: string, params: any): void; + focus(): void; + getRange(): Range; + getSelection(): Selection; + paste(html: string, options: any): void; + selectedHtml(): string; + refresh(): void; + saveAsPDF(): JQueryPromise; + selectRange(range: Range): void; + update(): void; + state(toolName: string): boolean; + value(): string; + value(value: string): void; + body: Element; + } + + interface EditorFileBrowserMessages { + uploadFile?: string; + orderBy?: string; + orderByName?: string; + orderBySize?: string; + directoryNotFound?: string; + emptyFolder?: string; + deleteFile?: string; + invalidFileType?: string; + overwriteFile?: string; + search?: string; + } + + interface EditorFileBrowserSchemaModelFieldsName { + field?: string; + parse?: Function; + } + + interface EditorFileBrowserSchemaModelFieldsSize { + field?: string; + parse?: Function; + } + + interface EditorFileBrowserSchemaModelFieldsType { + parse?: Function; + field?: string; + } + + interface EditorFileBrowserSchemaModelFields { + name?: EditorFileBrowserSchemaModelFieldsName; + type?: EditorFileBrowserSchemaModelFieldsType; + size?: EditorFileBrowserSchemaModelFieldsSize; + } + + interface EditorFileBrowserSchemaModel { + id?: string; + fields?: EditorFileBrowserSchemaModelFields; + } + + interface EditorFileBrowserSchema { + } + + interface EditorFileBrowserTransportCreate { + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface EditorFileBrowserTransportDestroy { + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface EditorFileBrowserTransportRead { + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface EditorFileBrowserTransport { + read?: EditorFileBrowserTransportRead; + uploadUrl?: string; + fileUrl?: any; + destroy?: EditorFileBrowserTransportDestroy; + create?: EditorFileBrowserTransportCreate; + } + + interface EditorFileBrowser { + fileTypes?: string; + path?: string; + transport?: EditorFileBrowserTransport; + schema?: EditorFileBrowserSchema; + messages?: EditorFileBrowserMessages; + } + + interface EditorImageBrowserMessages { + uploadFile?: string; + orderBy?: string; + orderByName?: string; + orderBySize?: string; + directoryNotFound?: string; + emptyFolder?: string; + deleteFile?: string; + invalidFileType?: string; + overwriteFile?: string; + search?: string; + } + + interface EditorImageBrowserSchemaModelFieldsName { + field?: string; + parse?: Function; + } + + interface EditorImageBrowserSchemaModelFieldsSize { + field?: string; + parse?: Function; + } + + interface EditorImageBrowserSchemaModelFieldsType { + parse?: Function; + field?: string; + } + + interface EditorImageBrowserSchemaModelFields { + name?: EditorImageBrowserSchemaModelFieldsName; + type?: EditorImageBrowserSchemaModelFieldsType; + size?: EditorImageBrowserSchemaModelFieldsSize; + } + + interface EditorImageBrowserSchemaModel { + id?: string; + fields?: EditorImageBrowserSchemaModelFields; + } + + interface EditorImageBrowserSchema { + } + + interface EditorImageBrowserTransportCreate { + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface EditorImageBrowserTransportDestroy { + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface EditorImageBrowserTransportRead { + contentType?: string; + data?: any; + dataType?: string; + type?: string; + url?: any; + } + + interface EditorImageBrowserTransport { + read?: EditorImageBrowserTransportRead; + thumbnailUrl?: any; + uploadUrl?: string; + imageUrl?: any; + destroy?: EditorImageBrowserTransportDestroy; + create?: EditorImageBrowserTransportCreate; + } + + interface EditorImageBrowser { + fileTypes?: string; + path?: string; + transport?: EditorImageBrowserTransport; + schema?: EditorImageBrowserSchema; + messages?: EditorImageBrowserMessages; + } + + interface EditorMessages { + bold?: string; + italic?: string; + underline?: string; + strikethrough?: string; + superscript?: string; + subscript?: string; + justifyCenter?: string; + justifyLeft?: string; + justifyRight?: string; + justifyFull?: string; + insertUnorderedList?: string; + insertOrderedList?: string; + indent?: string; + outdent?: string; + createLink?: string; + unlink?: string; + insertImage?: string; + insertFile?: string; + insertHtml?: string; + viewHtml?: string; + fontName?: string; + fontNameInherit?: string; + fontSize?: string; + fontSizeInherit?: string; + formatBlock?: string; + formatting?: string; + foreColor?: string; + backColor?: string; + style?: string; + emptyFolder?: string; + uploadFile?: string; + editAreaTitle?: string; + orderBy?: string; + orderBySize?: string; + orderByName?: string; + invalidFileType?: string; + deleteFile?: string; + overwriteFile?: string; + directoryNotFound?: string; + imageWebAddress?: string; + imageAltText?: string; + imageWidth?: string; + imageHeight?: string; + fileWebAddress?: string; + fileTitle?: string; + linkWebAddress?: string; + linkText?: string; + linkToolTip?: string; + linkOpenInNewWindow?: string; + dialogUpdate?: string; + dialogInsert?: string; + dialogCancel?: string; + createTable?: string; + createTableHint?: string; + addColumnLeft?: string; + addColumnRight?: string; + addRowAbove?: string; + addRowBelow?: string; + deleteRow?: string; + deleteColumn?: string; + } + + interface EditorPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface EditorPdf { + author?: string; + creator?: string; + date?: Date; + fileName?: string; + forceProxy?: boolean; + keywords?: string; + landscape?: boolean; + margin?: EditorPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface EditorResizable { + min?: number; + max?: number; + } + + interface EditorSerialization { + entities?: boolean; + scripts?: boolean; + semantic?: boolean; + } + + interface EditorToolItem { + text?: string; + value?: string; + context?: string; + } + + interface EditorTool { + name?: string; + tooltip?: string; + exec?: Function; + items?: EditorToolItem[]; + template?: string; + } + + interface EditorExecParams { + value?: any; + } + + interface EditorPasteOptions { + split?: boolean; + } + + interface EditorOptions { + name?: string; + domain?: string; + encoded?: boolean; + messages?: EditorMessages; + pdf?: EditorPdf; + resizable?: EditorResizable; + serialization?: EditorSerialization; + stylesheets?: any; + tools?: EditorTool[]; + imageBrowser?: EditorImageBrowser; + fileBrowser?: EditorFileBrowser; + change?(e: EditorEvent): void; + execute?(e: EditorExecuteEvent): void; + keydown?(e: EditorEvent): void; + keyup?(e: EditorEvent): void; + paste?(e: EditorPasteEvent): void; + pdfExport?(e: EditorPdfExportEvent): void; + select?(e: EditorEvent): void; + } + interface EditorEvent { + sender: Editor; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface EditorExecuteEvent extends EditorEvent { + name?: string; + command?: any; + } + + interface EditorPasteEvent extends EditorEvent { + html?: any; + } + + interface EditorPdfExportEvent extends EditorEvent { + promise?: JQueryPromise; + } + + + class FlatColorPicker extends kendo.ui.Widget { + static fn: FlatColorPicker; + static extend(proto: Object): FlatColorPicker; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: FlatColorPickerOptions); + options: FlatColorPickerOptions; + focus(): void; + value(): string; + value(color?: string): void; + color(): kendo.Color; + color(color?: kendo.Color): void; + enable(enable?: boolean): void; + } + + interface FlatColorPickerMessages { + apply?: string; + cancel?: string; + } + + interface FlatColorPickerOptions { + name?: string; + opacity?: boolean; + buttons?: boolean; + value?: string; + preview?: boolean; + autoupdate?: boolean; + messages?: FlatColorPickerMessages; + change?(e: FlatColorPickerChangeEvent): void; + } + interface FlatColorPickerEvent { + sender: FlatColorPicker; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface FlatColorPickerChangeEvent extends FlatColorPickerEvent { + value?: string; + } + + + class Gantt extends kendo.ui.Widget { + static fn: Gantt; + static extend(proto: Object): Gantt; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: GanttOptions); + options: GanttOptions; + dataSource: kendo.data.DataSource; + clearSelection(): void; + dataItem(row: string): kendo.data.GanttTask; + dataItem(row: Element): kendo.data.GanttTask; + dataItem(row: JQuery): kendo.data.GanttTask; + destroy(): void; + refresh(): void; + refreshDependencies(): void; + removeDependency(dependency: string): void; + removeDependency(dependency: kendo.data.GanttDependency): void; + removeTask(task: string): void; + removeTask(task: kendo.data.GanttTask): void; + saveAsPDF(): JQueryPromise; + select(): JQuery; + select(row: string): void; + select(row: Element): void; + select(row: JQuery): void; + setDataSource(dataSource: kendo.data.GanttDataSource): void; + setDependenciesDataSource(dataSource: kendo.data.GanttDependencyDataSource): void; + view(): kendo.ui.GanttView; + view(type?: string): void; + dependencies: kendo.data.GanttDependencyDataSource; + } + + interface GanttAssignments { + dataSource?: any; + dataResourceIdField?: string; + dataTaskIdField?: string; + dataValueField?: string; + } + + interface GanttColumn { + field?: string; + title?: string; + format?: string; + width?: any; + editable?: boolean; + sortable?: boolean; + } + + interface GanttCurrentTimeMarker { + updateInterval?: number; + } + + interface GanttEditable { + confirmation?: boolean; + template?: any; + } + + interface GanttMessagesActions { + addChild?: string; + append?: string; + insertAfter?: string; + insertBefore?: string; + pdf?: string; + } + + interface GanttMessagesEditor { + assignButton?: string; + editorTitle?: string; + end?: string; + percentComplete?: string; + resources?: string; + resourcesEditorTitle?: string; + resourcesHeader?: string; + start?: string; + title?: string; + unitsHeader?: string; + } + + interface GanttMessagesViews { + day?: string; + end?: string; + month?: string; + start?: string; + week?: string; + year?: string; + } + + interface GanttMessages { + actions?: GanttMessagesActions; + cancel?: string; + deleteDependencyWindowTitle?: string; + deleteTaskWindowTitle?: string; + destroy?: string; + editor?: GanttMessagesEditor; + save?: string; + views?: GanttMessagesViews; + } + + interface GanttPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface GanttPdf { + author?: string; + creator?: string; + date?: Date; + fileName?: string; + forceProxy?: boolean; + keywords?: string; + landscape?: boolean; + margin?: GanttPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface GanttResources { + dataFormatField?: string; + dataColorField?: string; + dataSource?: any; + dataTextField?: string; + field?: string; + } + + interface GanttToolbarItem { + name?: string; + template?: any; + text?: string; + } + + interface GanttTooltip { + template?: any; + visible?: boolean; + } + + interface GanttView { + type?: string; + selected?: boolean; + slotSize?: any; + timeHeaderTemplate?: any; + dayHeaderTemplate?: any; + weekHeaderTemplate?: any; + monthHeaderTemplate?: any; + yearHeaderTemplate?: any; + resizeTooltipFormat?: string; + } + + interface GanttOptions { + name?: string; + assignments?: GanttAssignments; + autoBind?: boolean; + columns?: GanttColumn[]; + currentTimeMarker?: GanttCurrentTimeMarker; + dataSource?: any; + dependencies?: any; + editable?: GanttEditable; + navigatable?: boolean; + workDayStart?: Date; + workDayEnd?: Date; + workWeekStart?: number; + workWeekEnd?: number; + hourSpan?: number; + snap?: boolean; + height?: any; + listWidth?: any; + messages?: GanttMessages; + pdf?: GanttPdf; + selectable?: boolean; + showWorkDays?: boolean; + showWorkHours?: boolean; + toolbar?: GanttToolbarItem[]; + tooltip?: GanttTooltip; + views?: GanttView[]; + resources?: GanttResources; + dataBinding?(e: GanttDataBindingEvent): void; + dataBound?(e: GanttDataBoundEvent): void; + add?(e: GanttAddEvent): void; + edit?(e: GanttEditEvent): void; + remove?(e: GanttRemoveEvent): void; + cancel?(e: GanttCancelEvent): void; + save?(e: GanttSaveEvent): void; + change?(e: GanttChangeEvent): void; + navigate?(e: GanttNavigateEvent): void; + moveStart?(e: GanttMoveStartEvent): void; + move?(e: GanttMoveEvent): void; + moveEnd?(e: GanttMoveEndEvent): void; + pdfExport?(e: GanttPdfExportEvent): void; + resizeStart?(e: GanttResizeStartEvent): void; + resize?(e: GanttResizeEvent): void; + resizeEnd?(e: GanttResizeEndEvent): void; + } + interface GanttEvent { + sender: Gantt; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface GanttDataBindingEvent extends GanttEvent { + } + + interface GanttDataBoundEvent extends GanttEvent { + } + + interface GanttAddEvent extends GanttEvent { + task?: kendo.data.GanttTask; + dependency?: kendo.data.GanttDependency; + } + + interface GanttEditEvent extends GanttEvent { + container?: JQuery; + task?: kendo.data.GanttTask; + } + + interface GanttRemoveEvent extends GanttEvent { + task?: kendo.data.GanttTask; + dependencies?: any; + } + + interface GanttCancelEvent extends GanttEvent { + container?: JQuery; + task?: kendo.data.GanttTask; + } + + interface GanttSaveEvent extends GanttEvent { + task?: kendo.data.GanttTask; + values?: any; + } + + interface GanttChangeEvent extends GanttEvent { + } + + interface GanttNavigateEvent extends GanttEvent { + view?: string; + } + + interface GanttMoveStartEvent extends GanttEvent { + task?: kendo.data.GanttTask; + } + + interface GanttMoveEvent extends GanttEvent { + task?: kendo.data.GanttTask; + start?: Date; + end?: Date; + } + + interface GanttMoveEndEvent extends GanttEvent { + task?: kendo.data.GanttTask; + start?: Date; + end?: Date; + } + + interface GanttPdfExportEvent extends GanttEvent { + promise?: JQueryPromise; + } + + interface GanttResizeStartEvent extends GanttEvent { + task?: kendo.data.GanttTask; + } + + interface GanttResizeEvent extends GanttEvent { + task?: kendo.data.GanttTask; + start?: Date; + end?: Date; + } + + interface GanttResizeEndEvent extends GanttEvent { + task?: kendo.data.GanttTask; + start?: Date; + end?: Date; + } + + + class Grid extends kendo.ui.Widget { + static fn: Grid; + static extend(proto: Object): Grid; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: GridOptions); + options: GridOptions; + dataSource: kendo.data.DataSource; + addRow(): void; + autoFitColumn(column: number): void; + autoFitColumn(column: string): void; + autoFitColumn(column: any): void; + cancelChanges(): void; + cancelRow(): void; + cellIndex(cell: string): number; + cellIndex(cell: Element): number; + cellIndex(cell: JQuery): number; + clearSelection(): void; + closeCell(isCancel?: boolean): void; + collapseGroup(row: string): void; + collapseGroup(row: Element): void; + collapseGroup(row: JQuery): void; + collapseRow(row: string): void; + collapseRow(row: Element): void; + collapseRow(row: JQuery): void; + current(): JQuery; + current(cell: JQuery): void; + dataItem(row: string): kendo.data.ObservableObject; + dataItem(row: Element): kendo.data.ObservableObject; + dataItem(row: JQuery): kendo.data.ObservableObject; + destroy(): void; + editCell(cell: JQuery): void; + editRow(row: JQuery): void; + expandGroup(row: string): void; + expandGroup(row: Element): void; + expandGroup(row: JQuery): void; + expandRow(row: string): void; + expandRow(row: Element): void; + expandRow(row: JQuery): void; + getOptions(): GridOptions; + hideColumn(column: number): void; + hideColumn(column: string): void; + hideColumn(column: any): void; + lockColumn(column: number): void; + lockColumn(column: string): void; + refresh(): void; + removeRow(row: string): void; + removeRow(row: Element): void; + removeRow(row: JQuery): void; + reorderColumn(destIndex: number, column: any): void; + saveAsExcel(): void; + saveAsPDF(): JQueryPromise; + saveChanges(): void; + saveRow(): void; + select(): JQuery; + select(rows: string): void; + select(rows: Element): void; + select(rows: JQuery): void; + setDataSource(dataSource: kendo.data.DataSource): void; + setOptions(options: any): void; + showColumn(column: number): void; + showColumn(column: string): void; + showColumn(column: any): void; + unlockColumn(column: number): void; + unlockColumn(column: string): void; + columns: GridColumn[]; + footer: JQuery; + pager: kendo.ui.Pager; + table: JQuery; + tbody: JQuery; + thead: JQuery; + content: JQuery; + lockedHeader: JQuery; + lockedTable: JQuery; + lockedContent: JQuery; + } + + interface GridAllowCopy { + delimeter?: any; + } + + interface GridColumnMenuMessages { + columns?: string; + filter?: string; + sortAscending?: string; + sortDescending?: string; + settings?: string; + done?: string; + lock?: string; + unlock?: string; + } + + interface GridColumnMenu { + columns?: boolean; + filterable?: boolean; + sortable?: boolean; + messages?: GridColumnMenuMessages; + } + + interface GridColumnCommandItemText { + edit?: string; + cancel?: string; + update?: string; + } + + interface GridColumnCommandItem { + name?: string; + text?: GridColumnCommandItemText; + className?: string; + click?: Function; + } + + interface GridColumnFilterableCell { + dataSource?: any; + dataTextField?: string; + delay?: number; + inputWidth?: number; + suggestionOperator?: string; + minLength?: number; + enabled?: boolean; + operator?: string; + showOperators?: boolean; + template?: Function; + } + + interface GridColumnFilterable { + cell?: GridColumnFilterableCell; + multi?: boolean; + dataSource?: any; + checkAll?: boolean; + itemTemplate?: Function; + ui?: any; + } + + interface GridColumnSortable { + compare?: Function; + } + + interface GridColumn { + aggregates?: any; + attributes?: any; + columns?: any; + command?: GridColumnCommandItem[]; + encoded?: boolean; + field?: string; + filterable?: GridColumnFilterable; + footerTemplate?: any; + format?: string; + groupable?: boolean; + groupHeaderTemplate?: any; + groupFooterTemplate?: any; + headerAttributes?: any; + headerTemplate?: any; + hidden?: boolean; + locked?: boolean; + lockable?: boolean; + minScreenWidth?: number; + sortable?: GridColumnSortable; + template?: any; + title?: string; + width?: any; + values?: any; + menu?: boolean; + } + + interface GridEditable { + confirmation?: any; + cancelDelete?: string; + confirmDelete?: string; + createAt?: string; + destroy?: boolean; + mode?: string; + template?: any; + update?: boolean; + window?: any; + } + + interface GridExcel { + allPages?: boolean; + fileName?: string; + filterable?: boolean; + forceProxy?: boolean; + proxyURL?: string; + } + + interface GridFilterableMessages { + and?: string; + clear?: string; + filter?: string; + info?: string; + isFalse?: string; + isTrue?: string; + or?: string; + selectValue?: string; + cancel?: string; + operator?: string; + value?: string; + checkAll?: string; + } + + interface GridFilterableOperatorsDate { + eq?: string; + neq?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface GridFilterableOperatorsEnums { + eq?: string; + neq?: string; + } + + interface GridFilterableOperatorsNumber { + eq?: string; + neq?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface GridFilterableOperatorsString { + eq?: string; + neq?: string; + startswith?: string; + contains?: string; + doesnotcontain?: string; + endswith?: string; + } + + interface GridFilterableOperators { + string?: GridFilterableOperatorsString; + number?: GridFilterableOperatorsNumber; + date?: GridFilterableOperatorsDate; + enums?: GridFilterableOperatorsEnums; + } + + interface GridFilterable { + extra?: boolean; + messages?: GridFilterableMessages; + operators?: GridFilterableOperators; + mode?: string; + } + + interface GridGroupableMessages { + empty?: string; + } + + interface GridGroupable { + enabled?: boolean; + showFooter?: boolean; + messages?: GridGroupableMessages; + } + + interface GridMessagesCommands { + cancel?: string; + canceledit?: string; + create?: string; + destroy?: string; + edit?: string; + excel?: string; + save?: string; + update?: string; + } + + interface GridMessages { + commands?: GridMessagesCommands; + } + + interface GridPageableMessages { + display?: string; + empty?: string; + page?: string; + of?: string; + itemsPerPage?: string; + first?: string; + last?: string; + next?: string; + previous?: string; + refresh?: string; + morePages?: string; + } + + interface GridPageable { + pageSize?: number; + previousNext?: boolean; + numeric?: boolean; + buttonCount?: number; + input?: boolean; + pageSizes?: any; + refresh?: boolean; + info?: boolean; + messages?: GridPageableMessages; + } + + interface GridPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface GridPdf { + allPages?: boolean; + author?: string; + creator?: string; + date?: Date; + fileName?: string; + forceProxy?: boolean; + keywords?: string; + landscape?: boolean; + margin?: GridPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface GridScrollable { + virtual?: boolean; + } + + interface GridSortable { + allowUnsort?: boolean; + mode?: string; + } + + interface GridToolbarItem { + name?: string; + template?: any; + text?: string; + } + + interface GridOptions { + name?: string; + allowCopy?: GridAllowCopy; + altRowTemplate?: any; + autoBind?: boolean; + columnResizeHandleWidth?: number; + columns?: GridColumn[]; + columnMenu?: GridColumnMenu; + dataSource?: any; + detailTemplate?: any; + editable?: GridEditable; + excel?: GridExcel; + filterable?: GridFilterable; + groupable?: GridGroupable; + height?: any; + messages?: GridMessages; + mobile?: any; + navigatable?: boolean; + pageable?: GridPageable; + pdf?: GridPdf; + reorderable?: boolean; + resizable?: boolean; + rowTemplate?: any; + scrollable?: GridScrollable; + selectable?: any; + sortable?: GridSortable; + toolbar?: GridToolbarItem[]; + cancel?(e: GridCancelEvent): void; + change?(e: GridChangeEvent): void; + columnHide?(e: GridColumnHideEvent): void; + columnMenuInit?(e: GridColumnMenuInitEvent): void; + columnReorder?(e: GridColumnReorderEvent): void; + columnResize?(e: GridColumnResizeEvent): void; + columnShow?(e: GridColumnShowEvent): void; + dataBinding?(e: GridDataBindingEvent): void; + dataBound?(e: GridDataBoundEvent): void; + detailCollapse?(e: GridDetailCollapseEvent): void; + detailExpand?(e: GridDetailExpandEvent): void; + detailInit?(e: GridDetailInitEvent): void; + edit?(e: GridEditEvent): void; + excelExport?(e: GridExcelExportEvent): void; + pdfExport?(e: GridPdfExportEvent): void; + filterMenuInit?(e: GridFilterMenuInitEvent): void; + remove?(e: GridRemoveEvent): void; + save?(e: GridSaveEvent): void; + saveChanges?(e: GridSaveChangesEvent): void; + columnLock?(e: GridColumnLockEvent): void; + columnUnlock?(e: GridColumnUnlockEvent): void; + } + interface GridEvent { + sender: Grid; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface GridCancelEvent extends GridEvent { + container?: JQuery; + model?: kendo.data.Model; + } + + interface GridChangeEvent extends GridEvent { + } + + interface GridColumnHideEvent extends GridEvent { + column?: any; + } + + interface GridColumnMenuInitEvent extends GridEvent { + container?: JQuery; + field?: string; + } + + interface GridColumnReorderEvent extends GridEvent { + column?: any; + newIndex?: number; + oldIndex?: number; + } + + interface GridColumnResizeEvent extends GridEvent { + column?: any; + newWidth?: number; + oldWidth?: number; + } + + interface GridColumnShowEvent extends GridEvent { + column?: any; + } + + interface GridDataBindingEvent extends GridEvent { + action?: string; + index?: number; + items?: any; + } + + interface GridDataBoundEvent extends GridEvent { + } + + interface GridDetailCollapseEvent extends GridEvent { + detailRow?: JQuery; + masterRow?: JQuery; + } + + interface GridDetailExpandEvent extends GridEvent { + detailRow?: JQuery; + masterRow?: JQuery; + } + + interface GridDetailInitEvent extends GridEvent { + data?: kendo.data.ObservableObject; + detailCell?: JQuery; + detailRow?: JQuery; + masterRow?: JQuery; + } + + interface GridEditEvent extends GridEvent { + container?: JQuery; + model?: kendo.data.Model; + } + + interface GridExcelExportEvent extends GridEvent { + data?: any; + workbook?: kendo.ooxml.Workbook; + } + + interface GridPdfExportEvent extends GridEvent { + promise?: JQueryPromise; + } + + interface GridFilterMenuInitEvent extends GridEvent { + container?: JQuery; + field?: string; + } + + interface GridRemoveEvent extends GridEvent { + model?: kendo.data.Model; + row?: JQuery; + } + + interface GridSaveEvent extends GridEvent { + model?: kendo.data.Model; + container?: JQuery; + values?: any; + } + + interface GridSaveChangesEvent extends GridEvent { + } + + interface GridColumnLockEvent extends GridEvent { + column?: any; + } + + interface GridColumnUnlockEvent extends GridEvent { + column?: any; + } + + + class ListView extends kendo.ui.Widget { + static fn: ListView; + static extend(proto: Object): ListView; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ListViewOptions); + options: ListViewOptions; + dataSource: kendo.data.DataSource; + add(): void; + cancel(): void; + clearSelection(): void; + dataItem(row: string): kendo.data.ObservableObject; + dataItem(row: Element): kendo.data.ObservableObject; + dataItem(row: JQuery): kendo.data.ObservableObject; + dataItems(): void; + destroy(): void; + edit(item: JQuery): void; + refresh(): void; + remove(item: any): void; + save(): void; + select(): JQuery; + select(items: JQuery): void; + select(items: any): void; + setDataSource(dataSource: kendo.data.DataSource): void; + } + + interface ListViewOptions { + name?: string; + autoBind?: boolean; + dataSource?: any; + editTemplate?: Function; + navigatable?: boolean; + selectable?: any; + template?: Function; + altTemplate?: Function; + cancel?(e: ListViewCancelEvent): void; + change?(e: ListViewEvent): void; + dataBound?(e: ListViewEvent): void; + dataBinding?(e: ListViewEvent): void; + edit?(e: ListViewEditEvent): void; + remove?(e: ListViewRemoveEvent): void; + save?(e: ListViewSaveEvent): void; + } + interface ListViewEvent { + sender: ListView; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ListViewCancelEvent extends ListViewEvent { + container?: JQuery; + model?: kendo.data.Model; + } + + interface ListViewEditEvent extends ListViewEvent { + item?: JQuery; + model?: kendo.data.Model; + } + + interface ListViewRemoveEvent extends ListViewEvent { + item?: JQuery; + model?: kendo.data.Model; + } + + interface ListViewSaveEvent extends ListViewEvent { + model?: kendo.data.Model; + item?: JQuery; + } + + + class MaskedTextBox extends kendo.ui.Widget { + static fn: MaskedTextBox; + static extend(proto: Object): MaskedTextBox; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: MaskedTextBoxOptions); + options: MaskedTextBoxOptions; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + raw(): string; + value(): string; + value(value: string): void; + } + + interface MaskedTextBoxOptions { + name?: string; + clearPromptChar?: boolean; + culture?: string; + mask?: string; + promptChar?: string; + rules?: any; + unmaskOnPost?: boolean; + value?: string; + change?(e: MaskedTextBoxChangeEvent): void; + } + interface MaskedTextBoxEvent { + sender: MaskedTextBox; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface MaskedTextBoxChangeEvent extends MaskedTextBoxEvent { + } + + + class Menu extends kendo.ui.Widget { + static fn: Menu; + static extend(proto: Object): Menu; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: MenuOptions); + options: MenuOptions; + append(item: any, referenceItem: string): kendo.ui.Menu; + append(item: any, referenceItem: JQuery): kendo.ui.Menu; + close(element: string): kendo.ui.Menu; + close(element: Element): kendo.ui.Menu; + close(element: JQuery): kendo.ui.Menu; + destroy(): void; + enable(element: string, enable: boolean): kendo.ui.Menu; + enable(element: Element, enable: boolean): kendo.ui.Menu; + enable(element: JQuery, enable: boolean): kendo.ui.Menu; + insertAfter(item: string, referenceItem: string): kendo.ui.Menu; + insertAfter(item: string, referenceItem: Element): kendo.ui.Menu; + insertAfter(item: string, referenceItem: JQuery): kendo.ui.Menu; + insertAfter(item: Element, referenceItem: string): kendo.ui.Menu; + insertAfter(item: Element, referenceItem: Element): kendo.ui.Menu; + insertAfter(item: Element, referenceItem: JQuery): kendo.ui.Menu; + insertAfter(item: JQuery, referenceItem: string): kendo.ui.Menu; + insertAfter(item: JQuery, referenceItem: Element): kendo.ui.Menu; + insertAfter(item: JQuery, referenceItem: JQuery): kendo.ui.Menu; + insertBefore(item: string, referenceItem: string): kendo.ui.Menu; + insertBefore(item: string, referenceItem: Element): kendo.ui.Menu; + insertBefore(item: string, referenceItem: JQuery): kendo.ui.Menu; + insertBefore(item: Element, referenceItem: string): kendo.ui.Menu; + insertBefore(item: Element, referenceItem: Element): kendo.ui.Menu; + insertBefore(item: Element, referenceItem: JQuery): kendo.ui.Menu; + insertBefore(item: JQuery, referenceItem: string): kendo.ui.Menu; + insertBefore(item: JQuery, referenceItem: Element): kendo.ui.Menu; + insertBefore(item: JQuery, referenceItem: JQuery): kendo.ui.Menu; + open(element: string): kendo.ui.Menu; + open(element: Element): kendo.ui.Menu; + open(element: JQuery): kendo.ui.Menu; + remove(element: string): kendo.ui.Menu; + remove(element: Element): kendo.ui.Menu; + remove(element: JQuery): kendo.ui.Menu; + } + + interface MenuAnimationClose { + effects?: string; + duration?: number; + } + + interface MenuAnimationOpen { + effects?: string; + duration?: number; + } + + interface MenuAnimation { + close?: MenuAnimationClose; + open?: MenuAnimationOpen; + } + + interface MenuOptions { + name?: string; + animation?: MenuAnimation; + closeOnClick?: boolean; + dataSource?: any; + direction?: string; + hoverDelay?: number; + openOnClick?: boolean; + orientation?: string; + popupCollision?: string; + close?(e: MenuCloseEvent): void; + open?(e: MenuOpenEvent): void; + activate?(e: MenuActivateEvent): void; + deactivate?(e: MenuDeactivateEvent): void; + select?(e: MenuSelectEvent): void; + } + interface MenuEvent { + sender: Menu; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface MenuCloseEvent extends MenuEvent { + item?: HTMLElement; + } + + interface MenuOpenEvent extends MenuEvent { + item?: HTMLElement; + } + + interface MenuActivateEvent extends MenuEvent { + item?: HTMLElement; + } + + interface MenuDeactivateEvent extends MenuEvent { + item?: HTMLElement; + } + + interface MenuSelectEvent extends MenuEvent { + item?: HTMLElement; + } + + + class MultiSelect extends kendo.ui.Widget { + static fn: MultiSelect; + static extend(proto: Object): MultiSelect; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: MultiSelectOptions); + options: MultiSelectOptions; + dataSource: kendo.data.DataSource; + close(): void; + dataItems(): any; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + focus(): void; + open(): void; + refresh(): void; + search(word: string): void; + setDataSource(dataSource: kendo.data.DataSource): void; + toggle(toggle: boolean): void; + value(): any; + value(value: any): void; + value(value: string): void; + input: JQuery; + list: JQuery; + ul: JQuery; + tagList: JQuery; + } + + interface MultiSelectAnimationClose { + effects?: string; + duration?: number; + } + + interface MultiSelectAnimationOpen { + effects?: string; + duration?: number; + } + + interface MultiSelectAnimation { + close?: MultiSelectAnimationClose; + open?: MultiSelectAnimationOpen; + } + + interface MultiSelectVirtual { + itemHeight?: number; + valueMapper?: Function; + } + + interface MultiSelectOptions { + name?: string; + animation?: MultiSelectAnimation; + autoBind?: boolean; + autoClose?: boolean; + dataSource?: any; + dataTextField?: string; + dataValueField?: string; + delay?: number; + enable?: boolean; + filter?: string; + fixedGroupTemplate?: any; + groupTemplate?: any; + height?: number; + highlightFirst?: boolean; + ignoreCase?: string; + minLength?: number; + maxSelectedItems?: number; + placeholder?: string; + headerTemplate?: any; + itemTemplate?: any; + tagTemplate?: string; + value?: any; + valuePrimitive?: boolean; + virtual?: MultiSelectVirtual; + change?(e: MultiSelectChangeEvent): void; + close?(e: MultiSelectCloseEvent): void; + dataBound?(e: MultiSelectDataBoundEvent): void; + filtering?(e: MultiSelectFilteringEvent): void; + open?(e: MultiSelectOpenEvent): void; + select?(e: MultiSelectSelectEvent): void; + } + interface MultiSelectEvent { + sender: MultiSelect; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface MultiSelectChangeEvent extends MultiSelectEvent { + } + + interface MultiSelectCloseEvent extends MultiSelectEvent { + } + + interface MultiSelectDataBoundEvent extends MultiSelectEvent { + } + + interface MultiSelectFilteringEvent extends MultiSelectEvent { + filter?: any; + } + + interface MultiSelectOpenEvent extends MultiSelectEvent { + } + + interface MultiSelectSelectEvent extends MultiSelectEvent { + item?: JQuery; + } + + + class Notification extends kendo.ui.Widget { + static fn: Notification; + static extend(proto: Object): Notification; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: NotificationOptions); + options: NotificationOptions; + error(data: any): void; + error(data: string): void; + error(data: Function): void; + getNotifications(): JQuery; + hide(): void; + info(data: any): void; + info(data: string): void; + info(data: Function): void; + show(data: any, type: string): void; + show(data: string, type: string): void; + show(data: Function, type: string): void; + success(data: any): void; + success(data: string): void; + success(data: Function): void; + warning(data: any): void; + warning(data: string): void; + warning(data: Function): void; + } + + interface NotificationPosition { + bottom?: number; + left?: number; + pinned?: boolean; + right?: number; + top?: number; + } + + interface NotificationTemplate { + type?: string; + template?: string; + } + + interface NotificationOptions { + name?: string; + allowHideAfter?: number; + animation?: any; + appendTo?: any; + autoHideAfter?: number; + button?: boolean; + height?: any; + hideOnClick?: boolean; + position?: NotificationPosition; + stacking?: string; + templates?: NotificationTemplate[]; + width?: any; + hide?(e: NotificationHideEvent): void; + show?(e: NotificationShowEvent): void; + } + interface NotificationEvent { + sender: Notification; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface NotificationHideEvent extends NotificationEvent { + element?: JQuery; + } + + interface NotificationShowEvent extends NotificationEvent { + element?: JQuery; + } + + + class NumericTextBox extends kendo.ui.Widget { + static fn: NumericTextBox; + static extend(proto: Object): NumericTextBox; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: NumericTextBoxOptions); + options: NumericTextBoxOptions; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + focus(): void; + max(): number; + max(value: number): void; + max(value: string): void; + min(): number; + min(value: number): void; + min(value: string): void; + step(): number; + step(value: number): void; + step(value: string): void; + value(): number; + value(value: number): void; + value(value: string): void; + } + + interface NumericTextBoxOptions { + name?: string; + culture?: string; + decimals?: number; + downArrowText?: string; + format?: string; + max?: number; + min?: number; + placeholder?: string; + spinners?: boolean; + step?: number; + upArrowText?: string; + value?: number; + change?(e: NumericTextBoxChangeEvent): void; + spin?(e: NumericTextBoxSpinEvent): void; + } + interface NumericTextBoxEvent { + sender: NumericTextBox; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface NumericTextBoxChangeEvent extends NumericTextBoxEvent { + } + + interface NumericTextBoxSpinEvent extends NumericTextBoxEvent { + } + + + class Pager extends kendo.ui.Widget { + static fn: Pager; + static extend(proto: Object): Pager; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: PagerOptions); + options: PagerOptions; + dataSource: kendo.data.DataSource; + totalPages(): number; + pageSize(): number; + page(page: boolean): number; + refresh(): void; + destroy(): void; + } + + interface PagerMessages { + display?: string; + empty?: string; + page?: string; + of?: string; + itemsPerPage?: string; + first?: string; + previous?: string; + next?: string; + last?: string; + refresh?: string; + } + + interface PagerOptions { + name?: string; + autoBind?: boolean; + buttonCount?: number; + dataSource?: any; + selectTemplate?: string; + linkTemplate?: string; + info?: boolean; + input?: boolean; + numeric?: boolean; + pageSizes?: any; + previousNext?: boolean; + refresh?: boolean; + messages?: PagerMessages; + change?(e: PagerChangeEvent): void; + } + interface PagerEvent { + sender: Pager; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface PagerChangeEvent extends PagerEvent { + } + + + class PanelBar extends kendo.ui.Widget { + static fn: PanelBar; + static extend(proto: Object): PanelBar; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: PanelBarOptions); + options: PanelBarOptions; + append(item: string, referenceItem: string): kendo.ui.PanelBar; + append(item: string, referenceItem: Element): kendo.ui.PanelBar; + append(item: string, referenceItem: JQuery): kendo.ui.PanelBar; + append(item: Element, referenceItem: string): kendo.ui.PanelBar; + append(item: Element, referenceItem: Element): kendo.ui.PanelBar; + append(item: Element, referenceItem: JQuery): kendo.ui.PanelBar; + append(item: JQuery, referenceItem: string): kendo.ui.PanelBar; + append(item: JQuery, referenceItem: Element): kendo.ui.PanelBar; + append(item: JQuery, referenceItem: JQuery): kendo.ui.PanelBar; + append(item: any, referenceItem: string): kendo.ui.PanelBar; + append(item: any, referenceItem: Element): kendo.ui.PanelBar; + append(item: any, referenceItem: JQuery): kendo.ui.PanelBar; + clearSelection(): void; + collapse(element: string, useAnimation: boolean): kendo.ui.PanelBar; + collapse(element: Element, useAnimation: boolean): kendo.ui.PanelBar; + collapse(element: JQuery, useAnimation: boolean): kendo.ui.PanelBar; + destroy(): void; + enable(element: string, enable: boolean): void; + enable(element: Element, enable: boolean): void; + enable(element: JQuery, enable: boolean): void; + expand(element: string, useAnimation: boolean): kendo.ui.PanelBar; + expand(element: Element, useAnimation: boolean): kendo.ui.PanelBar; + expand(element: JQuery, useAnimation: boolean): kendo.ui.PanelBar; + insertAfter(item: string, referenceItem: string): void; + insertAfter(item: string, referenceItem: Element): void; + insertAfter(item: string, referenceItem: JQuery): void; + insertAfter(item: Element, referenceItem: string): void; + insertAfter(item: Element, referenceItem: Element): void; + insertAfter(item: Element, referenceItem: JQuery): void; + insertAfter(item: JQuery, referenceItem: string): void; + insertAfter(item: JQuery, referenceItem: Element): void; + insertAfter(item: JQuery, referenceItem: JQuery): void; + insertAfter(item: any, referenceItem: string): void; + insertAfter(item: any, referenceItem: Element): void; + insertAfter(item: any, referenceItem: JQuery): void; + insertBefore(item: string, referenceItem: string): kendo.ui.PanelBar; + insertBefore(item: string, referenceItem: Element): kendo.ui.PanelBar; + insertBefore(item: string, referenceItem: JQuery): kendo.ui.PanelBar; + insertBefore(item: Element, referenceItem: string): kendo.ui.PanelBar; + insertBefore(item: Element, referenceItem: Element): kendo.ui.PanelBar; + insertBefore(item: Element, referenceItem: JQuery): kendo.ui.PanelBar; + insertBefore(item: JQuery, referenceItem: string): kendo.ui.PanelBar; + insertBefore(item: JQuery, referenceItem: Element): kendo.ui.PanelBar; + insertBefore(item: JQuery, referenceItem: JQuery): kendo.ui.PanelBar; + insertBefore(item: any, referenceItem: string): kendo.ui.PanelBar; + insertBefore(item: any, referenceItem: Element): kendo.ui.PanelBar; + insertBefore(item: any, referenceItem: JQuery): kendo.ui.PanelBar; + reload(element: string): void; + reload(element: Element): void; + reload(element: JQuery): void; + remove(element: string): void; + remove(element: Element): void; + remove(element: JQuery): void; + select(): JQuery; + select(element?: string): void; + select(element?: Element): void; + select(element?: JQuery): void; + } + + interface PanelBarAnimationCollapse { + duration?: number; + effects?: string; + } + + interface PanelBarAnimationExpand { + duration?: number; + effects?: string; + } + + interface PanelBarAnimation { + collapse?: PanelBarAnimationCollapse; + expand?: PanelBarAnimationExpand; + } + + interface PanelBarOptions { + name?: string; + animation?: PanelBarAnimation; + contentUrls?: any; + dataSource?: any; + expandMode?: string; + activate?(e: PanelBarActivateEvent): void; + collapse?(e: PanelBarCollapseEvent): void; + contentLoad?(e: PanelBarContentLoadEvent): void; + error?(e: PanelBarErrorEvent): void; + expand?(e: PanelBarExpandEvent): void; + select?(e: PanelBarSelectEvent): void; + } + interface PanelBarEvent { + sender: PanelBar; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface PanelBarActivateEvent extends PanelBarEvent { + item?: Element; + } + + interface PanelBarCollapseEvent extends PanelBarEvent { + item?: Element; + } + + interface PanelBarContentLoadEvent extends PanelBarEvent { + item?: Element; + contentElement?: Element; + } + + interface PanelBarErrorEvent extends PanelBarEvent { + xhr?: JQueryXHR; + status?: string; + } + + interface PanelBarExpandEvent extends PanelBarEvent { + item?: Element; + } + + interface PanelBarSelectEvent extends PanelBarEvent { + item?: Element; + } + + + class PivotConfigurator extends kendo.ui.Widget { + static fn: PivotConfigurator; + static extend(proto: Object): PivotConfigurator; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: PivotConfiguratorOptions); + options: PivotConfiguratorOptions; + dataSource: kendo.data.DataSource; + destroy(): void; + refresh(): void; + setDataSource(dataSource: kendo.data.PivotDataSource): void; + } + + interface PivotConfiguratorMessagesFieldMenuOperators { + contains?: string; + doesnotcontain?: string; + startswith?: string; + endswith?: string; + eq?: string; + neq?: string; + } + + interface PivotConfiguratorMessagesFieldMenu { + info?: string; + sortAscending?: string; + sortDescending?: string; + filterFields?: string; + filter?: string; + include?: string; + title?: string; + clear?: string; + ok?: string; + cancel?: string; + operators?: PivotConfiguratorMessagesFieldMenuOperators; + } + + interface PivotConfiguratorMessages { + measures?: string; + columns?: string; + rows?: string; + measuresLabel?: string; + rowsLabel?: string; + columnsLabel?: string; + fieldsLabel?: string; + fieldMenu?: PivotConfiguratorMessagesFieldMenu; + } + + interface PivotConfiguratorSortable { + allowUnsort?: boolean; + } + + interface PivotConfiguratorOptions { + name?: string; + dataSource?: any; + filterable?: boolean; + sortable?: PivotConfiguratorSortable; + height?: any; + messages?: PivotConfiguratorMessages; + } + interface PivotConfiguratorEvent { + sender: PivotConfigurator; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class PivotGrid extends kendo.ui.Widget { + static fn: PivotGrid; + static extend(proto: Object): PivotGrid; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: PivotGridOptions); + options: PivotGridOptions; + dataSource: kendo.data.DataSource; + cellInfo(columnIndex: number, rowIndex: number): any; + cellInfoByElement(cell: string): any; + cellInfoByElement(cell: Element): any; + cellInfoByElement(cell: JQuery): any; + destroy(): void; + refresh(): void; + setDataSource(dataSource: kendo.data.PivotDataSource): void; + saveAsExcel(): void; + saveAsPDF(): JQueryPromise; + } + + interface PivotGridExcel { + fileName?: string; + filterable?: boolean; + forceProxy?: boolean; + proxyURL?: string; + } + + interface PivotGridMessagesFieldMenuOperators { + contains?: string; + doesnotcontain?: string; + startswith?: string; + endswith?: string; + eq?: string; + neq?: string; + } + + interface PivotGridMessagesFieldMenu { + info?: string; + sortAscending?: string; + sortDescending?: string; + filterFields?: string; + filter?: string; + include?: string; + title?: string; + clear?: string; + ok?: string; + cancel?: string; + operators?: PivotGridMessagesFieldMenuOperators; + } + + interface PivotGridMessages { + measureFields?: string; + columnFields?: string; + rowFields?: string; + fieldMenu?: PivotGridMessagesFieldMenu; + } + + interface PivotGridPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface PivotGridPdf { + author?: string; + creator?: string; + date?: Date; + fileName?: string; + forceProxy?: boolean; + keywords?: string; + landscape?: boolean; + margin?: PivotGridPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface PivotGridSortable { + allowUnsort?: boolean; + } + + interface PivotGridOptions { + name?: string; + dataSource?: any; + autoBind?: boolean; + reorderable?: boolean; + excel?: PivotGridExcel; + pdf?: PivotGridPdf; + filterable?: boolean; + sortable?: PivotGridSortable; + columnWidth?: number; + height?: any; + columnHeaderTemplate?: any; + dataCellTemplate?: any; + kpiStatusTemplate?: any; + kpiTrendTemplate?: any; + rowHeaderTemplate?: any; + messages?: PivotGridMessages; + dataBinding?(e: PivotGridDataBindingEvent): void; + dataBound?(e: PivotGridDataBoundEvent): void; + expandMember?(e: PivotGridExpandMemberEvent): void; + collapseMember?(e: PivotGridCollapseMemberEvent): void; + excelExport?(e: PivotGridExcelExportEvent): void; + pdfExport?(e: PivotGridPdfExportEvent): void; + } + interface PivotGridEvent { + sender: PivotGrid; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface PivotGridDataBindingEvent extends PivotGridEvent { + } + + interface PivotGridDataBoundEvent extends PivotGridEvent { + } + + interface PivotGridExpandMemberEvent extends PivotGridEvent { + axis?: string; + path?: string; + } + + interface PivotGridCollapseMemberEvent extends PivotGridEvent { + axis?: string; + path?: string; + } + + interface PivotGridExcelExportEvent extends PivotGridEvent { + data?: any; + workbook?: any; + } + + interface PivotGridPdfExportEvent extends PivotGridEvent { + promise?: JQueryPromise; + } + + + class ProgressBar extends kendo.ui.Widget { + static fn: ProgressBar; + static extend(proto: Object): ProgressBar; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ProgressBarOptions); + options: ProgressBarOptions; + enable(enable: boolean): void; + value(): number; + value(value: number): void; + progressStatus: JQuery; + progressWrapper: JQuery; + } + + interface ProgressBarAnimation { + duration?: number; + } + + interface ProgressBarOptions { + name?: string; + animation?: ProgressBarAnimation; + chunkCount?: number; + enable?: boolean; + max?: number; + min?: number; + orientation?: string; + reverse?: boolean; + showStatus?: boolean; + type?: string; + value?: number; + change?(e: ProgressBarChangeEvent): void; + complete?(e: ProgressBarCompleteEvent): void; + } + interface ProgressBarEvent { + sender: ProgressBar; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ProgressBarChangeEvent extends ProgressBarEvent { + value?: number; + } + + interface ProgressBarCompleteEvent extends ProgressBarEvent { + value?: number; + } + + + class RangeSlider extends kendo.ui.Widget { + static fn: RangeSlider; + static extend(proto: Object): RangeSlider; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: RangeSliderOptions); + options: RangeSliderOptions; + destroy(): void; + enable(enable: boolean): void; + value(): any; + value(selectionStart: number, selectionEnd: number): void; + resize(): void; + } + + interface RangeSliderTooltip { + enabled?: boolean; + format?: string; + template?: string; + } + + interface RangeSliderOptions { + name?: string; + largeStep?: number; + max?: number; + min?: number; + orientation?: string; + selectionEnd?: number; + selectionStart?: number; + smallStep?: number; + tickPlacement?: string; + tooltip?: RangeSliderTooltip; + change?(e: RangeSliderChangeEvent): void; + slide?(e: RangeSliderSlideEvent): void; + } + interface RangeSliderEvent { + sender: RangeSlider; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface RangeSliderChangeEvent extends RangeSliderEvent { + value?: number; + } + + interface RangeSliderSlideEvent extends RangeSliderEvent { + value?: number; + } + + + class ResponsivePanel extends kendo.ui.Widget { + static fn: ResponsivePanel; + static extend(proto: Object): ResponsivePanel; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ResponsivePanelOptions); + options: ResponsivePanelOptions; + close(): void; + destroy(): void; + open(): void; + } + + interface ResponsivePanelOptions { + name?: string; + autoClose?: boolean; + breakpoint?: number; + orientation?: string; + toggleButton?: string; + close?(e: ResponsivePanelEvent): void; + open?(e: ResponsivePanelEvent): void; + } + interface ResponsivePanelEvent { + sender: ResponsivePanel; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Scheduler extends kendo.ui.Widget { + static fn: Scheduler; + static extend(proto: Object): Scheduler; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: SchedulerOptions); + options: SchedulerOptions; + dataSource: kendo.data.DataSource; + addEvent(data: any): void; + cancelEvent(): void; + data(): void; + date(): Date; + date(value?: Date): void; + destroy(): void; + editEvent(event: string): void; + editEvent(event: kendo.data.SchedulerEvent): void; + occurrenceByUid(uid: string): kendo.data.SchedulerEvent; + occurrencesInRange(start: Date, end: Date): any; + refresh(): void; + removeEvent(event: string): void; + removeEvent(event: kendo.data.SchedulerEvent): void; + resourcesBySlot(slot: any): any; + saveAsPDF(): JQueryPromise; + saveEvent(): void; + select(): void; + select(events: any, options: any): void; + setDataSource(dataSource: kendo.data.SchedulerDataSource): void; + slotByPosition(xPosition: number, yPosition: number): any; + slotByElement(element: Element): any; + slotByElement(element: JQuery): any; + view(): kendo.ui.SchedulerView; + view(type?: string): void; + } + + interface SchedulerCurrentTimeMarker { + updateInterval?: number; + useLocalTimezone?: boolean; + } + + interface SchedulerEditable { + confirmation?: any; + create?: boolean; + destroy?: boolean; + editRecurringMode?: string; + move?: boolean; + resize?: boolean; + template?: any; + update?: boolean; + window?: any; + } + + interface SchedulerFooter { + command?: any; + } + + interface SchedulerGroup { + resources?: any; + orientation?: string; + } + + interface SchedulerMessagesEditor { + allDayEvent?: string; + description?: string; + editorTitle?: string; + end?: string; + endTimezone?: string; + repeat?: string; + separateTimezones?: string; + start?: string; + startTimezone?: string; + timezone?: string; + timezoneEditorButton?: string; + timezoneEditorTitle?: string; + title?: string; + } + + interface SchedulerMessagesRecurrenceEditorDaily { + interval?: string; + repeatEvery?: string; + } + + interface SchedulerMessagesRecurrenceEditorEnd { + after?: string; + occurrence?: string; + label?: string; + never?: string; + mobileLabel?: string; + on?: string; + } + + interface SchedulerMessagesRecurrenceEditorFrequencies { + daily?: string; + monthly?: string; + never?: string; + weekly?: string; + yearly?: string; + } + + interface SchedulerMessagesRecurrenceEditorMonthly { + day?: string; + interval?: string; + repeatEvery?: string; + repeatOn?: string; + } + + interface SchedulerMessagesRecurrenceEditorOffsetPositions { + first?: string; + second?: string; + third?: string; + fourth?: string; + last?: string; + } + + interface SchedulerMessagesRecurrenceEditorWeekdays { + day?: string; + weekday?: string; + weekend?: string; + } + + interface SchedulerMessagesRecurrenceEditorWeekly { + interval?: string; + repeatEvery?: string; + repeatOn?: string; + } + + interface SchedulerMessagesRecurrenceEditorYearly { + of?: string; + repeatEvery?: string; + repeatOn?: string; + interval?: string; + } + + interface SchedulerMessagesRecurrenceEditor { + daily?: SchedulerMessagesRecurrenceEditorDaily; + end?: SchedulerMessagesRecurrenceEditorEnd; + frequencies?: SchedulerMessagesRecurrenceEditorFrequencies; + monthly?: SchedulerMessagesRecurrenceEditorMonthly; + offsetPositions?: SchedulerMessagesRecurrenceEditorOffsetPositions; + weekly?: SchedulerMessagesRecurrenceEditorWeekly; + weekdays?: SchedulerMessagesRecurrenceEditorWeekdays; + yearly?: SchedulerMessagesRecurrenceEditorYearly; + } + + interface SchedulerMessagesRecurrenceMessages { + deleteRecurring?: string; + deleteWindowOccurrence?: string; + deleteWindowSeries?: string; + deleteWindowTitle?: string; + editRecurring?: string; + editWindowOccurrence?: string; + editWindowSeries?: string; + editWindowTitle?: string; + } + + interface SchedulerMessagesViews { + day?: string; + week?: string; + month?: string; + agenda?: string; + } + + interface SchedulerMessages { + allDay?: string; + ariaEventLabel?: string; + ariaSlotLabel?: string; + cancel?: string; + date?: string; + deleteWindowTitle?: string; + destroy?: string; + event?: string; + defaultRowText?: string; + pdf?: string; + save?: string; + showFullDay?: string; + showWorkDay?: string; + time?: string; + today?: string; + editor?: SchedulerMessagesEditor; + recurrenceEditor?: SchedulerMessagesRecurrenceEditor; + recurrenceMessages?: SchedulerMessagesRecurrenceMessages; + views?: SchedulerMessagesViews; + } + + interface SchedulerPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface SchedulerPdf { + author?: string; + creator?: string; + date?: Date; + fileName?: string; + forceProxy?: boolean; + keywords?: string; + landscape?: boolean; + margin?: SchedulerPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface SchedulerResource { + dataColorField?: string; + dataSource?: any; + dataTextField?: string; + dataValueField?: string; + field?: string; + multiple?: boolean; + name?: string; + title?: string; + valuePrimitive?: boolean; + } + + interface SchedulerToolbarItem { + name?: string; + } + + interface SchedulerViewEditable { + create?: boolean; + destroy?: boolean; + update?: boolean; + } + + interface SchedulerViewGroup { + orientation?: string; + } + + interface SchedulerView { + allDayEventTemplate?: any; + allDaySlot?: boolean; + allDaySlotTemplate?: any; + columnWidth?: number; + dateHeaderTemplate?: any; + dayTemplate?: any; + editable?: SchedulerViewEditable; + endTime?: Date; + eventHeight?: number; + eventTemplate?: any; + eventTimeTemplate?: any; + group?: SchedulerViewGroup; + majorTick?: number; + majorTimeHeaderTemplate?: any; + minorTickCount?: number; + minorTimeHeaderTemplate?: any; + selected?: boolean; + selectedDateFormat?: string; + showWorkHours?: boolean; + slotTemplate?: any; + startTime?: Date; + title?: string; + type?: string; + workWeekStart?: number; + workWeekEnd?: number; + } + + interface SchedulerSelectOptions { + events?: any; + resources?: any; + start?: Date; + end?: Date; + isAllDay?: boolean; + } + + interface SchedulerOptions { + name?: string; + allDayEventTemplate?: any; + allDaySlot?: boolean; + autoBind?: boolean; + currentTimeMarker?: SchedulerCurrentTimeMarker; + dataSource?: any; + date?: Date; + dateHeaderTemplate?: any; + editable?: SchedulerEditable; + endTime?: Date; + eventTemplate?: any; + footer?: SchedulerFooter; + group?: SchedulerGroup; + height?: any; + majorTick?: number; + majorTimeHeaderTemplate?: any; + max?: Date; + messages?: SchedulerMessages; + min?: Date; + minorTickCount?: number; + minorTimeHeaderTemplate?: any; + mobile?: any; + pdf?: SchedulerPdf; + resources?: SchedulerResource[]; + selectable?: boolean; + showWorkHours?: boolean; + snap?: boolean; + startTime?: Date; + timezone?: string; + toolbar?: SchedulerToolbarItem[]; + views?: SchedulerView[]; + groupHeaderTemplate?: any; + width?: any; + workDayStart?: Date; + workDayEnd?: Date; + workWeekStart?: number; + workWeekEnd?: number; + add?(e: SchedulerAddEvent): void; + cancel?(e: SchedulerCancelEvent): void; + change?(e: SchedulerChangeEvent): void; + dataBinding?(e: SchedulerDataBindingEvent): void; + dataBound?(e: SchedulerDataBoundEvent): void; + edit?(e: SchedulerEditEvent): void; + moveStart?(e: SchedulerMoveStartEvent): void; + move?(e: SchedulerMoveEvent): void; + moveEnd?(e: SchedulerMoveEndEvent): void; + navigate?(e: SchedulerNavigateEvent): void; + pdfExport?(e: SchedulerPdfExportEvent): void; + remove?(e: SchedulerRemoveEvent): void; + resizeStart?(e: SchedulerResizeStartEvent): void; + resize?(e: SchedulerResizeEvent): void; + resizeEnd?(e: SchedulerResizeEndEvent): void; + save?(e: SchedulerSaveEvent): void; + } + interface SchedulerEvent { + sender: Scheduler; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SchedulerAddEvent extends SchedulerEvent { + event?: any; + } + + interface SchedulerCancelEvent extends SchedulerEvent { + container?: JQuery; + event?: kendo.data.SchedulerEvent; + } + + interface SchedulerChangeEvent extends SchedulerEvent { + start?: Date; + end?: Date; + events?: any; + slots?: any; + resources?: any; + } + + interface SchedulerDataBindingEvent extends SchedulerEvent { + } + + interface SchedulerDataBoundEvent extends SchedulerEvent { + } + + interface SchedulerEditEvent extends SchedulerEvent { + container?: JQuery; + event?: kendo.data.SchedulerEvent; + } + + interface SchedulerMoveStartEvent extends SchedulerEvent { + event?: kendo.data.SchedulerEvent; + } + + interface SchedulerMoveEvent extends SchedulerEvent { + event?: kendo.data.SchedulerEvent; + slot?: any; + } + + interface SchedulerMoveEndEvent extends SchedulerEvent { + start?: Date; + end?: Date; + event?: kendo.data.SchedulerEvent; + slot?: any; + resources?: any; + } + + interface SchedulerNavigateEvent extends SchedulerEvent { + action?: string; + date?: Date; + view?: string; + } + + interface SchedulerPdfExportEvent extends SchedulerEvent { + promise?: JQueryPromise; + } + + interface SchedulerRemoveEvent extends SchedulerEvent { + event?: kendo.data.SchedulerEvent; + } + + interface SchedulerResizeStartEvent extends SchedulerEvent { + event?: kendo.data.SchedulerEvent; + } + + interface SchedulerResizeEvent extends SchedulerEvent { + event?: kendo.data.SchedulerEvent; + slot?: any; + } + + interface SchedulerResizeEndEvent extends SchedulerEvent { + event?: kendo.data.SchedulerEvent; + slot?: any; + } + + interface SchedulerSaveEvent extends SchedulerEvent { + container?: JQuery; + event?: kendo.data.SchedulerEvent; + } + + + class Slider extends kendo.ui.Widget { + static fn: Slider; + static extend(proto: Object): Slider; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: SliderOptions); + options: SliderOptions; + destroy(): void; + enable(enable: boolean): void; + value(): number; + value(value: number): void; + resize(): void; + } + + interface SliderTooltip { + enabled?: boolean; + format?: string; + template?: string; + } + + interface SliderOptions { + name?: string; + decreaseButtonTitle?: string; + increaseButtonTitle?: string; + largeStep?: number; + max?: number; + min?: number; + orientation?: string; + showButtons?: boolean; + smallStep?: number; + tickPlacement?: string; + tooltip?: SliderTooltip; + value?: number; + change?(e: SliderChangeEvent): void; + slide?(e: SliderSlideEvent): void; + } + interface SliderEvent { + sender: Slider; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SliderChangeEvent extends SliderEvent { + value?: number; + } + + interface SliderSlideEvent extends SliderEvent { + value?: number; + } + + + class Sortable extends kendo.ui.Widget { + static fn: Sortable; + static extend(proto: Object): Sortable; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: SortableOptions); + options: SortableOptions; + indexOf(element: JQuery): number; + items(): JQuery; + } + + interface SortableCursorOffset { + left?: number; + top?: number; + } + + interface SortableOptions { + name?: string; + axis?: string; + container?: any; + connectWith?: any; + cursor?: string; + cursorOffset?: SortableCursorOffset; + disabled?: string; + filter?: string; + handler?: string; + hint?: any; + holdToDrag?: boolean; + ignore?: string; + placeholder?: any; + start?(e: SortableStartEvent): void; + move?(e: SortableMoveEvent): void; + end?(e: SortableEndEvent): void; + change?(e: SortableChangeEvent): void; + cancel?(e: SortableCancelEvent): void; + } + interface SortableEvent { + sender: Sortable; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SortableStartEvent extends SortableEvent { + draggableEvent?: any; + item?: JQuery; + } + + interface SortableMoveEvent extends SortableEvent { + item?: JQuery; + target?: JQuery; + list?: kendo.ui.Sortable; + draggableEvent?: any; + } + + interface SortableEndEvent extends SortableEvent { + action?: string; + item?: JQuery; + oldIndex?: number; + newIndex?: number; + draggableEvent?: any; + } + + interface SortableChangeEvent extends SortableEvent { + action?: string; + item?: JQuery; + oldIndex?: number; + newIndex?: number; + draggableEvent?: any; + } + + interface SortableCancelEvent extends SortableEvent { + item?: JQuery; + } + + + class Splitter extends kendo.ui.Widget { + static fn: Splitter; + static extend(proto: Object): Splitter; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: SplitterOptions); + options: SplitterOptions; + ajaxRequest(pane: string, url: string, data: any): void; + ajaxRequest(pane: string, url: string, data: string): void; + ajaxRequest(pane: Element, url: string, data: any): void; + ajaxRequest(pane: Element, url: string, data: string): void; + ajaxRequest(pane: JQuery, url: string, data: any): void; + ajaxRequest(pane: JQuery, url: string, data: string): void; + append(config?: any): JQuery; + collapse(pane: string): void; + collapse(pane: Element): void; + collapse(pane: JQuery): void; + destroy(): void; + expand(pane: string): void; + expand(pane: Element): void; + expand(pane: JQuery): void; + insertAfter(config: any, referencePane: string): JQuery; + insertAfter(config: any, referencePane: Element): JQuery; + insertAfter(config: any, referencePane: JQuery): JQuery; + insertBefore(config: any, referencePane: string): JQuery; + insertBefore(config: any, referencePane: Element): JQuery; + insertBefore(config: any, referencePane: JQuery): JQuery; + max(pane: string, value: string): void; + max(pane: Element, value: string): void; + max(pane: JQuery, value: string): void; + min(pane: string, value: string): void; + min(pane: Element, value: string): void; + min(pane: JQuery, value: string): void; + remove(pane: string): void; + remove(pane: Element): void; + remove(pane: JQuery): void; + size(pane: string, value: string): void; + size(pane: Element, value: string): void; + size(pane: JQuery, value: string): void; + toggle(pane: string, expand?: boolean): void; + toggle(pane: Element, expand?: boolean): void; + toggle(pane: JQuery, expand?: boolean): void; + } + + interface SplitterPane { + collapsed?: boolean; + collapsedSize?: string; + collapsible?: boolean; + contentUrl?: string; + max?: string; + min?: string; + resizable?: boolean; + scrollable?: boolean; + size?: string; + } + + interface SplitterOptions { + name?: string; + orientation?: string; + panes?: SplitterPane[]; + collapse?(e: SplitterCollapseEvent): void; + contentLoad?(e: SplitterContentLoadEvent): void; + error?(e: SplitterErrorEvent): void; + expand?(e: SplitterExpandEvent): void; + layoutChange?(e: SplitterEvent): void; + resize?(e: SplitterEvent): void; + } + interface SplitterEvent { + sender: Splitter; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SplitterCollapseEvent extends SplitterEvent { + pane?: Element; + } + + interface SplitterContentLoadEvent extends SplitterEvent { + pane?: Element; + } + + interface SplitterErrorEvent extends SplitterEvent { + xhr?: JQueryXHR; + status?: string; + } + + interface SplitterExpandEvent extends SplitterEvent { + pane?: Element; + } + + + class TabStrip extends kendo.ui.Widget { + static fn: TabStrip; + static extend(proto: Object): TabStrip; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TabStripOptions); + options: TabStripOptions; + activateTab(item: JQuery): void; + append(tab: any): kendo.ui.TabStrip; + contentElement(itemIndex: number): Element; + contentHolder(itemIndex: number): Element; + deactivateTab(item: JQuery): void; + destroy(): void; + disable(element: string): kendo.ui.TabStrip; + disable(element: Element): kendo.ui.TabStrip; + disable(element: JQuery): kendo.ui.TabStrip; + enable(element: string, enable?: boolean): kendo.ui.TabStrip; + enable(element: Element, enable?: boolean): kendo.ui.TabStrip; + enable(element: JQuery, enable?: boolean): kendo.ui.TabStrip; + insertAfter(item: string, referenceTab: string): kendo.ui.TabStrip; + insertAfter(item: string, referenceTab: Element): kendo.ui.TabStrip; + insertAfter(item: string, referenceTab: JQuery): kendo.ui.TabStrip; + insertAfter(item: Element, referenceTab: string): kendo.ui.TabStrip; + insertAfter(item: Element, referenceTab: Element): kendo.ui.TabStrip; + insertAfter(item: Element, referenceTab: JQuery): kendo.ui.TabStrip; + insertAfter(item: JQuery, referenceTab: string): kendo.ui.TabStrip; + insertAfter(item: JQuery, referenceTab: Element): kendo.ui.TabStrip; + insertAfter(item: JQuery, referenceTab: JQuery): kendo.ui.TabStrip; + insertBefore(item: string, referenceTab: string): kendo.ui.TabStrip; + insertBefore(item: string, referenceTab: Element): kendo.ui.TabStrip; + insertBefore(item: string, referenceTab: JQuery): kendo.ui.TabStrip; + insertBefore(item: Element, referenceTab: string): kendo.ui.TabStrip; + insertBefore(item: Element, referenceTab: Element): kendo.ui.TabStrip; + insertBefore(item: Element, referenceTab: JQuery): kendo.ui.TabStrip; + insertBefore(item: JQuery, referenceTab: string): kendo.ui.TabStrip; + insertBefore(item: JQuery, referenceTab: Element): kendo.ui.TabStrip; + insertBefore(item: JQuery, referenceTab: JQuery): kendo.ui.TabStrip; + items(): HTMLCollection; + reload(element: string): kendo.ui.TabStrip; + reload(element: Element): kendo.ui.TabStrip; + reload(element: JQuery): kendo.ui.TabStrip; + remove(element: string): kendo.ui.TabStrip; + remove(element: number): kendo.ui.TabStrip; + select(): JQuery; + select(element: string): void; + select(element: Element): void; + select(element: JQuery): void; + select(element: number): void; + setDataSource(): void; + tabGroup: JQuery; + } + + interface TabStripAnimationClose { + duration?: number; + effects?: string; + } + + interface TabStripAnimationOpen { + duration?: number; + effects?: string; + } + + interface TabStripAnimation { + close?: TabStripAnimationClose; + open?: TabStripAnimationOpen; + } + + interface TabStripOptions { + name?: string; + animation?: TabStripAnimation; + collapsible?: boolean; + contentUrls?: any; + dataContentField?: string; + dataContentUrlField?: string; + dataImageUrlField?: string; + dataSpriteCssClass?: string; + dataTextField?: string; + dataUrlField?: string; + navigatable?: boolean; + tabPosition?: string; + activate?(e: TabStripActivateEvent): void; + contentLoad?(e: TabStripContentLoadEvent): void; + error?(e: TabStripErrorEvent): void; + select?(e: TabStripSelectEvent): void; + show?(e: TabStripShowEvent): void; + } + interface TabStripEvent { + sender: TabStrip; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TabStripActivateEvent extends TabStripEvent { + item?: Element; + contentElement?: Element; + } + + interface TabStripContentLoadEvent extends TabStripEvent { + item?: Element; + contentElement?: Element; + } + + interface TabStripErrorEvent extends TabStripEvent { + xhr?: JQueryXHR; + status?: string; + } + + interface TabStripSelectEvent extends TabStripEvent { + item?: Element; + contentElement?: Element; + } + + interface TabStripShowEvent extends TabStripEvent { + item?: Element; + contentElement?: Element; + } + + + class TimePicker extends kendo.ui.Widget { + static fn: TimePicker; + static extend(proto: Object): TimePicker; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TimePickerOptions); + options: TimePickerOptions; + close(): void; + destroy(): void; + enable(enable: boolean): void; + readonly(readonly: boolean): void; + max(): Date; + max(value: Date): void; + max(value: string): void; + min(): Date; + min(value: Date): void; + min(value: string): void; + open(): void; + setOptions(options: any): void; + value(): Date; + value(value: Date): void; + value(value: string): void; + } + + interface TimePickerAnimationClose { + effects?: string; + duration?: number; + } + + interface TimePickerAnimationOpen { + effects?: string; + duration?: number; + } + + interface TimePickerAnimation { + close?: TimePickerAnimationClose; + open?: TimePickerAnimationOpen; + } + + interface TimePickerOptions { + name?: string; + animation?: TimePickerAnimation; + culture?: string; + dates?: any; + format?: string; + interval?: number; + max?: Date; + min?: Date; + parseFormats?: any; + value?: Date; + change?(e: TimePickerChangeEvent): void; + close?(e: TimePickerCloseEvent): void; + open?(e: TimePickerOpenEvent): void; + } + interface TimePickerEvent { + sender: TimePicker; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TimePickerChangeEvent extends TimePickerEvent { + } + + interface TimePickerCloseEvent extends TimePickerEvent { + } + + interface TimePickerOpenEvent extends TimePickerEvent { + } + + + class ToolBar extends kendo.ui.Widget { + static fn: ToolBar; + static extend(proto: Object): ToolBar; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ToolBarOptions); + options: ToolBarOptions; + add(command: any): void; + destroy(): void; + enable(command: string, enable: boolean): void; + enable(command: Element, enable: boolean): void; + enable(command: JQuery, enable: boolean): void; + getSelectedFromGroup(groupName: string): void; + remove(command: string): void; + remove(command: Element): void; + remove(command: JQuery): void; + toggle(): void; + } + + interface ToolBarItemButton { + attributes?: any; + click?: Function; + enable?: boolean; + group?: string; + icon?: string; + id?: string; + imageUrl?: string; + selected?: boolean; + showIcon?: string; + showText?: string; + spriteCssClass?: string; + toggle?: Function; + togglable?: boolean; + text?: string; + url?: string; + } + + interface ToolBarItemMenuButton { + attributes?: any; + enable?: boolean; + icon?: string; + id?: string; + imageUrl?: string; + spriteCssClass?: string; + text?: string; + url?: string; + } + + interface ToolBarItem { + attributes?: any; + buttons?: ToolBarItemButton[]; + click?: Function; + enable?: boolean; + group?: string; + icon?: string; + id?: string; + imageUrl?: string; + menuButtons?: ToolBarItemMenuButton[]; + overflow?: string; + overflowTemplate?: any; + primary?: boolean; + selected?: boolean; + showIcon?: string; + showText?: string; + spriteCssClass?: string; + template?: any; + text?: string; + togglable?: boolean; + toggle?: Function; + type?: string; + url?: string; + } + + interface ToolBarOptions { + name?: string; + resizable?: boolean; + items?: ToolBarItem[]; + click?(e: ToolBarClickEvent): void; + close?(e: ToolBarCloseEvent): void; + open?(e: ToolBarOpenEvent): void; + toggle?(e: ToolBarToggleEvent): void; + overflowClose?(e: ToolBarOverflowCloseEvent): void; + overflowOpen?(e: ToolBarOverflowOpenEvent): void; + } + interface ToolBarEvent { + sender: ToolBar; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ToolBarClickEvent extends ToolBarEvent { + target?: JQuery; + id?: string; + } + + interface ToolBarCloseEvent extends ToolBarEvent { + SplitButton?: JQuery; + } + + interface ToolBarOpenEvent extends ToolBarEvent { + SplitButton?: JQuery; + } + + interface ToolBarToggleEvent extends ToolBarEvent { + target?: JQuery; + checked?: boolean; + id?: string; + } + + interface ToolBarOverflowCloseEvent extends ToolBarEvent { + } + + interface ToolBarOverflowOpenEvent extends ToolBarEvent { + } + + + class Tooltip extends kendo.ui.Widget { + static fn: Tooltip; + static extend(proto: Object): Tooltip; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TooltipOptions); + options: TooltipOptions; + show(element: JQuery): void; + hide(): void; + refresh(): void; + target(): JQuery; + } + + interface TooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface TooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface TooltipAnimation { + close?: TooltipAnimationClose; + open?: TooltipAnimationOpen; + } + + interface TooltipContent { + url?: string; + } + + interface TooltipOptions { + name?: string; + autoHide?: boolean; + animation?: TooltipAnimation; + content?: TooltipContent; + callout?: boolean; + filter?: string; + iframe?: boolean; + height?: number; + width?: number; + position?: string; + showAfter?: number; + showOn?: string; + contentLoad?(e: TooltipEvent): void; + show?(e: TooltipEvent): void; + hide?(e: TooltipEvent): void; + requestStart?(e: TooltipRequestStartEvent): void; + error?(e: TooltipErrorEvent): void; + } + interface TooltipEvent { + sender: Tooltip; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TooltipRequestStartEvent extends TooltipEvent { + target?: JQuery; + options?: any; + } + + interface TooltipErrorEvent extends TooltipEvent { + xhr?: JQueryXHR; + status?: string; + } + + + class Touch extends kendo.ui.Widget { + static fn: Touch; + static extend(proto: Object): Touch; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TouchOptions); + options: TouchOptions; + cancel(): void; + destroy(): void; + } + + interface TouchOptions { + name?: string; + filter?: string; + surface?: JQuery; + multiTouch?: boolean; + enableSwipe?: boolean; + minXDelta?: number; + maxYDelta?: number; + maxDuration?: number; + minHold?: number; + doubleTapTimeout?: number; + touchstart?(e: TouchTouchstartEvent): void; + dragstart?(e: TouchDragstartEvent): void; + drag?(e: TouchDragEvent): void; + dragend?(e: TouchDragendEvent): void; + tap?(e: TouchTapEvent): void; + doubletap?(e: TouchDoubletapEvent): void; + hold?(e: TouchHoldEvent): void; + swipe?(e: TouchSwipeEvent): void; + gesturestart?(e: TouchGesturestartEvent): void; + gesturechange?(e: TouchGesturechangeEvent): void; + gestureend?(e: TouchGestureendEvent): void; + } + interface TouchEvent { + sender: Touch; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TouchTouchstartEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchDragstartEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchDragEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchDragendEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchTapEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchDoubletapEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchHoldEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchSwipeEvent extends TouchEvent { + touch?: kendo.mobile.ui.TouchEventOptions; + event?: JQueryEventObject; + } + + interface TouchGesturestartEvent extends TouchEvent { + touches?: any; + event?: JQueryEventObject; + distance?: number; + center?: kendo.mobile.ui.Point; + } + + interface TouchGesturechangeEvent extends TouchEvent { + touches?: any; + event?: JQueryEventObject; + distance?: number; + center?: kendo.mobile.ui.Point; + } + + interface TouchGestureendEvent extends TouchEvent { + touches?: any; + event?: JQueryEventObject; + distance?: number; + center?: kendo.mobile.ui.Point; + } + + + class TreeList extends kendo.ui.Widget { + static fn: TreeList; + static extend(proto: Object): TreeList; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TreeListOptions); + options: TreeListOptions; + dataSource: kendo.data.DataSource; + addRow(parentRow: string): void; + addRow(parentRow: Element): void; + addRow(parentRow: JQuery): void; + cancelRow(): void; + clearSelection(): void; + collapse(): void; + dataItem(row: string): kendo.data.TreeListModel; + dataItem(row: Element): kendo.data.TreeListModel; + dataItem(row: JQuery): kendo.data.TreeListModel; + destroy(): void; + editRow(row: JQuery): void; + expand(): void; + refresh(): void; + removeRow(row: string): void; + removeRow(row: Element): void; + removeRow(row: JQuery): void; + saveAsExcel(): void; + saveAsPDF(): JQueryPromise; + saveRow(): void; + select(): JQuery; + select(rows: Element): void; + select(rows: JQuery): void; + setDataSource(dataSource: kendo.data.TreeListDataSource): void; + showColumn(column: number): void; + showColumn(column: string): void; + hideColumn(column: number): void; + hideColumn(column: string): void; + lockColumn(column: number): void; + lockColumn(column: string): void; + unlockColumn(column: number): void; + unlockColumn(column: string): void; + reorderColumn(destIndex: number, column: any): void; + } + + interface TreeListColumnMenuMessages { + columns?: string; + filter?: string; + sortAscending?: string; + sortDescending?: string; + } + + interface TreeListColumnMenu { + columns?: boolean; + filterable?: boolean; + sortable?: boolean; + messages?: TreeListColumnMenuMessages; + } + + interface TreeListColumnCommandItem { + className?: string; + click?: Function; + name?: string; + text?: string; + } + + interface TreeListColumnFilterable { + ui?: any; + } + + interface TreeListColumnSortable { + compare?: Function; + } + + interface TreeListColumn { + attributes?: any; + command?: TreeListColumnCommandItem[]; + encoded?: boolean; + expandable?: boolean; + field?: string; + filterable?: TreeListColumnFilterable; + footerTemplate?: any; + format?: string; + headerAttributes?: any; + headerTemplate?: any; + sortable?: TreeListColumnSortable; + template?: any; + title?: string; + width?: any; + hidden?: boolean; + menu?: boolean; + locked?: boolean; + lockable?: boolean; + } + + interface TreeListEditable { + mode?: string; + template?: any; + window?: any; + } + + interface TreeListExcel { + fileName?: string; + filterable?: boolean; + forceProxy?: boolean; + proxyURL?: string; + } + + interface TreeListFilterableMessages { + and?: string; + clear?: string; + filter?: string; + info?: string; + isFalse?: string; + isTrue?: string; + or?: string; + selectValue?: string; + cancel?: string; + operator?: string; + } + + interface TreeListFilterable { + extra?: boolean; + messages?: TreeListFilterableMessages; + } + + interface TreeListMessagesCommands { + canceledit?: string; + create?: string; + createchild?: string; + destroy?: string; + edit?: string; + excel?: string; + pdf?: string; + update?: string; + } + + interface TreeListMessages { + commands?: TreeListMessagesCommands; + loading?: string; + noRows?: string; + requestFailed?: string; + retry?: string; + } + + interface TreeListPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface TreeListPdf { + author?: string; + creator?: string; + date?: Date; + fileName?: string; + forceProxy?: boolean; + keywords?: string; + landscape?: boolean; + margin?: TreeListPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface TreeListSortable { + allowUnsort?: boolean; + mode?: string; + } + + interface TreeListToolbarItem { + name?: string; + text?: string; + } + + interface TreeListOptions { + name?: string; + autoBind?: boolean; + columns?: TreeListColumn[]; + resizable?: boolean; + reorderable?: boolean; + columnMenu?: TreeListColumnMenu; + dataSource?: any; + editable?: TreeListEditable; + excel?: TreeListExcel; + filterable?: TreeListFilterable; + height?: any; + messages?: TreeListMessages; + pdf?: TreeListPdf; + scrollable?: any; + selectable?: any; + sortable?: TreeListSortable; + toolbar?: TreeListToolbarItem[]; + cancel?(e: TreeListCancelEvent): void; + change?(e: TreeListChangeEvent): void; + collapse?(e: TreeListCollapseEvent): void; + dataBinding?(e: TreeListDataBindingEvent): void; + dataBound?(e: TreeListDataBoundEvent): void; + edit?(e: TreeListEditEvent): void; + excelExport?(e: TreeListExcelExportEvent): void; + expand?(e: TreeListExpandEvent): void; + filterMenuInit?(e: TreeListFilterMenuInitEvent): void; + pdfExport?(e: TreeListPdfExportEvent): void; + remove?(e: TreeListRemoveEvent): void; + save?(e: TreeListSaveEvent): void; + columnShow?(e: TreeListColumnShowEvent): void; + columnHide?(e: TreeListColumnHideEvent): void; + columnReorder?(e: TreeListColumnReorderEvent): void; + columnMenuInit?(e: TreeListColumnMenuInitEvent): void; + columnLock?(e: TreeListColumnLockEvent): void; + columnUnlock?(e: TreeListColumnUnlockEvent): void; + } + interface TreeListEvent { + sender: TreeList; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TreeListCancelEvent extends TreeListEvent { + container?: JQuery; + model?: kendo.data.TreeListModel; + } + + interface TreeListChangeEvent extends TreeListEvent { + } + + interface TreeListCollapseEvent extends TreeListEvent { + model?: kendo.data.TreeListModel; + } + + interface TreeListDataBindingEvent extends TreeListEvent { + } + + interface TreeListDataBoundEvent extends TreeListEvent { + } + + interface TreeListEditEvent extends TreeListEvent { + container?: JQuery; + model?: kendo.data.TreeListModel; + } + + interface TreeListExcelExportEvent extends TreeListEvent { + data?: any; + workbook?: any; + } + + interface TreeListExpandEvent extends TreeListEvent { + model?: kendo.data.TreeListModel; + } + + interface TreeListFilterMenuInitEvent extends TreeListEvent { + container?: JQuery; + field?: string; + } + + interface TreeListPdfExportEvent extends TreeListEvent { + promise?: JQueryPromise; + } + + interface TreeListRemoveEvent extends TreeListEvent { + model?: kendo.data.TreeListModel; + row?: JQuery; + } + + interface TreeListSaveEvent extends TreeListEvent { + model?: kendo.data.TreeListModel; + container?: JQuery; + } + + interface TreeListColumnShowEvent extends TreeListEvent { + column?: any; + } + + interface TreeListColumnHideEvent extends TreeListEvent { + column?: any; + } + + interface TreeListColumnReorderEvent extends TreeListEvent { + column?: any; + newIndex?: number; + oldIndex?: number; + } + + interface TreeListColumnMenuInitEvent extends TreeListEvent { + container?: JQuery; + field?: string; + } + + interface TreeListColumnLockEvent extends TreeListEvent { + column?: any; + } + + interface TreeListColumnUnlockEvent extends TreeListEvent { + column?: any; + } + + + class TreeView extends kendo.ui.Widget { + static fn: TreeView; + static extend(proto: Object): TreeView; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TreeViewOptions); + options: TreeViewOptions; + dataSource: kendo.data.DataSource; + append(nodeData: any, parentNode?: JQuery, success?: Function): JQuery; + append(nodeData: JQuery, parentNode?: JQuery, success?: Function): JQuery; + collapse(nodes: JQuery): void; + collapse(nodes: Element): void; + collapse(nodes: string): void; + dataItem(node: JQuery): kendo.data.Node; + dataItem(node: Element): kendo.data.Node; + dataItem(node: string): kendo.data.Node; + destroy(): void; + detach(node: JQuery): JQuery; + detach(node: Element): JQuery; + detach(node: string): JQuery; + enable(nodes: JQuery, enable?: boolean): void; + enable(nodes: Element, enable?: boolean): void; + enable(nodes: string, enable?: boolean): void; + expand(nodes: JQuery): void; + expand(nodes: Element): void; + expand(nodes: string): void; + expandPath(path: any, complete: Function): void; + expandTo(targetNode: kendo.data.Node): void; + expandTo(targetNode: any): void; + findByText(text: string): JQuery; + findByUid(text: string): JQuery; + insertAfter(nodeData: any, referenceNode: JQuery): void; + insertBefore(nodeData: any, referenceNode: JQuery): void; + parent(node: JQuery): JQuery; + parent(node: Element): JQuery; + parent(node: string): JQuery; + remove(node: JQuery): void; + remove(node: Element): void; + remove(node: string): void; + select(): JQuery; + select(node?: JQuery): void; + select(node?: Element): void; + select(node?: string): void; + setDataSource(dataSource: kendo.data.HierarchicalDataSource): void; + text(): string; + text(node: JQuery, newText: string): void; + text(node: Element, newText: string): void; + text(node: string, newText: string): void; + toggle(node: JQuery): void; + toggle(node: Element): void; + toggle(node: string): void; + updateIndeterminate(node: JQuery): void; + } + + interface TreeViewAnimationCollapse { + duration?: number; + effects?: string; + } + + interface TreeViewAnimationExpand { + duration?: number; + effects?: string; + } + + interface TreeViewAnimation { + collapse?: TreeViewAnimationCollapse; + expand?: TreeViewAnimationExpand; + } + + interface TreeViewCheckboxes { + checkChildren?: boolean; + name?: string; + template?: any; + } + + interface TreeViewMessages { + loading?: string; + requestFailed?: string; + retry?: string; + } + + interface TreeViewOptions { + name?: string; + animation?: TreeViewAnimation; + autoBind?: boolean; + checkboxes?: TreeViewCheckboxes; + dataImageUrlField?: string; + dataSource?: any; + dataSpriteCssClassField?: string; + dataTextField?: any; + dataUrlField?: string; + dragAndDrop?: boolean; + loadOnDemand?: boolean; + messages?: TreeViewMessages; + template?: any; + change?(e: TreeViewEvent): void; + check?(e: TreeViewCheckEvent): void; + collapse?(e: TreeViewCollapseEvent): void; + dataBound?(e: TreeViewDataBoundEvent): void; + drag?(e: TreeViewDragEvent): void; + dragend?(e: TreeViewDragendEvent): void; + dragstart?(e: TreeViewDragstartEvent): void; + drop?(e: TreeViewDropEvent): void; + expand?(e: TreeViewExpandEvent): void; + navigate?(e: TreeViewNavigateEvent): void; + select?(e: TreeViewSelectEvent): void; + } + interface TreeViewEvent { + sender: TreeView; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TreeViewCheckEvent extends TreeViewEvent { + node?: Element; + } + + interface TreeViewCollapseEvent extends TreeViewEvent { + node?: Element; + } + + interface TreeViewDataBoundEvent extends TreeViewEvent { + node?: JQuery; + } + + interface TreeViewDragEvent extends TreeViewEvent { + sourceNode?: Element; + dropTarget?: Element; + pageX?: number; + pageY?: number; + statusClass?: string; + setStatusClass?: Function; + } + + interface TreeViewDragendEvent extends TreeViewEvent { + sourceNode?: Element; + destinationNode?: Element; + dropPosition?: string; + } + + interface TreeViewDragstartEvent extends TreeViewEvent { + sourceNode?: Element; + } + + interface TreeViewDropEvent extends TreeViewEvent { + sourceNode?: Element; + destinationNode?: Element; + valid?: boolean; + setValid?: Function; + dropTarget?: Element; + dropPosition?: string; + } + + interface TreeViewExpandEvent extends TreeViewEvent { + node?: Element; + } + + interface TreeViewNavigateEvent extends TreeViewEvent { + node?: Element; + } + + interface TreeViewSelectEvent extends TreeViewEvent { + node?: Element; + } + + + class Upload extends kendo.ui.Widget { + static fn: Upload; + static extend(proto: Object): Upload; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: UploadOptions); + options: UploadOptions; + destroy(): void; + disable(): void; + enable(enable?: boolean): void; + toggle(enable: boolean): void; + } + + interface UploadAsync { + autoUpload?: boolean; + batch?: boolean; + removeField?: string; + removeUrl?: string; + removeVerb?: string; + saveField?: string; + saveUrl?: string; + withCredentials?: boolean; + } + + interface UploadFile { + extension?: string; + name?: string; + size?: number; + } + + interface UploadLocalization { + cancel?: string; + dropFilesHere?: string; + headerStatusUploaded?: string; + headerStatusUploading?: string; + remove?: string; + retry?: string; + select?: string; + statusFailed?: string; + statusUploaded?: string; + statusUploading?: string; + uploadSelectedFiles?: string; + } + + interface UploadOptions { + name?: string; + async?: UploadAsync; + enabled?: boolean; + files?: UploadFile[]; + localization?: UploadLocalization; + multiple?: boolean; + showFileList?: boolean; + template?: any; + cancel?(e: UploadCancelEvent): void; + complete?(e: UploadEvent): void; + error?(e: UploadErrorEvent): void; + progress?(e: UploadProgressEvent): void; + remove?(e: UploadRemoveEvent): void; + select?(e: UploadSelectEvent): void; + success?(e: UploadSuccessEvent): void; + upload?(e: UploadUploadEvent): void; + } + interface UploadEvent { + sender: Upload; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface UploadCancelEvent extends UploadEvent { + files?: any; + } + + interface UploadErrorEvent extends UploadEvent { + files?: any; + operation?: string; + XMLHttpRequest?: any; + } + + interface UploadProgressEvent extends UploadEvent { + files?: any; + percentComplete?: number; + } + + interface UploadRemoveEvent extends UploadEvent { + files?: any; + data?: any; + } + + interface UploadSelectEvent extends UploadEvent { + e?: any; + files?: any; + } + + interface UploadSuccessEvent extends UploadEvent { + files?: any; + operation?: string; + response?: string; + XMLHttpRequest?: any; + } + + interface UploadUploadEvent extends UploadEvent { + files?: any; + data?: any; + formData?: any; + XMLHttpRequest?: any; + } + + + class Validator extends kendo.ui.Widget { + static fn: Validator; + static extend(proto: Object): Validator; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ValidatorOptions); + options: ValidatorOptions; + errors(): any; + hideMessages(): void; + validate(): boolean; + validateInput(input: Element): boolean; + validateInput(input: JQuery): boolean; + } + + interface ValidatorOptions { + name?: string; + errorTemplate?: string; + messages?: any; + rules?: any; + validateOnBlur?: boolean; + validate?(e: ValidatorValidateEvent): void; + } + interface ValidatorEvent { + sender: Validator; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ValidatorValidateEvent extends ValidatorEvent { + } + + + class Window extends kendo.ui.Widget { + static fn: Window; + static extend(proto: Object): Window; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: WindowOptions); + options: WindowOptions; + center(): kendo.ui.Window; + close(): kendo.ui.Window; + content(): any; + content(content?: string): void; + destroy(): void; + maximize(): kendo.ui.Window; + minimize(): kendo.ui.Window; + open(): kendo.ui.Window; + pin(): void; + refresh(options: any): kendo.ui.Window; + restore(): kendo.ui.Window; + setOptions(options: any): void; + title(): kendo.ui.Window; + title(text?: string): void; + toFront(): kendo.ui.Window; + toggleMaximization(): kendo.ui.Window; + unpin(): void; + } + + interface WindowAnimationClose { + effects?: string; + duration?: number; + } + + interface WindowAnimationOpen { + effects?: string; + duration?: number; + } + + interface WindowAnimation { + close?: WindowAnimationClose; + open?: WindowAnimationOpen; + } + + interface WindowContent { + template?: string; + } + + interface WindowPosition { + top?: any; + left?: any; + } + + interface WindowRefreshOptions { + url?: string; + data?: any; + type?: string; + template?: string; + iframe?: boolean; + } + + interface WindowOptions { + name?: string; + actions?: any; + animation?: WindowAnimation; + appendTo?: any; + autoFocus?: boolean; + content?: WindowContent; + draggable?: boolean; + iframe?: boolean; + maxHeight?: number; + maxWidth?: number; + minHeight?: number; + minWidth?: number; + modal?: boolean; + pinned?: boolean; + position?: WindowPosition; + resizable?: boolean; + title?: any; + visible?: boolean; + width?: any; + height?: any; + activate?(e: WindowEvent): void; + close?(e: WindowCloseEvent): void; + deactivate?(e: WindowEvent): void; + dragend?(e: WindowEvent): void; + dragstart?(e: WindowEvent): void; + error?(e: WindowErrorEvent): void; + open?(e: WindowEvent): void; + refresh?(e: WindowEvent): void; + resize?(e: WindowEvent): void; + } + interface WindowEvent { + sender: Window; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface WindowCloseEvent extends WindowEvent { + userTriggered?: boolean; + } + + interface WindowErrorEvent extends WindowEvent { + xhr?: JQueryXHR; + status?: string; + } + + +} +declare module kendo.dataviz.ui { + class Barcode extends kendo.ui.Widget { + static fn: Barcode; + static extend(proto: Object): Barcode; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: BarcodeOptions); + options: BarcodeOptions; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + imageDataURL(): string; + redraw(): void; + resize(force?: boolean): void; + svg(): string; + value(): string; + value(value: number): void; + value(value: string): void; + } + + interface BarcodeBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface BarcodePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface BarcodeTextMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface BarcodeText { + color?: string; + font?: string; + margin?: BarcodeTextMargin; + visible?: boolean; + } + + interface BarcodeExportImageOptions { + width?: string; + height?: string; + } + + interface BarcodeExportSVGOptions { + raw?: boolean; + } + + interface BarcodeOptions { + name?: string; + renderAs?: string; + background?: string; + border?: BarcodeBorder; + checksum?: boolean; + color?: string; + height?: number; + padding?: BarcodePadding; + text?: BarcodeText; + type?: string; + value?: string; + width?: number; + } + interface BarcodeEvent { + sender: Barcode; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Chart extends kendo.ui.Widget { + static fn: Chart; + static extend(proto: Object): Chart; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ChartOptions); + options: ChartOptions; + dataSource: kendo.data.DataSource; + destroy(): void; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + getAxis(name: string): kendo.dataviz.ChartAxis; + redraw(): void; + refresh(): void; + resize(force?: boolean): void; + saveAsPDF(): void; + setDataSource(dataSource: kendo.data.DataSource): void; + setOptions(options: any): void; + svg(): string; + imageDataURL(): string; + toggleHighlight(show: boolean, options: any): void; + } + + interface ChartCategoryAxisItemAutoBaseUnitSteps { + seconds?: any; + minutes?: any; + hours?: any; + days?: any; + weeks?: any; + months?: any; + years?: any; + } + + interface ChartCategoryAxisItemCrosshairTooltipBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartCategoryAxisItemCrosshairTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartCategoryAxisItemCrosshairTooltip { + background?: string; + border?: ChartCategoryAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: ChartCategoryAxisItemCrosshairTooltipPadding; + template?: any; + visible?: boolean; + } + + interface ChartCategoryAxisItemCrosshair { + color?: string; + opacity?: number; + tooltip?: ChartCategoryAxisItemCrosshairTooltip; + visible?: boolean; + width?: number; + } + + interface ChartCategoryAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartCategoryAxisItemLabelsDateFormats { + days?: string; + hours?: string; + months?: string; + weeks?: string; + years?: string; + } + + interface ChartCategoryAxisItemLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartCategoryAxisItemLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartCategoryAxisItemLabels { + background?: string; + border?: ChartCategoryAxisItemLabelsBorder; + color?: string; + culture?: string; + dateFormats?: ChartCategoryAxisItemLabelsDateFormats; + font?: string; + format?: string; + margin?: ChartCategoryAxisItemLabelsMargin; + mirror?: boolean; + padding?: ChartCategoryAxisItemLabelsPadding; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + visual?: Function; + } + + interface ChartCategoryAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface ChartCategoryAxisItemMajorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartCategoryAxisItemMajorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartCategoryAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartCategoryAxisItemMinorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartCategoryAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface ChartCategoryAxisItemNotesDataItemIcon { + background?: string; + border?: ChartCategoryAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartCategoryAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartCategoryAxisItemNotesDataItemLabel { + background?: string; + border?: ChartCategoryAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface ChartCategoryAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartCategoryAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: ChartCategoryAxisItemNotesDataItemIcon; + label?: ChartCategoryAxisItemNotesDataItemLabel; + line?: ChartCategoryAxisItemNotesDataItemLine; + } + + interface ChartCategoryAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface ChartCategoryAxisItemNotesIcon { + background?: string; + border?: ChartCategoryAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartCategoryAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartCategoryAxisItemNotesLabel { + background?: string; + border?: ChartCategoryAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface ChartCategoryAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartCategoryAxisItemNotes { + position?: string; + icon?: ChartCategoryAxisItemNotesIcon; + label?: ChartCategoryAxisItemNotesLabel; + line?: ChartCategoryAxisItemNotesLine; + data?: ChartCategoryAxisItemNotesDataItem[]; + visual?: Function; + } + + interface ChartCategoryAxisItemPlotBand { + color?: string; + from?: number; + opacity?: number; + to?: number; + } + + interface ChartCategoryAxisItemSelectMousewheel { + reverse?: boolean; + zoom?: string; + } + + interface ChartCategoryAxisItemSelect { + from?: any; + max?: any; + min?: any; + mousewheel?: ChartCategoryAxisItemSelectMousewheel; + to?: any; + } + + interface ChartCategoryAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartCategoryAxisItemTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartCategoryAxisItemTitlePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartCategoryAxisItemTitle { + background?: string; + border?: ChartCategoryAxisItemTitleBorder; + color?: string; + font?: string; + margin?: ChartCategoryAxisItemTitleMargin; + padding?: ChartCategoryAxisItemTitlePadding; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + visual?: Function; + } + + interface ChartCategoryAxisItem { + autoBaseUnitSteps?: ChartCategoryAxisItemAutoBaseUnitSteps; + axisCrossingValue?: any; + background?: string; + baseUnit?: string; + baseUnitStep?: any; + categories?: any; + color?: string; + crosshair?: ChartCategoryAxisItemCrosshair; + field?: string; + justified?: boolean; + labels?: ChartCategoryAxisItemLabels; + line?: ChartCategoryAxisItemLine; + majorGridLines?: ChartCategoryAxisItemMajorGridLines; + majorTicks?: ChartCategoryAxisItemMajorTicks; + max?: any; + maxDateGroups?: number; + min?: any; + minorGridLines?: ChartCategoryAxisItemMinorGridLines; + minorTicks?: ChartCategoryAxisItemMinorTicks; + name?: string; + pane?: string; + plotBands?: ChartCategoryAxisItemPlotBand[]; + reverse?: boolean; + roundToBaseUnit?: boolean; + select?: ChartCategoryAxisItemSelect; + startAngle?: number; + title?: ChartCategoryAxisItemTitle; + type?: string; + visible?: boolean; + weekStartDay?: number; + notes?: ChartCategoryAxisItemNotes; + } + + interface ChartChartAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartChartAreaMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartChartArea { + background?: string; + border?: ChartChartAreaBorder; + height?: number; + margin?: ChartChartAreaMargin; + opacity?: number; + width?: number; + } + + interface ChartLegendBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartLegendInactiveItemsLabels { + color?: string; + font?: string; + template?: any; + } + + interface ChartLegendInactiveItems { + labels?: ChartLegendInactiveItemsLabels; + } + + interface ChartLegendItem { + visual?: Function; + } + + interface ChartLegendLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartLegendLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartLegendLabels { + color?: string; + font?: string; + margin?: ChartLegendLabelsMargin; + padding?: ChartLegendLabelsPadding; + template?: any; + } + + interface ChartLegendMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartLegendPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartLegend { + align?: string; + background?: string; + border?: ChartLegendBorder; + height?: number; + inactiveItems?: ChartLegendInactiveItems; + item?: ChartLegendItem; + labels?: ChartLegendLabels; + margin?: ChartLegendMargin; + offsetX?: number; + offsetY?: number; + orientation?: string; + padding?: ChartLegendPadding; + position?: string; + reverse?: boolean; + visible?: boolean; + width?: number; + } + + interface ChartPaneBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartPaneMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartPanePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartPaneTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartPaneTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartPaneTitle { + background?: string; + border?: ChartPaneTitleBorder; + color?: string; + font?: string; + margin?: ChartPaneTitleMargin; + position?: string; + text?: string; + visible?: boolean; + visual?: Function; + } + + interface ChartPane { + background?: string; + border?: ChartPaneBorder; + clip?: boolean; + height?: number; + margin?: ChartPaneMargin; + name?: string; + padding?: ChartPanePadding; + title?: ChartPaneTitle; + } + + interface ChartPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface ChartPdf { + author?: string; + creator?: string; + date?: Date; + forceProxy?: boolean; + fileName?: string; + keywords?: string; + landscape?: boolean; + margin?: ChartPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface ChartPlotAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartPlotAreaMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartPlotAreaPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartPlotArea { + background?: string; + border?: ChartPlotAreaBorder; + margin?: ChartPlotAreaMargin; + opacity?: number; + padding?: ChartPlotAreaPadding; + } + + interface ChartSeriesItemBorder { + color?: any; + dashType?: any; + opacity?: any; + width?: any; + } + + interface ChartSeriesItemConnectors { + color?: string; + padding?: number; + width?: number; + } + + interface ChartSeriesItemErrorBarsLine { + width?: number; + dashType?: string; + } + + interface ChartSeriesItemErrorBars { + value?: any; + visual?: Function; + xValue?: any; + yValue?: any; + endCaps?: boolean; + color?: string; + line?: ChartSeriesItemErrorBarsLine; + } + + interface ChartSeriesItemExtremesBorder { + color?: any; + width?: any; + } + + interface ChartSeriesItemExtremes { + background?: any; + border?: ChartSeriesItemExtremesBorder; + size?: any; + type?: any; + rotation?: any; + } + + interface ChartSeriesItemHighlightBorder { + color?: string; + opacity?: number; + width?: number; + } + + interface ChartSeriesItemHighlightLine { + color?: string; + opacity?: number; + width?: number; + } + + interface ChartSeriesItemHighlight { + border?: ChartSeriesItemHighlightBorder; + color?: string; + line?: ChartSeriesItemHighlightLine; + opacity?: number; + toggle?: Function; + visible?: boolean; + visual?: Function; + } + + interface ChartSeriesItemLabelsBorder { + color?: any; + dashType?: any; + width?: any; + } + + interface ChartSeriesItemLabelsFromBorder { + color?: any; + dashType?: any; + width?: any; + } + + interface ChartSeriesItemLabelsFromMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemLabelsFromPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemLabelsFrom { + background?: any; + border?: ChartSeriesItemLabelsFromBorder; + color?: any; + font?: any; + format?: any; + margin?: ChartSeriesItemLabelsFromMargin; + padding?: ChartSeriesItemLabelsFromPadding; + position?: any; + template?: any; + visible?: any; + } + + interface ChartSeriesItemLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemLabelsToBorder { + color?: any; + dashType?: any; + width?: any; + } + + interface ChartSeriesItemLabelsToMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemLabelsToPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemLabelsTo { + background?: any; + border?: ChartSeriesItemLabelsToBorder; + color?: any; + font?: any; + format?: any; + margin?: ChartSeriesItemLabelsToMargin; + padding?: ChartSeriesItemLabelsToPadding; + position?: any; + template?: any; + visible?: any; + } + + interface ChartSeriesItemLabels { + align?: string; + background?: any; + border?: ChartSeriesItemLabelsBorder; + color?: any; + distance?: number; + font?: any; + format?: any; + margin?: ChartSeriesItemLabelsMargin; + padding?: ChartSeriesItemLabelsPadding; + position?: any; + template?: any; + visible?: any; + visual?: Function; + from?: ChartSeriesItemLabelsFrom; + to?: ChartSeriesItemLabelsTo; + } + + interface ChartSeriesItemLine { + color?: string; + opacity?: number; + width?: string; + style?: string; + } + + interface ChartSeriesItemMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemMarkersBorder { + color?: any; + width?: any; + } + + interface ChartSeriesItemMarkers { + background?: any; + border?: ChartSeriesItemMarkersBorder; + size?: any; + type?: any; + visible?: any; + visual?: Function; + rotation?: any; + } + + interface ChartSeriesItemNegativeValues { + color?: string; + visible?: boolean; + } + + interface ChartSeriesItemNotesIconBorder { + color?: string; + width?: number; + } + + interface ChartSeriesItemNotesIcon { + background?: string; + border?: ChartSeriesItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartSeriesItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartSeriesItemNotesLabel { + background?: string; + border?: ChartSeriesItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface ChartSeriesItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartSeriesItemNotes { + position?: string; + icon?: ChartSeriesItemNotesIcon; + label?: ChartSeriesItemNotesLabel; + line?: ChartSeriesItemNotesLine; + visual?: Function; + } + + interface ChartSeriesItemOutliersBorder { + color?: any; + width?: any; + } + + interface ChartSeriesItemOutliers { + background?: any; + border?: ChartSeriesItemOutliersBorder; + size?: any; + type?: any; + rotation?: any; + } + + interface ChartSeriesItemOverlay { + gradient?: string; + } + + interface ChartSeriesItemStack { + type?: string; + group?: string; + } + + interface ChartSeriesItemTargetBorder { + color?: any; + dashType?: any; + width?: any; + } + + interface ChartSeriesItemTargetLine { + width?: any; + } + + interface ChartSeriesItemTarget { + border?: ChartSeriesItemTargetBorder; + color?: any; + line?: ChartSeriesItemTargetLine; + } + + interface ChartSeriesItemTooltipBorder { + color?: string; + width?: number; + } + + interface ChartSeriesItemTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesItemTooltip { + background?: string; + border?: ChartSeriesItemTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: ChartSeriesItemTooltipPadding; + template?: any; + visible?: boolean; + } + + interface ChartSeriesItem { + aggregate?: any; + axis?: string; + border?: ChartSeriesItemBorder; + categoryField?: string; + closeField?: string; + color?: any; + colorField?: string; + connectors?: ChartSeriesItemConnectors; + currentField?: string; + dashType?: string; + data?: any; + downColor?: any; + downColorField?: string; + segmentSpacing?: number; + summaryField?: string; + neckRatio?: number; + dynamicSlope?: boolean; + dynamicHeight?: boolean; + errorBars?: ChartSeriesItemErrorBars; + errorLowField?: string; + errorHighField?: string; + xErrorLowField?: string; + xErrorHighField?: string; + yErrorLowField?: string; + yErrorHighField?: string; + explodeField?: string; + field?: string; + fromField?: string; + toField?: string; + noteTextField?: string; + lowerField?: string; + q1Field?: string; + medianField?: string; + q3Field?: string; + upperField?: string; + meanField?: string; + outliersField?: string; + gap?: number; + highField?: string; + highlight?: ChartSeriesItemHighlight; + holeSize?: number; + labels?: ChartSeriesItemLabels; + line?: ChartSeriesItemLine; + lowField?: string; + margin?: ChartSeriesItemMargin; + markers?: ChartSeriesItemMarkers; + outliers?: ChartSeriesItemOutliers; + extremes?: ChartSeriesItemExtremes; + maxSize?: number; + minSize?: number; + missingValues?: string; + style?: string; + name?: string; + negativeColor?: string; + negativeValues?: ChartSeriesItemNegativeValues; + opacity?: number; + openField?: string; + overlay?: ChartSeriesItemOverlay; + padding?: number; + size?: number; + sizeField?: string; + spacing?: number; + stack?: ChartSeriesItemStack; + startAngle?: number; + target?: ChartSeriesItemTarget; + targetField?: string; + tooltip?: ChartSeriesItemTooltip; + type?: string; + visible?: boolean; + visibleInLegend?: boolean; + visibleInLegendField?: string; + visual?: Function; + width?: number; + xAxis?: string; + xField?: string; + yAxis?: string; + yField?: string; + notes?: ChartSeriesItemNotes; + zIndex?: number; + } + + interface ChartSeriesDefaultsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartSeriesDefaultsLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartSeriesDefaultsLabelsFromBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartSeriesDefaultsLabelsFromMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesDefaultsLabelsFromPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesDefaultsLabelsFrom { + background?: string; + border?: ChartSeriesDefaultsLabelsFromBorder; + color?: string; + font?: string; + format?: string; + margin?: ChartSeriesDefaultsLabelsFromMargin; + padding?: ChartSeriesDefaultsLabelsFromPadding; + template?: any; + visible?: boolean; + } + + interface ChartSeriesDefaultsLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesDefaultsLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesDefaultsLabelsToBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartSeriesDefaultsLabelsToMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesDefaultsLabelsToPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesDefaultsLabelsTo { + background?: string; + border?: ChartSeriesDefaultsLabelsToBorder; + color?: string; + font?: string; + format?: string; + margin?: ChartSeriesDefaultsLabelsToMargin; + padding?: ChartSeriesDefaultsLabelsToPadding; + template?: any; + visible?: boolean; + } + + interface ChartSeriesDefaultsLabels { + background?: string; + border?: ChartSeriesDefaultsLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: ChartSeriesDefaultsLabelsMargin; + padding?: ChartSeriesDefaultsLabelsPadding; + template?: any; + visible?: boolean; + visual?: Function; + from?: ChartSeriesDefaultsLabelsFrom; + to?: ChartSeriesDefaultsLabelsTo; + } + + interface ChartSeriesDefaultsNotesIconBorder { + color?: string; + width?: number; + } + + interface ChartSeriesDefaultsNotesIcon { + background?: string; + border?: ChartSeriesDefaultsNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartSeriesDefaultsNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartSeriesDefaultsNotesLabel { + background?: string; + border?: ChartSeriesDefaultsNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface ChartSeriesDefaultsNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartSeriesDefaultsNotes { + icon?: ChartSeriesDefaultsNotesIcon; + label?: ChartSeriesDefaultsNotesLabel; + line?: ChartSeriesDefaultsNotesLine; + visual?: Function; + } + + interface ChartSeriesDefaultsOverlay { + gradient?: string; + } + + interface ChartSeriesDefaultsStack { + type?: string; + } + + interface ChartSeriesDefaultsTooltipBorder { + color?: string; + width?: number; + } + + interface ChartSeriesDefaultsTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartSeriesDefaultsTooltip { + background?: string; + border?: ChartSeriesDefaultsTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: ChartSeriesDefaultsTooltipPadding; + template?: any; + visible?: boolean; + } + + interface ChartSeriesDefaults { + area?: any; + bar?: any; + border?: ChartSeriesDefaultsBorder; + bubble?: any; + candlestick?: any; + column?: any; + donut?: any; + gap?: number; + labels?: ChartSeriesDefaultsLabels; + line?: any; + ohlc?: any; + overlay?: ChartSeriesDefaultsOverlay; + pie?: any; + scatter?: any; + scatterLine?: any; + spacing?: number; + stack?: ChartSeriesDefaultsStack; + type?: string; + tooltip?: ChartSeriesDefaultsTooltip; + verticalArea?: any; + verticalLine?: any; + visual?: Function; + notes?: ChartSeriesDefaultsNotes; + } + + interface ChartTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartTitlePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartTitle { + align?: string; + background?: string; + border?: ChartTitleBorder; + color?: string; + font?: string; + margin?: ChartTitleMargin; + padding?: ChartTitlePadding; + position?: string; + text?: string; + visible?: boolean; + } + + interface ChartTooltipBorder { + color?: string; + width?: number; + } + + interface ChartTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartTooltip { + background?: string; + border?: ChartTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: ChartTooltipPadding; + shared?: boolean; + sharedTemplate?: any; + template?: any; + visible?: boolean; + } + + interface ChartValueAxisItemCrosshairTooltipBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartValueAxisItemCrosshairTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartValueAxisItemCrosshairTooltip { + background?: string; + border?: ChartValueAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: ChartValueAxisItemCrosshairTooltipPadding; + template?: any; + visible?: boolean; + } + + interface ChartValueAxisItemCrosshair { + color?: string; + opacity?: number; + tooltip?: ChartValueAxisItemCrosshairTooltip; + visible?: boolean; + width?: number; + } + + interface ChartValueAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartValueAxisItemLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartValueAxisItemLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartValueAxisItemLabels { + background?: string; + border?: ChartValueAxisItemLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: ChartValueAxisItemLabelsMargin; + mirror?: boolean; + padding?: ChartValueAxisItemLabelsPadding; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + visual?: Function; + } + + interface ChartValueAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface ChartValueAxisItemMajorGridLines { + color?: string; + dashType?: string; + type?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartValueAxisItemMajorTicks { + color?: string; + size?: number; + visible?: boolean; + step?: number; + skip?: number; + } + + interface ChartValueAxisItemMinorGridLines { + color?: string; + dashType?: string; + type?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartValueAxisItemMinorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartValueAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface ChartValueAxisItemNotesDataItemIcon { + background?: string; + border?: ChartValueAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartValueAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartValueAxisItemNotesDataItemLabel { + background?: string; + border?: ChartValueAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface ChartValueAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartValueAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: ChartValueAxisItemNotesDataItemIcon; + label?: ChartValueAxisItemNotesDataItemLabel; + line?: ChartValueAxisItemNotesDataItemLine; + } + + interface ChartValueAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface ChartValueAxisItemNotesIcon { + background?: string; + border?: ChartValueAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartValueAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartValueAxisItemNotesLabel { + background?: string; + border?: ChartValueAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface ChartValueAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartValueAxisItemNotes { + position?: string; + icon?: ChartValueAxisItemNotesIcon; + label?: ChartValueAxisItemNotesLabel; + line?: ChartValueAxisItemNotesLine; + data?: ChartValueAxisItemNotesDataItem[]; + visual?: Function; + } + + interface ChartValueAxisItemPlotBand { + color?: string; + from?: number; + opacity?: number; + to?: number; + } + + interface ChartValueAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartValueAxisItemTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartValueAxisItemTitlePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartValueAxisItemTitle { + background?: string; + border?: ChartValueAxisItemTitleBorder; + color?: string; + font?: string; + margin?: ChartValueAxisItemTitleMargin; + padding?: ChartValueAxisItemTitlePadding; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + visual?: Function; + } + + interface ChartValueAxisItem { + axisCrossingValue?: any; + background?: string; + color?: string; + crosshair?: ChartValueAxisItemCrosshair; + labels?: ChartValueAxisItemLabels; + line?: ChartValueAxisItemLine; + majorGridLines?: ChartValueAxisItemMajorGridLines; + majorUnit?: number; + max?: number; + min?: number; + minorGridLines?: ChartValueAxisItemMinorGridLines; + majorTicks?: ChartValueAxisItemMajorTicks; + minorTicks?: ChartValueAxisItemMinorTicks; + minorUnit?: number; + name?: any; + narrowRange?: boolean; + pane?: string; + plotBands?: ChartValueAxisItemPlotBand[]; + reverse?: boolean; + title?: ChartValueAxisItemTitle; + type?: string; + visible?: boolean; + notes?: ChartValueAxisItemNotes; + } + + interface ChartXAxisItemCrosshairTooltipBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartXAxisItemCrosshairTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartXAxisItemCrosshairTooltip { + background?: string; + border?: ChartXAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: ChartXAxisItemCrosshairTooltipPadding; + template?: any; + visible?: boolean; + } + + interface ChartXAxisItemCrosshair { + color?: string; + opacity?: number; + tooltip?: ChartXAxisItemCrosshairTooltip; + visible?: boolean; + width?: number; + } + + interface ChartXAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartXAxisItemLabelsDateFormats { + days?: string; + hours?: string; + months?: string; + weeks?: string; + years?: string; + } + + interface ChartXAxisItemLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartXAxisItemLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartXAxisItemLabels { + background?: string; + border?: ChartXAxisItemLabelsBorder; + color?: string; + culture?: string; + dateFormats?: ChartXAxisItemLabelsDateFormats; + font?: string; + format?: string; + margin?: ChartXAxisItemLabelsMargin; + mirror?: boolean; + padding?: ChartXAxisItemLabelsPadding; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + visual?: Function; + } + + interface ChartXAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface ChartXAxisItemMajorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartXAxisItemMajorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartXAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartXAxisItemMinorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartXAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface ChartXAxisItemNotesDataItemIcon { + background?: string; + border?: ChartXAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartXAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartXAxisItemNotesDataItemLabel { + background?: string; + border?: ChartXAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface ChartXAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartXAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: ChartXAxisItemNotesDataItemIcon; + label?: ChartXAxisItemNotesDataItemLabel; + line?: ChartXAxisItemNotesDataItemLine; + } + + interface ChartXAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface ChartXAxisItemNotesIcon { + background?: string; + border?: ChartXAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartXAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartXAxisItemNotesLabel { + background?: string; + border?: ChartXAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface ChartXAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartXAxisItemNotes { + position?: string; + icon?: ChartXAxisItemNotesIcon; + label?: ChartXAxisItemNotesLabel; + line?: ChartXAxisItemNotesLine; + data?: ChartXAxisItemNotesDataItem[]; + visual?: Function; + } + + interface ChartXAxisItemPlotBand { + color?: string; + from?: number; + opacity?: number; + to?: number; + } + + interface ChartXAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartXAxisItemTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartXAxisItemTitlePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartXAxisItemTitle { + background?: string; + border?: ChartXAxisItemTitleBorder; + color?: string; + font?: string; + margin?: ChartXAxisItemTitleMargin; + padding?: ChartXAxisItemTitlePadding; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + visual?: Function; + } + + interface ChartXAxisItem { + axisCrossingValue?: any; + background?: string; + baseUnit?: string; + color?: string; + crosshair?: ChartXAxisItemCrosshair; + labels?: ChartXAxisItemLabels; + line?: ChartXAxisItemLine; + majorGridLines?: ChartXAxisItemMajorGridLines; + minorGridLines?: ChartXAxisItemMinorGridLines; + minorTicks?: ChartXAxisItemMinorTicks; + majorTicks?: ChartXAxisItemMajorTicks; + majorUnit?: number; + max?: any; + min?: any; + minorUnit?: number; + name?: any; + narrowRange?: boolean; + pane?: string; + plotBands?: ChartXAxisItemPlotBand[]; + reverse?: boolean; + startAngle?: number; + title?: ChartXAxisItemTitle; + type?: string; + visible?: boolean; + notes?: ChartXAxisItemNotes; + } + + interface ChartYAxisItemCrosshairTooltipBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartYAxisItemCrosshairTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartYAxisItemCrosshairTooltip { + background?: string; + border?: ChartYAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: ChartYAxisItemCrosshairTooltipPadding; + template?: any; + visible?: boolean; + } + + interface ChartYAxisItemCrosshair { + color?: string; + opacity?: number; + tooltip?: ChartYAxisItemCrosshairTooltip; + visible?: boolean; + width?: number; + } + + interface ChartYAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartYAxisItemLabelsDateFormats { + days?: string; + hours?: string; + months?: string; + weeks?: string; + years?: string; + } + + interface ChartYAxisItemLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartYAxisItemLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartYAxisItemLabels { + background?: string; + border?: ChartYAxisItemLabelsBorder; + color?: string; + culture?: string; + dateFormats?: ChartYAxisItemLabelsDateFormats; + font?: string; + format?: string; + margin?: ChartYAxisItemLabelsMargin; + mirror?: boolean; + padding?: ChartYAxisItemLabelsPadding; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + visual?: Function; + } + + interface ChartYAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface ChartYAxisItemMajorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartYAxisItemMajorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartYAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartYAxisItemMinorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface ChartYAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface ChartYAxisItemNotesDataItemIcon { + background?: string; + border?: ChartYAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartYAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartYAxisItemNotesDataItemLabel { + background?: string; + border?: ChartYAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface ChartYAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartYAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: ChartYAxisItemNotesDataItemIcon; + label?: ChartYAxisItemNotesDataItemLabel; + line?: ChartYAxisItemNotesDataItemLine; + } + + interface ChartYAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface ChartYAxisItemNotesIcon { + background?: string; + border?: ChartYAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface ChartYAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartYAxisItemNotesLabel { + background?: string; + border?: ChartYAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface ChartYAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface ChartYAxisItemNotes { + position?: string; + icon?: ChartYAxisItemNotesIcon; + label?: ChartYAxisItemNotesLabel; + line?: ChartYAxisItemNotesLine; + data?: ChartYAxisItemNotesDataItem[]; + visual?: Function; + } + + interface ChartYAxisItemPlotBand { + color?: string; + from?: number; + opacity?: number; + to?: number; + } + + interface ChartYAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface ChartYAxisItemTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartYAxisItemTitlePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface ChartYAxisItemTitle { + background?: string; + border?: ChartYAxisItemTitleBorder; + color?: string; + font?: string; + margin?: ChartYAxisItemTitleMargin; + padding?: ChartYAxisItemTitlePadding; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + visual?: Function; + } + + interface ChartYAxisItem { + axisCrossingValue?: any; + background?: string; + baseUnit?: string; + color?: string; + crosshair?: ChartYAxisItemCrosshair; + labels?: ChartYAxisItemLabels; + line?: ChartYAxisItemLine; + majorGridLines?: ChartYAxisItemMajorGridLines; + minorGridLines?: ChartYAxisItemMinorGridLines; + minorTicks?: ChartYAxisItemMinorTicks; + majorTicks?: ChartYAxisItemMajorTicks; + majorUnit?: number; + max?: any; + min?: any; + minorUnit?: number; + name?: any; + narrowRange?: boolean; + pane?: string; + plotBands?: ChartYAxisItemPlotBand[]; + reverse?: boolean; + title?: ChartYAxisItemTitle; + type?: string; + visible?: boolean; + notes?: ChartYAxisItemNotes; + } + + interface ChartExportImageOptions { + width?: string; + height?: string; + } + + interface ChartExportSVGOptions { + raw?: boolean; + } + + interface ChartToggleHighlightOptions { + series?: string; + category?: string; + } + + interface ChartSeriesClickEventSeries { + type?: any; + name?: any; + data?: any; + } + + interface ChartSeriesHoverEventSeries { + type?: any; + name?: any; + data?: any; + } + + interface ChartOptions { + name?: string; + autoBind?: boolean; + axisDefaults?: any; + categoryAxis?: ChartCategoryAxisItem[]; + chartArea?: ChartChartArea; + dataSource?: any; + legend?: ChartLegend; + panes?: ChartPane[]; + pdf?: ChartPdf; + plotArea?: ChartPlotArea; + renderAs?: string; + series?: ChartSeriesItem[]; + seriesColors?: any; + seriesDefaults?: ChartSeriesDefaults; + theme?: string; + title?: ChartTitle; + tooltip?: ChartTooltip; + transitions?: boolean; + valueAxis?: ChartValueAxisItem[]; + xAxis?: ChartXAxisItem[]; + yAxis?: ChartYAxisItem[]; + axisLabelClick?(e: ChartAxisLabelClickEvent): void; + legendItemClick?(e: ChartLegendItemClickEvent): void; + legendItemHover?(e: ChartLegendItemHoverEvent): void; + dataBound?(e: ChartDataBoundEvent): void; + drag?(e: ChartDragEvent): void; + dragEnd?(e: ChartDragEndEvent): void; + dragStart?(e: ChartDragStartEvent): void; + noteClick?(e: ChartNoteClickEvent): void; + noteHover?(e: ChartNoteHoverEvent): void; + plotAreaClick?(e: ChartPlotAreaClickEvent): void; + render?(e: ChartEvent): void; + select?(e: ChartSelectEvent): void; + selectEnd?(e: ChartSelectEndEvent): void; + selectStart?(e: ChartSelectStartEvent): void; + seriesClick?(e: ChartSeriesClickEvent): void; + seriesHover?(e: ChartSeriesHoverEvent): void; + zoom?(e: ChartZoomEvent): void; + zoomEnd?(e: ChartZoomEndEvent): void; + zoomStart?(e: ChartZoomStartEvent): void; + } + interface ChartEvent { + sender: Chart; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ChartAxisLabelClickEvent extends ChartEvent { + axis?: any; + dataItem?: any; + element?: any; + index?: any; + text?: string; + value?: any; + } + + interface ChartLegendItemClickEvent extends ChartEvent { + text?: string; + series?: any; + seriesIndex?: number; + pointIndex?: number; + element?: any; + } + + interface ChartLegendItemHoverEvent extends ChartEvent { + text?: string; + series?: any; + seriesIndex?: number; + pointIndex?: number; + element?: any; + } + + interface ChartDataBoundEvent extends ChartEvent { + } + + interface ChartDragEvent extends ChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface ChartDragEndEvent extends ChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface ChartDragStartEvent extends ChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface ChartNoteClickEvent extends ChartEvent { + category?: any; + element?: any; + value?: any; + series?: any; + dataItem?: any; + } + + interface ChartNoteHoverEvent extends ChartEvent { + category?: any; + element?: any; + value?: any; + series?: any; + dataItem?: any; + } + + interface ChartPlotAreaClickEvent extends ChartEvent { + category?: any; + element?: any; + originalEvent?: any; + value?: any; + x?: any; + y?: any; + } + + interface ChartSelectEvent extends ChartEvent { + axis?: any; + from?: any; + to?: any; + } + + interface ChartSelectEndEvent extends ChartEvent { + axis?: any; + from?: any; + to?: any; + } + + interface ChartSelectStartEvent extends ChartEvent { + axis?: any; + from?: any; + to?: any; + } + + interface ChartSeriesClickEvent extends ChartEvent { + category?: any; + element?: any; + originalEvent?: any; + series?: ChartSeriesClickEventSeries; + dataItem?: any; + value?: any; + percentage?: any; + } + + interface ChartSeriesHoverEvent extends ChartEvent { + category?: any; + categoryPoints?: any; + element?: any; + originalEvent?: any; + series?: ChartSeriesHoverEventSeries; + dataItem?: any; + value?: any; + percentage?: any; + } + + interface ChartZoomEvent extends ChartEvent { + axisRanges?: any; + delta?: number; + originalEvent?: any; + } + + interface ChartZoomEndEvent extends ChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface ChartZoomStartEvent extends ChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + + class Diagram extends kendo.ui.Widget { + static fn: Diagram; + static extend(proto: Object): Diagram; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: DiagramOptions); + options: DiagramOptions; + dataSource: kendo.data.DataSource; + addConnection(connection: any, undoable: boolean): void; + addShape(obj: any, undoable: boolean): kendo.dataviz.diagram.Shape; + alignShapes(direction: string): void; + boundingBox(items: any): kendo.dataviz.diagram.Rect; + bringIntoView(obj: any, options: any): void; + cancelEdit(): void; + clear(): void; + connect(source: any, target: any, options: any): void; + connected(source: any, target: any): void; + copy(): void; + createConnection(item: any): void; + createShape(item: any): void; + cut(): void; + destroy(): void; + documentToModel(point: any): any; + documentToView(point: any): any; + edit(item: any): void; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + focus(): void; + getShapeById(id: string): any; + layerToModel(point: any): any; + layout(options: any): void; + load(json: string): void; + modelToDocument(point: any): any; + modelToLayer(point: any): any; + modelToView(point: any): any; + pan(pan: any): void; + paste(): void; + redo(): void; + remove(items: any, undoable: boolean): void; + resize(): void; + save(): void; + saveEdit(): void; + select(): any; + select(elements: kendo.dataviz.diagram.Connection, options: any): void; + select(elements: kendo.dataviz.diagram.Shape, options: any): void; + select(elements: any, options: any): void; + selectAll(): void; + selectArea(rect: kendo.dataviz.diagram.Rect): void; + setConnectionsDataSource(dataSource: kendo.data.DataSource): void; + setDataSource(dataSource: kendo.data.DataSource): void; + toBack(items: any, undoable: boolean): void; + toFront(items: any, undoable: boolean): void; + transformPoint(p: any): void; + transformRect(r: any): void; + undo(): void; + viewToDocument(point: any): any; + viewToModel(point: any): any; + viewport(): void; + zoom(zoom: number, point: any): void; + } + + interface DiagramConnectionDefaultsContent { + template?: any; + text?: string; + } + + interface DiagramConnectionDefaultsEditableTool { + name?: string; + } + + interface DiagramConnectionDefaultsEditable { + tools?: DiagramConnectionDefaultsEditableTool[]; + } + + interface DiagramConnectionDefaultsEndCapFill { + color?: string; + } + + interface DiagramConnectionDefaultsEndCapStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramConnectionDefaultsEndCap { + fill?: DiagramConnectionDefaultsEndCapFill; + stroke?: DiagramConnectionDefaultsEndCapStroke; + type?: string; + } + + interface DiagramConnectionDefaultsHoverStroke { + color?: string; + } + + interface DiagramConnectionDefaultsHover { + stroke?: DiagramConnectionDefaultsHoverStroke; + } + + interface DiagramConnectionDefaultsSelectionHandlesFill { + color?: string; + } + + interface DiagramConnectionDefaultsSelectionHandlesStroke { + color?: string; + } + + interface DiagramConnectionDefaultsSelectionHandles { + fill?: DiagramConnectionDefaultsSelectionHandlesFill; + stroke?: DiagramConnectionDefaultsSelectionHandlesStroke; + } + + interface DiagramConnectionDefaultsSelection { + handles?: DiagramConnectionDefaultsSelectionHandles; + } + + interface DiagramConnectionDefaultsStartCapFill { + color?: string; + } + + interface DiagramConnectionDefaultsStartCapStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramConnectionDefaultsStartCap { + fill?: DiagramConnectionDefaultsStartCapFill; + stroke?: DiagramConnectionDefaultsStartCapStroke; + type?: string; + } + + interface DiagramConnectionDefaultsStroke { + color?: string; + width?: number; + } + + interface DiagramConnectionDefaults { + content?: DiagramConnectionDefaultsContent; + editable?: DiagramConnectionDefaultsEditable; + endCap?: DiagramConnectionDefaultsEndCap; + hover?: DiagramConnectionDefaultsHover; + selectable?: boolean; + selection?: DiagramConnectionDefaultsSelection; + startCap?: DiagramConnectionDefaultsStartCap; + stroke?: DiagramConnectionDefaultsStroke; + } + + interface DiagramConnectionContent { + template?: any; + text?: string; + } + + interface DiagramConnectionEditableTool { + name?: string; + } + + interface DiagramConnectionEditable { + tools?: DiagramConnectionEditableTool[]; + } + + interface DiagramConnectionEndCapFill { + color?: string; + } + + interface DiagramConnectionEndCapStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramConnectionEndCap { + fill?: DiagramConnectionEndCapFill; + stroke?: DiagramConnectionEndCapStroke; + type?: string; + } + + interface DiagramConnectionFrom { + x?: number; + y?: number; + } + + interface DiagramConnectionHoverStroke { + color?: string; + } + + interface DiagramConnectionHover { + stroke?: DiagramConnectionHoverStroke; + } + + interface DiagramConnectionPoint { + x?: number; + y?: number; + } + + interface DiagramConnectionSelectionHandlesFill { + color?: string; + } + + interface DiagramConnectionSelectionHandlesStroke { + color?: string; + } + + interface DiagramConnectionSelectionHandles { + fill?: DiagramConnectionSelectionHandlesFill; + stroke?: DiagramConnectionSelectionHandlesStroke; + } + + interface DiagramConnectionSelection { + handles?: DiagramConnectionSelectionHandles; + } + + interface DiagramConnectionStartCapFill { + color?: string; + } + + interface DiagramConnectionStartCapStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramConnectionStartCap { + fill?: DiagramConnectionStartCapFill; + stroke?: DiagramConnectionStartCapStroke; + type?: string; + } + + interface DiagramConnectionStroke { + color?: string; + width?: number; + } + + interface DiagramConnectionTo { + x?: number; + y?: number; + } + + interface DiagramConnection { + content?: DiagramConnectionContent; + editable?: DiagramConnectionEditable; + endCap?: DiagramConnectionEndCap; + from?: DiagramConnectionFrom; + hover?: DiagramConnectionHover; + points?: DiagramConnectionPoint[]; + selection?: DiagramConnectionSelection; + startCap?: DiagramConnectionStartCap; + stroke?: DiagramConnectionStroke; + to?: DiagramConnectionTo; + } + + interface DiagramEditableResizeHandlesFill { + color?: string; + opacity?: number; + } + + interface DiagramEditableResizeHandlesHoverFill { + color?: string; + opacity?: number; + } + + interface DiagramEditableResizeHandlesHoverStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramEditableResizeHandlesHover { + fill?: DiagramEditableResizeHandlesHoverFill; + stroke?: DiagramEditableResizeHandlesHoverStroke; + } + + interface DiagramEditableResizeHandlesStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramEditableResizeHandles { + fill?: DiagramEditableResizeHandlesFill; + height?: number; + hover?: DiagramEditableResizeHandlesHover; + stroke?: DiagramEditableResizeHandlesStroke; + width?: number; + } + + interface DiagramEditableResize { + handles?: DiagramEditableResizeHandles; + } + + interface DiagramEditableRotateFill { + color?: string; + opacity?: number; + } + + interface DiagramEditableRotateStroke { + color?: string; + width?: number; + } + + interface DiagramEditableRotate { + fill?: DiagramEditableRotateFill; + stroke?: DiagramEditableRotateStroke; + } + + interface DiagramEditableTool { + name?: string; + step?: number; + } + + interface DiagramEditable { + connectionTemplate?: any; + resize?: DiagramEditableResize; + rotate?: DiagramEditableRotate; + shapeTemplate?: any; + tools?: DiagramEditableTool[]; + } + + interface DiagramLayoutGrid { + componentSpacingX?: number; + componentSpacingY?: number; + offsetX?: number; + offsetY?: number; + width?: number; + } + + interface DiagramLayout { + endRadialAngle?: number; + grid?: DiagramLayoutGrid; + horizontalSeparation?: number; + iterations?: number; + layerSeparation?: number; + nodeDistance?: number; + radialFirstLevelSeparation?: number; + radialSeparation?: number; + startRadialAngle?: number; + subtype?: string; + type?: string; + underneathHorizontalOffset?: number; + underneathVerticalSeparation?: number; + underneathVerticalTopOffset?: number; + verticalSeparation?: number; + } + + interface DiagramPannable { + key?: string; + } + + interface DiagramPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface DiagramPdf { + author?: string; + creator?: string; + date?: Date; + fileName?: string; + forceProxy?: boolean; + keywords?: string; + landscape?: boolean; + margin?: DiagramPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface DiagramSelectableStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramSelectable { + key?: string; + stroke?: DiagramSelectableStroke; + } + + interface DiagramShapeDefaultsConnector { + name?: string; + position?: any; + } + + interface DiagramShapeDefaultsContent { + align?: string; + color?: string; + fontFamily?: string; + fontSize?: number; + template?: any; + text?: string; + } + + interface DiagramShapeDefaultsEditableTool { + name?: string; + step?: number; + } + + interface DiagramShapeDefaultsEditable { + connect?: boolean; + tools?: DiagramShapeDefaultsEditableTool[]; + } + + interface DiagramShapeDefaultsFill { + color?: string; + opacity?: number; + } + + interface DiagramShapeDefaultsHoverFill { + color?: string; + opacity?: number; + } + + interface DiagramShapeDefaultsHover { + fill?: DiagramShapeDefaultsHoverFill; + } + + interface DiagramShapeDefaultsRotation { + angle?: number; + } + + interface DiagramShapeDefaultsStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramShapeDefaults { + connectors?: DiagramShapeDefaultsConnector[]; + content?: DiagramShapeDefaultsContent; + editable?: DiagramShapeDefaultsEditable; + fill?: DiagramShapeDefaultsFill; + height?: number; + hover?: DiagramShapeDefaultsHover; + minHeight?: number; + minWidth?: number; + path?: string; + rotation?: DiagramShapeDefaultsRotation; + selectable?: boolean; + source?: string; + stroke?: DiagramShapeDefaultsStroke; + type?: string; + visual?: Function; + width?: number; + x?: number; + y?: number; + } + + interface DiagramShapeConnector { + description?: string; + name?: string; + position?: any; + } + + interface DiagramShapeContent { + align?: string; + color?: string; + fontFamily?: string; + fontSize?: number; + template?: any; + text?: string; + } + + interface DiagramShapeEditableTool { + name?: string; + step?: number; + } + + interface DiagramShapeEditable { + connect?: boolean; + tools?: DiagramShapeEditableTool[]; + } + + interface DiagramShapeFill { + color?: string; + opacity?: number; + } + + interface DiagramShapeHoverFill { + color?: string; + opacity?: number; + } + + interface DiagramShapeHover { + fill?: DiagramShapeHoverFill; + } + + interface DiagramShapeRotation { + angle?: number; + } + + interface DiagramShapeStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface DiagramShape { + connectors?: DiagramShapeConnector[]; + content?: DiagramShapeContent; + editable?: DiagramShapeEditable; + fill?: DiagramShapeFill; + height?: number; + hover?: DiagramShapeHover; + id?: string; + minHeight?: number; + minWidth?: number; + path?: string; + rotation?: DiagramShapeRotation; + source?: string; + stroke?: DiagramShapeStroke; + type?: string; + visual?: Function; + width?: number; + x?: number; + y?: number; + } + + interface DiagramExportImageOptions { + width?: string; + height?: string; + } + + interface DiagramExportSVGOptions { + raw?: boolean; + } + + interface DiagramSelectOptions { + addToSelection?: boolean; + } + + interface DiagramOptions { + name?: string; + autoBind?: boolean; + connectionDefaults?: DiagramConnectionDefaults; + connections?: DiagramConnection[]; + connectionsDataSource?: any; + dataSource?: any; + editable?: DiagramEditable; + layout?: DiagramLayout; + pannable?: DiagramPannable; + pdf?: DiagramPdf; + selectable?: DiagramSelectable; + shapeDefaults?: DiagramShapeDefaults; + shapes?: DiagramShape[]; + template?: any; + zoom?: number; + zoomMax?: number; + zoomMin?: number; + zoomRate?: number; + add?(e: DiagramAddEvent): void; + cancel?(e: DiagramCancelEvent): void; + change?(e: DiagramChangeEvent): void; + click?(e: DiagramClickEvent): void; + dataBound?(e: DiagramDataBoundEvent): void; + edit?(e: DiagramEditEvent): void; + itemBoundsChange?(e: DiagramItemBoundsChangeEvent): void; + itemRotate?(e: DiagramItemRotateEvent): void; + mouseEnter?(e: DiagramMouseEnterEvent): void; + mouseLeave?(e: DiagramMouseLeaveEvent): void; + pan?(e: DiagramPanEvent): void; + remove?(e: DiagramRemoveEvent): void; + save?(e: DiagramSaveEvent): void; + select?(e: DiagramSelectEvent): void; + zoomEnd?(e: DiagramZoomEndEvent): void; + zoomStart?(e: DiagramZoomStartEvent): void; + } + interface DiagramEvent { + sender: Diagram; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface DiagramAddEvent extends DiagramEvent { + connection?: kendo.dataviz.diagram.Connection; + shape?: kendo.dataviz.diagram.Shape; + } + + interface DiagramCancelEvent extends DiagramEvent { + container?: JQuery; + connection?: kendo.data.Model; + shape?: kendo.data.Model; + } + + interface DiagramChangeEvent extends DiagramEvent { + added?: any; + removed?: any; + } + + interface DiagramClickEvent extends DiagramEvent { + item?: any; + point?: kendo.dataviz.diagram.Point; + } + + interface DiagramDataBoundEvent extends DiagramEvent { + } + + interface DiagramEditEvent extends DiagramEvent { + container?: JQuery; + connection?: kendo.data.Model; + shape?: kendo.data.Model; + } + + interface DiagramItemBoundsChangeEvent extends DiagramEvent { + bounds?: kendo.dataviz.diagram.Rect; + item?: any; + } + + interface DiagramItemRotateEvent extends DiagramEvent { + item?: any; + } + + interface DiagramMouseEnterEvent extends DiagramEvent { + item?: any; + } + + interface DiagramMouseLeaveEvent extends DiagramEvent { + item?: any; + } + + interface DiagramPanEvent extends DiagramEvent { + } + + interface DiagramRemoveEvent extends DiagramEvent { + connection?: kendo.dataviz.diagram.Connection; + shape?: kendo.dataviz.diagram.Shape; + } + + interface DiagramSaveEvent extends DiagramEvent { + container?: JQuery; + connection?: kendo.data.Model; + shape?: kendo.data.Model; + } + + interface DiagramSelectEvent extends DiagramEvent { + selected?: any; + deselected?: any; + } + + interface DiagramZoomEndEvent extends DiagramEvent { + point?: kendo.dataviz.diagram.Point; + zoom?: number; + } + + interface DiagramZoomStartEvent extends DiagramEvent { + point?: kendo.dataviz.diagram.Point; + zoom?: number; + } + + + class LinearGauge extends kendo.ui.Widget { + static fn: LinearGauge; + static extend(proto: Object): LinearGauge; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: LinearGaugeOptions); + options: LinearGaugeOptions; + allValues(values: any): any; + destroy(): void; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + redraw(): void; + resize(force?: boolean): void; + svg(): void; + imageDataURL(): string; + value(): void; + } + + interface LinearGaugeGaugeAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface LinearGaugeGaugeArea { + background?: any; + border?: LinearGaugeGaugeAreaBorder; + height?: number; + margin?: any; + width?: number; + } + + interface LinearGaugePointerItemBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface LinearGaugePointerItemTrackBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface LinearGaugePointerItemTrack { + border?: LinearGaugePointerItemTrackBorder; + color?: string; + opacity?: number; + size?: number; + visible?: boolean; + } + + interface LinearGaugePointerItem { + border?: LinearGaugePointerItemBorder; + color?: string; + margin?: any; + opacity?: number; + shape?: string; + size?: number; + track?: LinearGaugePointerItemTrack; + value?: number; + } + + interface LinearGaugeScaleLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface LinearGaugeScaleLabels { + background?: string; + border?: LinearGaugeScaleLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + padding?: any; + template?: any; + visible?: boolean; + } + + interface LinearGaugeScaleLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface LinearGaugeScaleMajorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + } + + interface LinearGaugeScaleMinorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + } + + interface LinearGaugeScaleRange { + from?: number; + to?: number; + opacity?: number; + color?: string; + } + + interface LinearGaugeScale { + line?: LinearGaugeScaleLine; + labels?: LinearGaugeScaleLabels; + majorTicks?: LinearGaugeScaleMajorTicks; + majorUnit?: number; + max?: number; + min?: number; + minorTicks?: LinearGaugeScaleMinorTicks; + minorUnit?: number; + mirror?: boolean; + ranges?: LinearGaugeScaleRange[]; + rangePlaceholderColor?: string; + rangeSize?: number; + reverse?: boolean; + vertical?: boolean; + } + + interface LinearGaugeExportImageOptions { + width?: string; + height?: string; + } + + interface LinearGaugeExportSVGOptions { + raw?: boolean; + } + + interface LinearGaugeOptions { + name?: string; + gaugeArea?: LinearGaugeGaugeArea; + pointer?: LinearGaugePointerItem[]; + renderAs?: string; + scale?: LinearGaugeScale; + transitions?: boolean; + } + interface LinearGaugeEvent { + sender: LinearGauge; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Map extends kendo.ui.Widget { + static fn: Map; + static extend(proto: Object): Map; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: MapOptions); + options: MapOptions; + center(): kendo.dataviz.map.Location; + center(center: any): void; + center(center: kendo.dataviz.map.Location): void; + destroy(): void; + eventOffset(e: any): kendo.geometry.Point; + eventOffset(e: JQueryEventObject): kendo.geometry.Point; + eventToLayer(e: any): kendo.geometry.Point; + eventToLayer(e: JQueryEventObject): kendo.geometry.Point; + eventToLocation(e: any): kendo.geometry.Point; + eventToLocation(e: JQueryEventObject): kendo.geometry.Point; + eventToView(e: any): kendo.geometry.Point; + eventToView(e: JQueryEventObject): kendo.geometry.Point; + extent(): kendo.dataviz.map.Extent; + extent(extent: kendo.dataviz.map.Extent): void; + layerToLocation(point: any, zoom: number): kendo.dataviz.map.Location; + layerToLocation(point: kendo.geometry.Point, zoom: number): kendo.dataviz.map.Location; + locationToLayer(location: any, zoom: number): kendo.geometry.Point; + locationToLayer(location: kendo.dataviz.map.Location, zoom: number): kendo.geometry.Point; + locationToView(location: any): kendo.geometry.Point; + locationToView(location: kendo.dataviz.map.Location): kendo.geometry.Point; + resize(force?: boolean): void; + setOptions(options: any): void; + viewSize(): any; + viewToLocation(point: any, zoom: number): kendo.dataviz.map.Location; + viewToLocation(point: kendo.geometry.Point, zoom: number): kendo.dataviz.map.Location; + zoom(): number; + zoom(level: number): void; + layers: any; + } + + interface MapControlsAttribution { + position?: string; + } + + interface MapControlsNavigator { + position?: string; + } + + interface MapControlsZoom { + position?: string; + } + + interface MapControls { + attribution?: MapControlsAttribution; + navigator?: MapControlsNavigator; + zoom?: MapControlsZoom; + } + + interface MapLayerDefaultsBing { + attribution?: string; + opacity?: number; + key?: string; + imagerySet?: string; + } + + interface MapLayerDefaultsBubbleStyleFill { + color?: string; + opacity?: number; + } + + interface MapLayerDefaultsBubbleStyleStroke { + color?: string; + dashType?: string; + opacity?: number; + width?: number; + } + + interface MapLayerDefaultsBubbleStyle { + fill?: MapLayerDefaultsBubbleStyleFill; + stroke?: MapLayerDefaultsBubbleStyleStroke; + } + + interface MapLayerDefaultsBubble { + attribution?: string; + opacity?: number; + maxSize?: number; + minSize?: number; + style?: MapLayerDefaultsBubbleStyle; + symbol?: any; + } + + interface MapLayerDefaultsMarkerTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface MapLayerDefaultsMarkerTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface MapLayerDefaultsMarkerTooltipAnimation { + close?: MapLayerDefaultsMarkerTooltipAnimationClose; + open?: MapLayerDefaultsMarkerTooltipAnimationOpen; + } + + interface MapLayerDefaultsMarkerTooltipContent { + url?: string; + } + + interface MapLayerDefaultsMarkerTooltip { + autoHide?: boolean; + animation?: MapLayerDefaultsMarkerTooltipAnimation; + content?: MapLayerDefaultsMarkerTooltipContent; + template?: string; + callout?: boolean; + iframe?: boolean; + height?: number; + width?: number; + position?: string; + showAfter?: number; + showOn?: string; + } + + interface MapLayerDefaultsMarker { + shape?: string; + tooltip?: MapLayerDefaultsMarkerTooltip; + opacity?: number; + } + + interface MapLayerDefaultsShapeStyleFill { + color?: string; + opacity?: number; + } + + interface MapLayerDefaultsShapeStyleStroke { + color?: string; + dashType?: string; + opacity?: number; + width?: number; + } + + interface MapLayerDefaultsShapeStyle { + fill?: MapLayerDefaultsShapeStyleFill; + stroke?: MapLayerDefaultsShapeStyleStroke; + } + + interface MapLayerDefaultsShape { + attribution?: string; + opacity?: number; + style?: MapLayerDefaultsShapeStyle; + } + + interface MapLayerDefaultsTile { + urlTemplate?: string; + attribution?: string; + subdomains?: any; + opacity?: number; + } + + interface MapLayerDefaults { + marker?: MapLayerDefaultsMarker; + shape?: MapLayerDefaultsShape; + bubble?: MapLayerDefaultsBubble; + tile?: MapLayerDefaultsTile; + bing?: MapLayerDefaultsBing; + } + + interface MapLayerStyleFill { + color?: string; + opacity?: number; + } + + interface MapLayerStyleStroke { + color?: string; + dashType?: number; + opacity?: number; + width?: number; + } + + interface MapLayerStyle { + fill?: MapLayerStyleFill; + stroke?: MapLayerStyleStroke; + } + + interface MapLayerTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface MapLayerTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface MapLayerTooltipAnimation { + close?: MapLayerTooltipAnimationClose; + open?: MapLayerTooltipAnimationOpen; + } + + interface MapLayerTooltipContent { + url?: string; + } + + interface MapLayerTooltip { + autoHide?: boolean; + animation?: MapLayerTooltipAnimation; + content?: MapLayerTooltipContent; + template?: string; + callout?: boolean; + iframe?: boolean; + height?: number; + width?: number; + position?: string; + showAfter?: number; + showOn?: string; + } + + interface MapLayer { + attribution?: string; + autoBind?: boolean; + dataSource?: any; + extent?: any; + key?: string; + imagerySet?: string; + locationField?: string; + shape?: string; + titleField?: string; + tooltip?: MapLayerTooltip; + maxSize?: number; + minSize?: number; + opacity?: number; + subdomains?: any; + symbol?: any; + type?: string; + style?: MapLayerStyle; + urlTemplate?: string; + valueField?: string; + zIndex?: number; + } + + interface MapMarkerDefaultsTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface MapMarkerDefaultsTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface MapMarkerDefaultsTooltipAnimation { + close?: MapMarkerDefaultsTooltipAnimationClose; + open?: MapMarkerDefaultsTooltipAnimationOpen; + } + + interface MapMarkerDefaultsTooltipContent { + url?: string; + } + + interface MapMarkerDefaultsTooltip { + autoHide?: boolean; + animation?: MapMarkerDefaultsTooltipAnimation; + content?: MapMarkerDefaultsTooltipContent; + template?: string; + callout?: boolean; + iframe?: boolean; + height?: number; + width?: number; + position?: string; + showAfter?: number; + showOn?: string; + } + + interface MapMarkerDefaults { + shape?: string; + tooltip?: MapMarkerDefaultsTooltip; + } + + interface MapMarkerTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface MapMarkerTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface MapMarkerTooltipAnimation { + close?: MapMarkerTooltipAnimationClose; + open?: MapMarkerTooltipAnimationOpen; + } + + interface MapMarkerTooltipContent { + url?: string; + } + + interface MapMarkerTooltip { + autoHide?: boolean; + animation?: MapMarkerTooltipAnimation; + content?: MapMarkerTooltipContent; + template?: string; + callout?: boolean; + iframe?: boolean; + height?: number; + width?: number; + position?: string; + showAfter?: number; + showOn?: string; + } + + interface MapMarker { + location?: any; + shape?: string; + title?: string; + tooltip?: MapMarkerTooltip; + } + + interface MapOptions { + name?: string; + center?: any; + controls?: MapControls; + layerDefaults?: MapLayerDefaults; + layers?: MapLayer[]; + markerDefaults?: MapMarkerDefaults; + markers?: MapMarker[]; + minZoom?: number; + maxZoom?: number; + minSize?: number; + pannable?: boolean; + wraparound?: boolean; + zoom?: number; + zoomable?: boolean; + beforeReset?(e: MapBeforeResetEvent): void; + click?(e: MapClickEvent): void; + markerActivate?(e: MapMarkerActivateEvent): void; + markerCreated?(e: MapMarkerCreatedEvent): void; + markerClick?(e: MapMarkerClickEvent): void; + pan?(e: MapPanEvent): void; + panEnd?(e: MapPanEndEvent): void; + reset?(e: MapResetEvent): void; + shapeClick?(e: MapShapeClickEvent): void; + shapeCreated?(e: MapShapeCreatedEvent): void; + shapeMouseEnter?(e: MapShapeMouseEnterEvent): void; + shapeMouseLeave?(e: MapShapeMouseLeaveEvent): void; + zoomStart?(e: MapZoomStartEvent): void; + zoomEnd?(e: MapZoomEndEvent): void; + } + interface MapEvent { + sender: Map; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface MapBeforeResetEvent extends MapEvent { + } + + interface MapClickEvent extends MapEvent { + location?: kendo.dataviz.map.Location; + originalEvent?: any; + } + + interface MapMarkerActivateEvent extends MapEvent { + marker?: kendo.dataviz.map.Marker; + layer?: kendo.dataviz.map.Marker; + } + + interface MapMarkerCreatedEvent extends MapEvent { + marker?: kendo.dataviz.map.Marker; + layer?: kendo.dataviz.map.Marker; + } + + interface MapMarkerClickEvent extends MapEvent { + marker?: kendo.dataviz.map.Marker; + layer?: kendo.dataviz.map.Marker; + } + + interface MapPanEvent extends MapEvent { + origin?: kendo.dataviz.map.Location; + center?: kendo.dataviz.map.Location; + originalEvent?: any; + } + + interface MapPanEndEvent extends MapEvent { + origin?: kendo.dataviz.map.Location; + center?: kendo.dataviz.map.Location; + originalEvent?: any; + } + + interface MapResetEvent extends MapEvent { + } + + interface MapShapeClickEvent extends MapEvent { + layer?: kendo.dataviz.map.layer.Shape; + shape?: kendo.drawing.Element; + originalEvent?: any; + } + + interface MapShapeCreatedEvent extends MapEvent { + layer?: kendo.dataviz.map.layer.Shape; + shape?: kendo.drawing.Element; + originalEvent?: any; + } + + interface MapShapeMouseEnterEvent extends MapEvent { + layer?: kendo.dataviz.map.layer.Shape; + shape?: kendo.drawing.Element; + originalEvent?: any; + } + + interface MapShapeMouseLeaveEvent extends MapEvent { + layer?: kendo.dataviz.map.layer.Shape; + shape?: kendo.drawing.Element; + originalEvent?: any; + } + + interface MapZoomStartEvent extends MapEvent { + originalEvent?: any; + } + + interface MapZoomEndEvent extends MapEvent { + originalEvent?: any; + } + + + class QRCode extends kendo.ui.Widget { + static fn: QRCode; + static extend(proto: Object): QRCode; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: QRCodeOptions); + options: QRCodeOptions; + destroy(): void; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + imageDataURL(): string; + redraw(): void; + resize(force?: boolean): void; + setOptions(options: any): void; + svg(): string; + value(options: string): void; + value(options: number): void; + } + + interface QRCodeBorder { + color?: string; + width?: number; + } + + interface QRCodeExportImageOptions { + width?: string; + height?: string; + } + + interface QRCodeExportSVGOptions { + raw?: boolean; + } + + interface QRCodeOptions { + name?: string; + background?: string; + border?: QRCodeBorder; + color?: string; + encoding?: string; + errorCorrection?: string; + padding?: number; + renderAs?: string; + size?: any; + value?: any; + } + interface QRCodeEvent { + sender: QRCode; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class RadialGauge extends kendo.ui.Widget { + static fn: RadialGauge; + static extend(proto: Object): RadialGauge; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: RadialGaugeOptions); + options: RadialGaugeOptions; + allValues(values: any): any; + destroy(): void; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + redraw(): void; + resize(force?: boolean): void; + svg(): void; + imageDataURL(): string; + value(): void; + } + + interface RadialGaugeGaugeAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface RadialGaugeGaugeArea { + background?: any; + border?: RadialGaugeGaugeAreaBorder; + height?: number; + margin?: any; + width?: number; + } + + interface RadialGaugePointerItemCap { + color?: string; + size?: number; + } + + interface RadialGaugePointerItem { + cap?: RadialGaugePointerItemCap; + color?: string; + value?: number; + } + + interface RadialGaugeScaleLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface RadialGaugeScaleLabels { + background?: string; + border?: RadialGaugeScaleLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + padding?: any; + position?: string; + template?: any; + visible?: boolean; + } + + interface RadialGaugeScaleMajorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + } + + interface RadialGaugeScaleMinorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + } + + interface RadialGaugeScaleRange { + from?: number; + to?: number; + opacity?: number; + color?: string; + } + + interface RadialGaugeScale { + endAngle?: number; + labels?: RadialGaugeScaleLabels; + majorTicks?: RadialGaugeScaleMajorTicks; + majorUnit?: number; + max?: number; + min?: number; + minorTicks?: RadialGaugeScaleMinorTicks; + minorUnit?: number; + ranges?: RadialGaugeScaleRange[]; + rangePlaceholderColor?: string; + rangeSize?: number; + rangeDistance?: number; + reverse?: boolean; + startAngle?: number; + } + + interface RadialGaugeExportImageOptions { + width?: string; + height?: string; + } + + interface RadialGaugeExportSVGOptions { + raw?: boolean; + } + + interface RadialGaugeOptions { + name?: string; + gaugeArea?: RadialGaugeGaugeArea; + pointer?: RadialGaugePointerItem[]; + renderAs?: string; + scale?: RadialGaugeScale; + transitions?: boolean; + } + interface RadialGaugeEvent { + sender: RadialGauge; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Sparkline extends kendo.ui.Widget { + static fn: Sparkline; + static extend(proto: Object): Sparkline; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: SparklineOptions); + options: SparklineOptions; + dataSource: kendo.data.DataSource; + destroy(): void; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + refresh(): void; + setDataSource(dataSource: kendo.data.DataSource): void; + setOptions(options: any): void; + svg(): string; + imageDataURL(): string; + } + + interface SparklineCategoryAxisItemCrosshairTooltipBorder { + color?: string; + width?: number; + } + + interface SparklineCategoryAxisItemCrosshairTooltip { + background?: string; + border?: SparklineCategoryAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface SparklineCategoryAxisItemCrosshair { + color?: string; + width?: number; + opacity?: number; + dashType?: number; + visible?: boolean; + tooltip?: SparklineCategoryAxisItemCrosshairTooltip; + } + + interface SparklineCategoryAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineCategoryAxisItemLabels { + background?: string; + border?: SparklineCategoryAxisItemLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + mirror?: boolean; + padding?: any; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + culture?: string; + dateFormats?: any; + } + + interface SparklineCategoryAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface SparklineCategoryAxisItemMajorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface SparklineCategoryAxisItemMajorTicks { + size?: number; + visible?: boolean; + color?: string; + width?: number; + step?: number; + skip?: number; + } + + interface SparklineCategoryAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface SparklineCategoryAxisItemMinorTicks { + size?: number; + visible?: boolean; + color?: string; + width?: number; + step?: number; + skip?: number; + } + + interface SparklineCategoryAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface SparklineCategoryAxisItemNotesDataItemIcon { + background?: string; + border?: SparklineCategoryAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface SparklineCategoryAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineCategoryAxisItemNotesDataItemLabel { + background?: string; + border?: SparklineCategoryAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface SparklineCategoryAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface SparklineCategoryAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: SparklineCategoryAxisItemNotesDataItemIcon; + label?: SparklineCategoryAxisItemNotesDataItemLabel; + line?: SparklineCategoryAxisItemNotesDataItemLine; + } + + interface SparklineCategoryAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface SparklineCategoryAxisItemNotesIcon { + background?: string; + border?: SparklineCategoryAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface SparklineCategoryAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineCategoryAxisItemNotesLabel { + background?: string; + border?: SparklineCategoryAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface SparklineCategoryAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface SparklineCategoryAxisItemNotes { + position?: string; + icon?: SparklineCategoryAxisItemNotesIcon; + label?: SparklineCategoryAxisItemNotesLabel; + line?: SparklineCategoryAxisItemNotesLine; + data?: SparklineCategoryAxisItemNotesDataItem[]; + } + + interface SparklineCategoryAxisItemPlotBand { + from?: number; + to?: number; + color?: string; + opacity?: number; + } + + interface SparklineCategoryAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineCategoryAxisItemTitle { + background?: string; + border?: SparklineCategoryAxisItemTitleBorder; + color?: string; + font?: string; + margin?: any; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + } + + interface SparklineCategoryAxisItem { + axisCrossingValue?: any; + categories?: any; + color?: string; + field?: string; + justified?: boolean; + labels?: SparklineCategoryAxisItemLabels; + line?: SparklineCategoryAxisItemLine; + majorGridLines?: SparklineCategoryAxisItemMajorGridLines; + majorTicks?: SparklineCategoryAxisItemMajorTicks; + minorGridLines?: SparklineCategoryAxisItemMinorGridLines; + minorTicks?: SparklineCategoryAxisItemMinorTicks; + name?: string; + plotBands?: SparklineCategoryAxisItemPlotBand[]; + reverse?: boolean; + title?: SparklineCategoryAxisItemTitle; + type?: string; + autoBaseUnitSteps?: any; + baseUnit?: string; + baseUnitStep?: any; + max?: any; + min?: any; + roundToBaseUnit?: boolean; + weekStartDay?: number; + maxDateGroups?: number; + visible?: boolean; + crosshair?: SparklineCategoryAxisItemCrosshair; + notes?: SparklineCategoryAxisItemNotes; + } + + interface SparklineChartAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineChartArea { + background?: string; + opacity?: number; + border?: SparklineChartAreaBorder; + height?: number; + margin?: any; + width?: number; + } + + interface SparklinePlotAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklinePlotArea { + background?: string; + opacity?: number; + border?: SparklinePlotAreaBorder; + margin?: any; + } + + interface SparklineSeriesItemBorder { + color?: any; + dashType?: any; + opacity?: any; + width?: any; + } + + interface SparklineSeriesItemConnectors { + color?: string; + padding?: number; + width?: number; + } + + interface SparklineSeriesItemHighlightBorder { + width?: number; + color?: string; + opacity?: number; + } + + interface SparklineSeriesItemHighlight { + border?: SparklineSeriesItemHighlightBorder; + color?: string; + opacity?: number; + visible?: boolean; + } + + interface SparklineSeriesItemLabelsBorder { + color?: any; + dashType?: any; + width?: any; + } + + interface SparklineSeriesItemLabels { + align?: string; + background?: any; + border?: SparklineSeriesItemLabelsBorder; + color?: any; + distance?: number; + font?: any; + format?: any; + margin?: any; + padding?: any; + position?: any; + template?: any; + visible?: any; + } + + interface SparklineSeriesItemLine { + color?: string; + opacity?: number; + width?: string; + style?: string; + } + + interface SparklineSeriesItemMarkersBorder { + color?: any; + width?: any; + } + + interface SparklineSeriesItemMarkers { + background?: any; + border?: SparklineSeriesItemMarkersBorder; + size?: any; + type?: any; + visible?: any; + rotation?: any; + } + + interface SparklineSeriesItemNotesIconBorder { + color?: string; + width?: number; + } + + interface SparklineSeriesItemNotesIcon { + background?: string; + border?: SparklineSeriesItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface SparklineSeriesItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineSeriesItemNotesLabel { + background?: string; + border?: SparklineSeriesItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface SparklineSeriesItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface SparklineSeriesItemNotes { + position?: string; + icon?: SparklineSeriesItemNotesIcon; + label?: SparklineSeriesItemNotesLabel; + line?: SparklineSeriesItemNotesLine; + } + + interface SparklineSeriesItemOverlay { + gradient?: string; + } + + interface SparklineSeriesItemStack { + type?: string; + group?: string; + } + + interface SparklineSeriesItemTargetBorder { + color?: any; + dashType?: any; + width?: number; + } + + interface SparklineSeriesItemTargetLine { + width?: any; + } + + interface SparklineSeriesItemTarget { + line?: SparklineSeriesItemTargetLine; + color?: any; + border?: SparklineSeriesItemTargetBorder; + } + + interface SparklineSeriesItemTooltipBorder { + color?: string; + width?: number; + } + + interface SparklineSeriesItemTooltip { + background?: string; + border?: SparklineSeriesItemTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface SparklineSeriesItem { + type?: string; + dashType?: string; + data?: any; + explodeField?: string; + currentField?: string; + targetField?: string; + field?: string; + name?: string; + highlight?: SparklineSeriesItemHighlight; + aggregate?: any; + axis?: string; + border?: SparklineSeriesItemBorder; + categoryField?: string; + color?: any; + colorField?: string; + connectors?: SparklineSeriesItemConnectors; + gap?: number; + labels?: SparklineSeriesItemLabels; + line?: SparklineSeriesItemLine; + markers?: SparklineSeriesItemMarkers; + missingValues?: string; + style?: string; + negativeColor?: string; + opacity?: number; + overlay?: SparklineSeriesItemOverlay; + padding?: number; + size?: number; + startAngle?: number; + spacing?: number; + stack?: SparklineSeriesItemStack; + tooltip?: SparklineSeriesItemTooltip; + width?: number; + target?: SparklineSeriesItemTarget; + notes?: SparklineSeriesItemNotes; + zIndex?: number; + } + + interface SparklineSeriesDefaultsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineSeriesDefaultsLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineSeriesDefaultsLabels { + background?: string; + border?: SparklineSeriesDefaultsLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + padding?: any; + template?: any; + visible?: boolean; + } + + interface SparklineSeriesDefaultsStack { + type?: string; + } + + interface SparklineSeriesDefaultsTooltipBorder { + color?: string; + width?: number; + } + + interface SparklineSeriesDefaultsTooltip { + background?: string; + border?: SparklineSeriesDefaultsTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface SparklineSeriesDefaults { + area?: any; + bar?: any; + border?: SparklineSeriesDefaultsBorder; + column?: any; + gap?: number; + labels?: SparklineSeriesDefaultsLabels; + line?: any; + overlay?: any; + pie?: any; + spacing?: number; + stack?: SparklineSeriesDefaultsStack; + type?: string; + tooltip?: SparklineSeriesDefaultsTooltip; + } + + interface SparklineTooltipBorder { + color?: string; + width?: number; + } + + interface SparklineTooltip { + background?: string; + border?: SparklineTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + shared?: boolean; + sharedTemplate?: string; + } + + interface SparklineValueAxisItemCrosshairTooltipBorder { + color?: string; + width?: number; + } + + interface SparklineValueAxisItemCrosshairTooltip { + background?: string; + border?: SparklineValueAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface SparklineValueAxisItemCrosshair { + color?: string; + width?: number; + opacity?: number; + dashType?: number; + visible?: boolean; + tooltip?: SparklineValueAxisItemCrosshairTooltip; + } + + interface SparklineValueAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineValueAxisItemLabels { + background?: string; + border?: SparklineValueAxisItemLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + mirror?: boolean; + padding?: any; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + } + + interface SparklineValueAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface SparklineValueAxisItemMajorGridLines { + color?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface SparklineValueAxisItemMajorTicks { + size?: number; + visible?: boolean; + color?: string; + width?: number; + step?: number; + skip?: number; + } + + interface SparklineValueAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface SparklineValueAxisItemMinorTicks { + size?: number; + color?: string; + width?: number; + visible?: boolean; + step?: number; + skip?: number; + } + + interface SparklineValueAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface SparklineValueAxisItemNotesDataItemIcon { + background?: string; + border?: SparklineValueAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface SparklineValueAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineValueAxisItemNotesDataItemLabel { + background?: string; + border?: SparklineValueAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface SparklineValueAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface SparklineValueAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: SparklineValueAxisItemNotesDataItemIcon; + label?: SparklineValueAxisItemNotesDataItemLabel; + line?: SparklineValueAxisItemNotesDataItemLine; + } + + interface SparklineValueAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface SparklineValueAxisItemNotesIcon { + background?: string; + border?: SparklineValueAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface SparklineValueAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineValueAxisItemNotesLabel { + background?: string; + border?: SparklineValueAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface SparklineValueAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface SparklineValueAxisItemNotes { + position?: string; + icon?: SparklineValueAxisItemNotesIcon; + label?: SparklineValueAxisItemNotesLabel; + line?: SparklineValueAxisItemNotesLine; + data?: SparklineValueAxisItemNotesDataItem[]; + } + + interface SparklineValueAxisItemPlotBand { + from?: number; + to?: number; + color?: string; + opacity?: number; + } + + interface SparklineValueAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface SparklineValueAxisItemTitle { + background?: string; + border?: SparklineValueAxisItemTitleBorder; + color?: string; + font?: string; + margin?: any; + padding?: any; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + } + + interface SparklineValueAxisItem { + axisCrossingValue?: any; + color?: string; + labels?: SparklineValueAxisItemLabels; + line?: SparklineValueAxisItemLine; + majorGridLines?: SparklineValueAxisItemMajorGridLines; + majorTicks?: SparklineValueAxisItemMajorTicks; + majorUnit?: number; + max?: number; + min?: number; + minorGridLines?: SparklineValueAxisItemMinorGridLines; + minorTicks?: SparklineValueAxisItemMinorTicks; + minorUnit?: number; + name?: any; + narrowRange?: boolean; + plotBands?: SparklineValueAxisItemPlotBand[]; + reverse?: boolean; + title?: SparklineValueAxisItemTitle; + visible?: boolean; + crosshair?: SparklineValueAxisItemCrosshair; + notes?: SparklineValueAxisItemNotes; + } + + interface SparklineExportImageOptions { + width?: string; + height?: string; + } + + interface SparklineExportSVGOptions { + raw?: boolean; + } + + interface SparklineSeriesClickEventSeries { + type?: any; + name?: any; + data?: any; + } + + interface SparklineSeriesHoverEventSeries { + type?: any; + name?: any; + data?: any; + } + + interface SparklineOptions { + name?: string; + axisDefaults?: any; + categoryAxis?: SparklineCategoryAxisItem[]; + chartArea?: SparklineChartArea; + data?: any; + dataSource?: any; + autoBind?: boolean; + plotArea?: SparklinePlotArea; + pointWidth?: number; + renderAs?: string; + series?: SparklineSeriesItem[]; + seriesColors?: any; + seriesDefaults?: SparklineSeriesDefaults; + theme?: string; + tooltip?: SparklineTooltip; + transitions?: boolean; + type?: string; + valueAxis?: SparklineValueAxisItem[]; + axisLabelClick?(e: SparklineAxisLabelClickEvent): void; + dataBound?(e: SparklineEvent): void; + dragStart?(e: SparklineDragStartEvent): void; + drag?(e: SparklineDragEvent): void; + dragEnd?(e: SparklineDragEndEvent): void; + plotAreaClick?(e: SparklinePlotAreaClickEvent): void; + seriesClick?(e: SparklineSeriesClickEvent): void; + seriesHover?(e: SparklineSeriesHoverEvent): void; + zoomStart?(e: SparklineZoomStartEvent): void; + zoom?(e: SparklineZoomEvent): void; + zoomEnd?(e: SparklineZoomEndEvent): void; + } + interface SparklineEvent { + sender: Sparkline; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SparklineAxisLabelClickEvent extends SparklineEvent { + axis?: any; + value?: any; + text?: any; + index?: any; + dataItem?: any; + element?: any; + } + + interface SparklineDragStartEvent extends SparklineEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface SparklineDragEvent extends SparklineEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface SparklineDragEndEvent extends SparklineEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface SparklinePlotAreaClickEvent extends SparklineEvent { + value?: any; + category?: any; + element?: any; + x?: any; + y?: any; + } + + interface SparklineSeriesClickEvent extends SparklineEvent { + value?: any; + category?: any; + series?: SparklineSeriesClickEventSeries; + dataItem?: any; + element?: any; + percentage?: any; + } + + interface SparklineSeriesHoverEvent extends SparklineEvent { + value?: any; + category?: any; + series?: SparklineSeriesHoverEventSeries; + dataItem?: any; + element?: any; + percentage?: any; + } + + interface SparklineZoomStartEvent extends SparklineEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface SparklineZoomEvent extends SparklineEvent { + axisRanges?: any; + delta?: number; + originalEvent?: any; + } + + interface SparklineZoomEndEvent extends SparklineEvent { + axisRanges?: any; + originalEvent?: any; + } + + + class StockChart extends kendo.ui.Widget { + static fn: StockChart; + static extend(proto: Object): StockChart; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: StockChartOptions); + options: StockChartOptions; + dataSource: kendo.data.DataSource; + destroy(): void; + exportImage(options: any): JQueryPromise; + exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; + exportSVG(options: any): JQueryPromise; + redraw(): void; + refresh(): void; + resize(force?: boolean): void; + setDataSource(dataSource: kendo.data.DataSource): void; + svg(): string; + imageDataURL(): string; + } + + interface StockChartCategoryAxisItemAutoBaseUnitSteps { + days?: any; + hours?: any; + minutes?: any; + months?: any; + weeks?: any; + years?: any; + } + + interface StockChartCategoryAxisItemCrosshairTooltipBorder { + color?: string; + width?: number; + } + + interface StockChartCategoryAxisItemCrosshairTooltip { + background?: string; + border?: StockChartCategoryAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface StockChartCategoryAxisItemCrosshair { + color?: string; + width?: number; + opacity?: number; + dashType?: number; + visible?: boolean; + tooltip?: StockChartCategoryAxisItemCrosshairTooltip; + } + + interface StockChartCategoryAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartCategoryAxisItemLabels { + background?: string; + border?: StockChartCategoryAxisItemLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + mirror?: boolean; + padding?: any; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + culture?: string; + dateFormats?: any; + } + + interface StockChartCategoryAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface StockChartCategoryAxisItemMajorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartCategoryAxisItemMajorTicks { + color?: string; + size?: number; + width?: number; + visible?: boolean; + step?: number; + skip?: number; + } + + interface StockChartCategoryAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartCategoryAxisItemMinorTicks { + size?: number; + visible?: boolean; + color?: string; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartCategoryAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface StockChartCategoryAxisItemNotesDataItemIcon { + background?: string; + border?: StockChartCategoryAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartCategoryAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartCategoryAxisItemNotesDataItemLabel { + background?: string; + border?: StockChartCategoryAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface StockChartCategoryAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface StockChartCategoryAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: StockChartCategoryAxisItemNotesDataItemIcon; + label?: StockChartCategoryAxisItemNotesDataItemLabel; + line?: StockChartCategoryAxisItemNotesDataItemLine; + } + + interface StockChartCategoryAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface StockChartCategoryAxisItemNotesIcon { + background?: string; + border?: StockChartCategoryAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartCategoryAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartCategoryAxisItemNotesLabel { + background?: string; + border?: StockChartCategoryAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface StockChartCategoryAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface StockChartCategoryAxisItemNotes { + position?: string; + icon?: StockChartCategoryAxisItemNotesIcon; + label?: StockChartCategoryAxisItemNotesLabel; + line?: StockChartCategoryAxisItemNotesLine; + data?: StockChartCategoryAxisItemNotesDataItem[]; + } + + interface StockChartCategoryAxisItemPlotBand { + from?: number; + to?: number; + color?: string; + opacity?: number; + } + + interface StockChartCategoryAxisItemSelectMousewheel { + reverse?: boolean; + zoom?: string; + } + + interface StockChartCategoryAxisItemSelect { + from?: any; + to?: any; + min?: any; + max?: any; + mousewheel?: StockChartCategoryAxisItemSelectMousewheel; + } + + interface StockChartCategoryAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartCategoryAxisItemTitle { + background?: string; + border?: StockChartCategoryAxisItemTitleBorder; + color?: string; + font?: string; + margin?: any; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + } + + interface StockChartCategoryAxisItem { + axisCrossingValue?: any; + categories?: any; + color?: string; + field?: string; + justified?: boolean; + labels?: StockChartCategoryAxisItemLabels; + line?: StockChartCategoryAxisItemLine; + majorGridLines?: StockChartCategoryAxisItemMajorGridLines; + majorTicks?: StockChartCategoryAxisItemMajorTicks; + minorGridLines?: StockChartCategoryAxisItemMinorGridLines; + minorTicks?: StockChartCategoryAxisItemMinorTicks; + name?: string; + pane?: string; + plotBands?: StockChartCategoryAxisItemPlotBand[]; + reverse?: boolean; + select?: StockChartCategoryAxisItemSelect; + title?: StockChartCategoryAxisItemTitle; + type?: string; + autoBaseUnitSteps?: StockChartCategoryAxisItemAutoBaseUnitSteps; + background?: string; + baseUnit?: string; + baseUnitStep?: any; + max?: any; + min?: any; + roundToBaseUnit?: boolean; + weekStartDay?: number; + maxDateGroups?: number; + visible?: boolean; + crosshair?: StockChartCategoryAxisItemCrosshair; + notes?: StockChartCategoryAxisItemNotes; + } + + interface StockChartChartAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartChartArea { + background?: string; + opacity?: number; + border?: StockChartChartAreaBorder; + height?: number; + margin?: any; + width?: number; + } + + interface StockChartLegendBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartLegendInactiveItemsLabels { + color?: string; + font?: string; + template?: string; + } + + interface StockChartLegendInactiveItemsMarkers { + color?: string; + } + + interface StockChartLegendInactiveItems { + labels?: StockChartLegendInactiveItemsLabels; + markers?: StockChartLegendInactiveItemsMarkers; + } + + interface StockChartLegendLabels { + color?: string; + font?: string; + template?: string; + } + + interface StockChartLegend { + background?: string; + border?: StockChartLegendBorder; + labels?: StockChartLegendLabels; + margin?: any; + offsetX?: number; + offsetY?: number; + padding?: any; + position?: string; + reverse?: boolean; + visible?: boolean; + inactiveItems?: StockChartLegendInactiveItems; + } + + interface StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps { + seconds?: any; + minutes?: any; + hours?: any; + days?: any; + weeks?: any; + months?: any; + years?: any; + } + + interface StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorCategoryAxisItemCrosshairTooltip { + background?: string; + border?: StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding; + template?: any; + visible?: boolean; + } + + interface StockChartNavigatorCategoryAxisItemCrosshair { + color?: string; + opacity?: number; + tooltip?: StockChartNavigatorCategoryAxisItemCrosshairTooltip; + visible?: boolean; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemLabelsDateFormats { + days?: string; + hours?: string; + months?: string; + weeks?: string; + years?: string; + } + + interface StockChartNavigatorCategoryAxisItemLabelsMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorCategoryAxisItemLabelsPadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorCategoryAxisItemLabels { + background?: string; + border?: StockChartNavigatorCategoryAxisItemLabelsBorder; + color?: string; + culture?: string; + dateFormats?: StockChartNavigatorCategoryAxisItemLabelsDateFormats; + font?: string; + format?: string; + margin?: StockChartNavigatorCategoryAxisItemLabelsMargin; + mirror?: boolean; + padding?: StockChartNavigatorCategoryAxisItemLabelsPadding; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + } + + interface StockChartNavigatorCategoryAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemMajorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartNavigatorCategoryAxisItemMajorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartNavigatorCategoryAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartNavigatorCategoryAxisItemMinorTicks { + color?: string; + size?: number; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemNotesDataItemIcon { + background?: string; + border?: StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemNotesDataItemLabel { + background?: string; + border?: StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface StockChartNavigatorCategoryAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface StockChartNavigatorCategoryAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: StockChartNavigatorCategoryAxisItemNotesDataItemIcon; + label?: StockChartNavigatorCategoryAxisItemNotesDataItemLabel; + line?: StockChartNavigatorCategoryAxisItemNotesDataItemLine; + } + + interface StockChartNavigatorCategoryAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemNotesIcon { + background?: string; + border?: StockChartNavigatorCategoryAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartNavigatorCategoryAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemNotesLabel { + background?: string; + border?: StockChartNavigatorCategoryAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface StockChartNavigatorCategoryAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface StockChartNavigatorCategoryAxisItemNotes { + position?: string; + icon?: StockChartNavigatorCategoryAxisItemNotesIcon; + label?: StockChartNavigatorCategoryAxisItemNotesLabel; + line?: StockChartNavigatorCategoryAxisItemNotesLine; + data?: StockChartNavigatorCategoryAxisItemNotesDataItem[]; + } + + interface StockChartNavigatorCategoryAxisItemPlotBand { + color?: string; + from?: number; + opacity?: number; + to?: number; + } + + interface StockChartNavigatorCategoryAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorCategoryAxisItemTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorCategoryAxisItemTitlePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorCategoryAxisItemTitle { + background?: string; + border?: StockChartNavigatorCategoryAxisItemTitleBorder; + color?: string; + font?: string; + margin?: StockChartNavigatorCategoryAxisItemTitleMargin; + padding?: StockChartNavigatorCategoryAxisItemTitlePadding; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + } + + interface StockChartNavigatorCategoryAxisItem { + autoBaseUnitSteps?: StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps; + axisCrossingValue?: any; + background?: string; + baseUnit?: string; + baseUnitStep?: any; + categories?: any; + color?: string; + crosshair?: StockChartNavigatorCategoryAxisItemCrosshair; + field?: string; + justified?: boolean; + labels?: StockChartNavigatorCategoryAxisItemLabels; + line?: StockChartNavigatorCategoryAxisItemLine; + majorGridLines?: StockChartNavigatorCategoryAxisItemMajorGridLines; + majorTicks?: StockChartNavigatorCategoryAxisItemMajorTicks; + max?: any; + maxDateGroups?: number; + min?: any; + minorGridLines?: StockChartNavigatorCategoryAxisItemMinorGridLines; + minorTicks?: StockChartNavigatorCategoryAxisItemMinorTicks; + plotBands?: StockChartNavigatorCategoryAxisItemPlotBand[]; + reverse?: boolean; + roundToBaseUnit?: boolean; + title?: StockChartNavigatorCategoryAxisItemTitle; + visible?: boolean; + weekStartDay?: number; + notes?: StockChartNavigatorCategoryAxisItemNotes; + } + + interface StockChartNavigatorHint { + visible?: boolean; + template?: any; + format?: string; + } + + interface StockChartNavigatorPaneBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorPaneMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorPanePadding { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorPaneTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorPaneTitleMargin { + bottom?: number; + left?: number; + right?: number; + top?: number; + } + + interface StockChartNavigatorPaneTitle { + background?: string; + border?: StockChartNavigatorPaneTitleBorder; + color?: string; + font?: string; + margin?: StockChartNavigatorPaneTitleMargin; + position?: string; + text?: string; + visible?: boolean; + } + + interface StockChartNavigatorPane { + background?: string; + border?: StockChartNavigatorPaneBorder; + height?: number; + margin?: StockChartNavigatorPaneMargin; + name?: string; + padding?: StockChartNavigatorPanePadding; + title?: StockChartNavigatorPaneTitle; + } + + interface StockChartNavigatorSelect { + from?: Date; + to?: Date; + } + + interface StockChartNavigatorSeriesItemBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorSeriesItemHighlightBorder { + width?: number; + color?: string; + opacity?: number; + } + + interface StockChartNavigatorSeriesItemHighlightLine { + width?: number; + color?: string; + opacity?: number; + } + + interface StockChartNavigatorSeriesItemHighlight { + border?: StockChartNavigatorSeriesItemHighlightBorder; + color?: string; + line?: StockChartNavigatorSeriesItemHighlightLine; + opacity?: number; + visible?: boolean; + } + + interface StockChartNavigatorSeriesItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartNavigatorSeriesItemLabels { + background?: string; + border?: StockChartNavigatorSeriesItemLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + padding?: any; + position?: string; + template?: any; + visible?: boolean; + } + + interface StockChartNavigatorSeriesItemLine { + color?: string; + opacity?: number; + width?: string; + } + + interface StockChartNavigatorSeriesItemMarkersBorder { + color?: string; + width?: number; + } + + interface StockChartNavigatorSeriesItemMarkers { + background?: string; + border?: StockChartNavigatorSeriesItemMarkersBorder; + rotation?: any; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartNavigatorSeriesItemOverlay { + gradient?: string; + } + + interface StockChartNavigatorSeriesItemStack { + type?: string; + group?: string; + } + + interface StockChartNavigatorSeriesItemTooltipBorder { + color?: string; + width?: number; + } + + interface StockChartNavigatorSeriesItemTooltip { + background?: string; + border?: StockChartNavigatorSeriesItemTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface StockChartNavigatorSeriesItem { + type?: string; + dashType?: string; + data?: any; + highField?: string; + field?: string; + categoryField?: string; + name?: string; + highlight?: StockChartNavigatorSeriesItemHighlight; + aggregate?: any; + axis?: string; + border?: StockChartNavigatorSeriesItemBorder; + closeField?: string; + color?: string; + colorField?: string; + downColor?: string; + downColorField?: string; + gap?: number; + labels?: StockChartNavigatorSeriesItemLabels; + line?: StockChartNavigatorSeriesItemLine; + lowField?: string; + markers?: StockChartNavigatorSeriesItemMarkers; + missingValues?: string; + style?: string; + opacity?: number; + openField?: string; + overlay?: StockChartNavigatorSeriesItemOverlay; + spacing?: number; + stack?: StockChartNavigatorSeriesItemStack; + tooltip?: StockChartNavigatorSeriesItemTooltip; + width?: number; + } + + interface StockChartNavigator { + categoryAxis?: StockChartNavigatorCategoryAxisItem[]; + dataSource?: any; + autoBind?: boolean; + dateField?: string; + pane?: StockChartNavigatorPane; + visible?: boolean; + series?: StockChartNavigatorSeriesItem[]; + select?: StockChartNavigatorSelect; + hint?: StockChartNavigatorHint; + } + + interface StockChartPaneBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartPaneTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartPaneTitle { + background?: string; + border?: StockChartPaneTitleBorder; + color?: string; + font?: string; + margin?: any; + position?: string; + text?: string; + visible?: boolean; + } + + interface StockChartPane { + name?: string; + margin?: any; + padding?: any; + background?: string; + border?: StockChartPaneBorder; + clip?: boolean; + height?: number; + title?: StockChartPaneTitle; + } + + interface StockChartPdfMargin { + bottom?: any; + left?: any; + right?: any; + top?: any; + } + + interface StockChartPdf { + author?: string; + creator?: string; + date?: Date; + forceProxy?: boolean; + fileName?: string; + keywords?: string; + landscape?: boolean; + margin?: StockChartPdfMargin; + paperSize?: any; + proxyURL?: string; + proxyTarget?: string; + subject?: string; + title?: string; + } + + interface StockChartPlotAreaBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartPlotArea { + background?: string; + opacity?: number; + border?: StockChartPlotAreaBorder; + margin?: any; + } + + interface StockChartSeriesItemBorder { + color?: any; + dashType?: any; + opacity?: any; + width?: any; + } + + interface StockChartSeriesItemHighlightBorder { + width?: number; + color?: string; + opacity?: number; + } + + interface StockChartSeriesItemHighlightLine { + width?: number; + color?: string; + opacity?: number; + } + + interface StockChartSeriesItemHighlight { + visible?: boolean; + border?: StockChartSeriesItemHighlightBorder; + color?: string; + line?: StockChartSeriesItemHighlightLine; + opacity?: number; + } + + interface StockChartSeriesItemLabelsBorder { + color?: any; + dashType?: any; + width?: any; + } + + interface StockChartSeriesItemLabels { + background?: any; + border?: StockChartSeriesItemLabelsBorder; + color?: any; + font?: any; + format?: any; + margin?: any; + padding?: any; + position?: any; + template?: any; + visible?: any; + } + + interface StockChartSeriesItemLine { + color?: string; + opacity?: number; + width?: string; + style?: string; + } + + interface StockChartSeriesItemMarkersBorder { + color?: any; + width?: any; + } + + interface StockChartSeriesItemMarkers { + background?: any; + border?: StockChartSeriesItemMarkersBorder; + size?: any; + rotation?: any; + type?: any; + visible?: any; + } + + interface StockChartSeriesItemNotesIconBorder { + color?: string; + width?: number; + } + + interface StockChartSeriesItemNotesIcon { + background?: string; + border?: StockChartSeriesItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartSeriesItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartSeriesItemNotesLabel { + background?: string; + border?: StockChartSeriesItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface StockChartSeriesItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface StockChartSeriesItemNotes { + position?: string; + icon?: StockChartSeriesItemNotesIcon; + label?: StockChartSeriesItemNotesLabel; + line?: StockChartSeriesItemNotesLine; + } + + interface StockChartSeriesItemOverlay { + gradient?: string; + } + + interface StockChartSeriesItemStack { + type?: string; + group?: string; + } + + interface StockChartSeriesItemTargetBorder { + color?: any; + dashType?: any; + width?: any; + } + + interface StockChartSeriesItemTargetLine { + width?: any; + } + + interface StockChartSeriesItemTarget { + line?: StockChartSeriesItemTargetLine; + color?: any; + border?: StockChartSeriesItemTargetBorder; + } + + interface StockChartSeriesItemTooltipBorder { + color?: string; + width?: number; + } + + interface StockChartSeriesItemTooltip { + background?: string; + border?: StockChartSeriesItemTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface StockChartSeriesItem { + type?: string; + dashType?: string; + data?: any; + highField?: string; + field?: string; + categoryField?: string; + currentField?: string; + targetField?: string; + name?: string; + highlight?: StockChartSeriesItemHighlight; + aggregate?: any; + axis?: string; + border?: StockChartSeriesItemBorder; + closeField?: string; + color?: any; + colorField?: string; + downColor?: any; + downColorField?: string; + gap?: number; + labels?: StockChartSeriesItemLabels; + line?: StockChartSeriesItemLine; + lowField?: string; + markers?: StockChartSeriesItemMarkers; + missingValues?: string; + style?: string; + negativeColor?: string; + opacity?: number; + openField?: string; + overlay?: StockChartSeriesItemOverlay; + spacing?: number; + stack?: StockChartSeriesItemStack; + tooltip?: StockChartSeriesItemTooltip; + visibleInLegend?: boolean; + width?: number; + target?: StockChartSeriesItemTarget; + notes?: StockChartSeriesItemNotes; + zIndex?: number; + } + + interface StockChartSeriesDefaultsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartSeriesDefaultsLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartSeriesDefaultsLabels { + background?: string; + border?: StockChartSeriesDefaultsLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + padding?: any; + template?: any; + visible?: boolean; + } + + interface StockChartSeriesDefaultsStack { + type?: string; + } + + interface StockChartSeriesDefaultsTooltipBorder { + color?: string; + width?: number; + } + + interface StockChartSeriesDefaultsTooltip { + background?: string; + border?: StockChartSeriesDefaultsTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface StockChartSeriesDefaults { + area?: any; + candlestick?: any; + ohlc?: any; + border?: StockChartSeriesDefaultsBorder; + column?: any; + gap?: number; + labels?: StockChartSeriesDefaultsLabels; + line?: any; + overlay?: any; + pie?: any; + spacing?: number; + stack?: StockChartSeriesDefaultsStack; + type?: string; + tooltip?: StockChartSeriesDefaultsTooltip; + } + + interface StockChartTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartTitle { + align?: string; + background?: string; + border?: StockChartTitleBorder; + font?: string; + color?: string; + margin?: any; + padding?: any; + position?: string; + text?: string; + visible?: boolean; + } + + interface StockChartTooltipBorder { + color?: string; + width?: number; + } + + interface StockChartTooltip { + background?: string; + border?: StockChartTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + shared?: boolean; + sharedTemplate?: string; + } + + interface StockChartValueAxisItemCrosshairTooltipBorder { + color?: string; + width?: number; + } + + interface StockChartValueAxisItemCrosshairTooltip { + background?: string; + border?: StockChartValueAxisItemCrosshairTooltipBorder; + color?: string; + font?: string; + format?: string; + padding?: any; + template?: any; + visible?: boolean; + } + + interface StockChartValueAxisItemCrosshair { + color?: string; + width?: number; + opacity?: number; + dashType?: number; + visible?: boolean; + tooltip?: StockChartValueAxisItemCrosshairTooltip; + } + + interface StockChartValueAxisItemLabelsBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartValueAxisItemLabels { + background?: string; + border?: StockChartValueAxisItemLabelsBorder; + color?: string; + font?: string; + format?: string; + margin?: any; + mirror?: boolean; + padding?: any; + rotation?: number; + skip?: number; + step?: number; + template?: any; + visible?: boolean; + } + + interface StockChartValueAxisItemLine { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + } + + interface StockChartValueAxisItemMajorGridLines { + color?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartValueAxisItemMajorTicks { + size?: number; + visible?: boolean; + color?: string; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartValueAxisItemMinorGridLines { + color?: string; + dashType?: string; + visible?: boolean; + width?: number; + step?: number; + skip?: number; + } + + interface StockChartValueAxisItemMinorTicks { + size?: number; + color?: string; + width?: number; + visible?: boolean; + step?: number; + skip?: number; + } + + interface StockChartValueAxisItemNotesDataItemIconBorder { + color?: string; + width?: number; + } + + interface StockChartValueAxisItemNotesDataItemIcon { + background?: string; + border?: StockChartValueAxisItemNotesDataItemIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartValueAxisItemNotesDataItemLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartValueAxisItemNotesDataItemLabel { + background?: string; + border?: StockChartValueAxisItemNotesDataItemLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + text?: string; + position?: string; + } + + interface StockChartValueAxisItemNotesDataItemLine { + width?: number; + color?: string; + length?: number; + } + + interface StockChartValueAxisItemNotesDataItem { + value?: any; + position?: string; + icon?: StockChartValueAxisItemNotesDataItemIcon; + label?: StockChartValueAxisItemNotesDataItemLabel; + line?: StockChartValueAxisItemNotesDataItemLine; + } + + interface StockChartValueAxisItemNotesIconBorder { + color?: string; + width?: number; + } + + interface StockChartValueAxisItemNotesIcon { + background?: string; + border?: StockChartValueAxisItemNotesIconBorder; + size?: number; + type?: string; + visible?: boolean; + } + + interface StockChartValueAxisItemNotesLabelBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartValueAxisItemNotesLabel { + background?: string; + border?: StockChartValueAxisItemNotesLabelBorder; + color?: string; + font?: string; + template?: any; + visible?: boolean; + rotation?: number; + format?: string; + position?: string; + } + + interface StockChartValueAxisItemNotesLine { + width?: number; + color?: string; + length?: number; + } + + interface StockChartValueAxisItemNotes { + position?: string; + icon?: StockChartValueAxisItemNotesIcon; + label?: StockChartValueAxisItemNotesLabel; + line?: StockChartValueAxisItemNotesLine; + data?: StockChartValueAxisItemNotesDataItem[]; + } + + interface StockChartValueAxisItemPlotBand { + from?: number; + to?: number; + color?: string; + opacity?: number; + } + + interface StockChartValueAxisItemTitleBorder { + color?: string; + dashType?: string; + width?: number; + } + + interface StockChartValueAxisItemTitle { + background?: string; + border?: StockChartValueAxisItemTitleBorder; + color?: string; + font?: string; + margin?: any; + padding?: any; + position?: string; + rotation?: number; + text?: string; + visible?: boolean; + } + + interface StockChartValueAxisItem { + axisCrossingValue?: any; + background?: string; + color?: string; + labels?: StockChartValueAxisItemLabels; + line?: StockChartValueAxisItemLine; + majorGridLines?: StockChartValueAxisItemMajorGridLines; + majorTicks?: StockChartValueAxisItemMajorTicks; + majorUnit?: number; + max?: number; + min?: number; + minorGridLines?: StockChartValueAxisItemMinorGridLines; + minorTicks?: StockChartValueAxisItemMinorTicks; + minorUnit?: number; + name?: any; + narrowRange?: boolean; + pane?: string; + plotBands?: StockChartValueAxisItemPlotBand[]; + reverse?: boolean; + title?: StockChartValueAxisItemTitle; + visible?: boolean; + crosshair?: StockChartValueAxisItemCrosshair; + notes?: StockChartValueAxisItemNotes; + } + + interface StockChartExportImageOptions { + width?: string; + height?: string; + } + + interface StockChartExportSVGOptions { + raw?: boolean; + } + + interface StockChartSeriesClickEventSeries { + type?: any; + name?: any; + data?: any; + } + + interface StockChartSeriesHoverEventSeries { + type?: any; + name?: any; + data?: any; + } + + interface StockChartOptions { + name?: string; + dateField?: string; + navigator?: StockChartNavigator; + axisDefaults?: any; + categoryAxis?: StockChartCategoryAxisItem[]; + chartArea?: StockChartChartArea; + dataSource?: any; + autoBind?: boolean; + legend?: StockChartLegend; + panes?: StockChartPane[]; + pdf?: StockChartPdf; + plotArea?: StockChartPlotArea; + renderAs?: string; + series?: StockChartSeriesItem[]; + seriesColors?: any; + seriesDefaults?: StockChartSeriesDefaults; + theme?: string; + title?: StockChartTitle; + tooltip?: StockChartTooltip; + transitions?: boolean; + valueAxis?: StockChartValueAxisItem[]; + axisLabelClick?(e: StockChartAxisLabelClickEvent): void; + legendItemClick?(e: StockChartLegendItemClickEvent): void; + legendItemHover?(e: StockChartLegendItemHoverEvent): void; + dataBound?(e: StockChartEvent): void; + dragStart?(e: StockChartDragStartEvent): void; + drag?(e: StockChartDragEvent): void; + dragEnd?(e: StockChartDragEndEvent): void; + noteClick?(e: StockChartNoteClickEvent): void; + noteHover?(e: StockChartNoteHoverEvent): void; + plotAreaClick?(e: StockChartPlotAreaClickEvent): void; + render?(e: StockChartEvent): void; + seriesClick?(e: StockChartSeriesClickEvent): void; + seriesHover?(e: StockChartSeriesHoverEvent): void; + zoomStart?(e: StockChartZoomStartEvent): void; + zoom?(e: StockChartZoomEvent): void; + zoomEnd?(e: StockChartZoomEndEvent): void; + selectStart?(e: StockChartSelectStartEvent): void; + select?(e: StockChartSelectEvent): void; + selectEnd?(e: StockChartSelectEndEvent): void; + } + interface StockChartEvent { + sender: StockChart; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface StockChartAxisLabelClickEvent extends StockChartEvent { + axis?: any; + value?: any; + text?: any; + index?: any; + dataItem?: any; + element?: any; + } + + interface StockChartLegendItemClickEvent extends StockChartEvent { + text?: string; + series?: any; + seriesIndex?: number; + pointIndex?: number; + element?: any; + } + + interface StockChartLegendItemHoverEvent extends StockChartEvent { + text?: string; + series?: any; + seriesIndex?: number; + pointIndex?: number; + element?: any; + } + + interface StockChartDragStartEvent extends StockChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface StockChartDragEvent extends StockChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface StockChartDragEndEvent extends StockChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface StockChartNoteClickEvent extends StockChartEvent { + category?: any; + element?: any; + value?: any; + series?: any; + dataItem?: any; + } + + interface StockChartNoteHoverEvent extends StockChartEvent { + category?: any; + element?: any; + value?: any; + series?: any; + dataItem?: any; + } + + interface StockChartPlotAreaClickEvent extends StockChartEvent { + value?: any; + category?: any; + element?: any; + x?: any; + y?: any; + } + + interface StockChartSeriesClickEvent extends StockChartEvent { + value?: any; + category?: any; + series?: StockChartSeriesClickEventSeries; + dataItem?: any; + element?: any; + percentage?: any; + } + + interface StockChartSeriesHoverEvent extends StockChartEvent { + value?: any; + category?: any; + series?: StockChartSeriesHoverEventSeries; + dataItem?: any; + element?: any; + percentage?: any; + } + + interface StockChartZoomStartEvent extends StockChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface StockChartZoomEvent extends StockChartEvent { + axisRanges?: any; + delta?: number; + originalEvent?: any; + } + + interface StockChartZoomEndEvent extends StockChartEvent { + axisRanges?: any; + originalEvent?: any; + } + + interface StockChartSelectStartEvent extends StockChartEvent { + axis?: any; + from?: any; + to?: any; + } + + interface StockChartSelectEvent extends StockChartEvent { + axis?: any; + from?: any; + to?: any; + } + + interface StockChartSelectEndEvent extends StockChartEvent { + axis?: any; + from?: any; + to?: any; + } + + + class TreeMap extends kendo.ui.Widget { + static fn: TreeMap; + static extend(proto: Object): TreeMap; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TreeMapOptions); + options: TreeMapOptions; + dataSource: kendo.data.DataSource; + } + + interface TreeMapOptions { + name?: string; + dataSource?: any; + autoBind?: boolean; + type?: string; + theme?: string; + valueField?: string; + colorField?: string; + textField?: string; + template?: any; + colors?: any; + itemCreated?(e: TreeMapItemCreatedEvent): void; + dataBound?(e: TreeMapDataBoundEvent): void; + } + interface TreeMapEvent { + sender: TreeMap; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TreeMapItemCreatedEvent extends TreeMapEvent { + element?: any; + } + + interface TreeMapDataBoundEvent extends TreeMapEvent { + } + + +} +declare module kendo.dataviz { + class ChartAxis extends Observable { + options: ChartAxisOptions; + range(): any; + slot(from: string, to?: string): kendo.geometry.Rect; + slot(from: string, to?: number): kendo.geometry.Rect; + slot(from: string, to?: Date): kendo.geometry.Rect; + slot(from: number, to?: string): kendo.geometry.Rect; + slot(from: number, to?: number): kendo.geometry.Rect; + slot(from: number, to?: Date): kendo.geometry.Rect; + slot(from: Date, to?: string): kendo.geometry.Rect; + slot(from: Date, to?: number): kendo.geometry.Rect; + slot(from: Date, to?: Date): kendo.geometry.Rect; + } + + interface ChartAxisOptions { + name?: string; + } + interface ChartAxisEvent { + sender: ChartAxis; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} +declare module kendo.dataviz.diagram { + class Circle extends Observable { + constructor(options?: CircleOptions); + options: CircleOptions; + visible(): boolean; + visible(visible: boolean): void; + } + + interface CircleFill { + color?: string; + opacity?: number; + } + + interface CircleStroke { + color?: string; + width?: number; + } + + interface CircleOptions { + name?: string; + fill?: CircleFill; + stroke?: CircleStroke; + center?: any; + radius?: number; + } + interface CircleEvent { + sender: Circle; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Connection extends Observable { + constructor(options?: ConnectionOptions); + options: ConnectionOptions; + source(): any; + source(source: kendo.dataviz.diagram.Shape): void; + source(source: kendo.dataviz.diagram.Point): void; + source(source: kendo.dataviz.diagram.Connector): void; + sourcePoint(): kendo.dataviz.diagram.Point; + target(): any; + target(target: kendo.dataviz.diagram.Shape): void; + target(target: kendo.dataviz.diagram.Point): void; + target(target: kendo.dataviz.diagram.Connector): void; + targetPoint(): kendo.dataviz.diagram.Point; + select(value: boolean): void; + type(): void; + type(value: string): void; + points(): any; + allPoints(): any; + redraw(): void; + } + + interface ConnectionEndCapFill { + color?: string; + } + + interface ConnectionEndCapStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface ConnectionEndCap { + fill?: ConnectionEndCapFill; + stroke?: ConnectionEndCapStroke; + type?: string; + } + + interface ConnectionHoverStroke { + color?: string; + } + + interface ConnectionHover { + stroke?: ConnectionHoverStroke; + } + + interface ConnectionPoint { + x?: number; + y?: number; + } + + interface ConnectionStartCapFill { + color?: string; + } + + interface ConnectionStartCapStroke { + color?: string; + dashType?: string; + width?: number; + } + + interface ConnectionStartCap { + fill?: ConnectionStartCapFill; + stroke?: ConnectionStartCapStroke; + type?: string; + } + + interface ConnectionStroke { + color?: string; + } + + interface ConnectionOptions { + name?: string; + stroke?: ConnectionStroke; + hover?: ConnectionHover; + startCap?: ConnectionStartCap; + endCap?: ConnectionEndCap; + points?: ConnectionPoint[]; + selectable?: boolean; + } + interface ConnectionEvent { + sender: Connection; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Connector extends Observable { + constructor(options?: ConnectorOptions); + options: ConnectorOptions; + position(): kendo.dataviz.diagram.Point; + position(position: kendo.dataviz.diagram.Point): void; + } + + interface ConnectorFill { + color?: string; + opacity?: number; + } + + interface ConnectorOptions { + name?: string; + width?: number; + height?: number; + fill?: ConnectorFill; + } + interface ConnectorEvent { + sender: Connector; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Group extends Observable { + constructor(options?: GroupOptions); + options: GroupOptions; + append(element: any): void; + clear(): void; + remove(element: any): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface GroupOptions { + name?: string; + x?: number; + y?: number; + } + interface GroupEvent { + sender: Group; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Image extends Observable { + constructor(options?: ImageOptions); + options: ImageOptions; + visible(): boolean; + visible(visible: boolean): void; + } + + interface ImageOptions { + name?: string; + height?: number; + width?: number; + x?: number; + y?: number; + source?: string; + } + interface ImageEvent { + sender: Image; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Line extends Observable { + constructor(options?: LineOptions); + options: LineOptions; + visible(): boolean; + visible(visible: boolean): void; + } + + interface LineStroke { + color?: string; + width?: number; + } + + interface LineOptions { + name?: string; + stroke?: LineStroke; + from?: any; + to?: any; + } + interface LineEvent { + sender: Line; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Point extends Observable { + constructor(options?: PointOptions); + options: PointOptions; + } + + interface PointOptions { + name?: string; + x?: number; + y?: number; + } + interface PointEvent { + sender: Point; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Rect extends Observable { + constructor(options?: RectOptions); + options: RectOptions; + } + + interface RectOptions { + name?: string; + height?: number; + width?: number; + x?: number; + y?: number; + } + interface RectEvent { + sender: Rect; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Rectangle extends Observable { + constructor(options?: RectangleOptions); + options: RectangleOptions; + visible(): boolean; + visible(visible: boolean): void; + } + + interface RectangleFill { + color?: string; + opacity?: number; + } + + interface RectangleStroke { + color?: string; + width?: number; + } + + interface RectangleOptions { + name?: string; + fill?: RectangleFill; + height?: number; + stroke?: RectangleStroke; + width?: number; + x?: number; + y?: number; + } + interface RectangleEvent { + sender: Rectangle; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Shape extends Observable { + constructor(options?: ShapeOptions); + options: ShapeOptions; + position(): void; + position(point: kendo.dataviz.diagram.Point): void; + clone(): kendo.dataviz.diagram.Shape; + select(value: boolean): void; + connections(type: string): void; + getConnector(): void; + getPosition(side: string): void; + redraw(): void; + } + + interface ShapeConnector { + name?: string; + description?: string; + position?: Function; + } + + interface ShapeContent { + text?: string; + align?: string; + } + + interface ShapeEditable { + connect?: boolean; + } + + interface ShapeFill { + color?: string; + opacity?: number; + } + + interface ShapeHoverFill { + color?: string; + opacity?: number; + } + + interface ShapeHover { + fill?: ShapeHoverFill; + } + + interface ShapeRotation { + angle?: number; + } + + interface ShapeStroke { + color?: string; + width?: number; + dashType?: string; + } + + interface ShapeOptions { + name?: string; + id?: string; + editable?: ShapeEditable; + path?: string; + stroke?: ShapeStroke; + type?: string; + x?: number; + y?: number; + minWidth?: number; + minHeight?: number; + width?: number; + height?: number; + fill?: ShapeFill; + hover?: ShapeHover; + connectors?: ShapeConnector[]; + rotation?: ShapeRotation; + content?: ShapeContent; + selectable?: boolean; + visual?: Function; + } + interface ShapeEvent { + sender: Shape; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class TextBlock extends Observable { + constructor(options?: TextBlockOptions); + options: TextBlockOptions; + content(): string; + content(content: string): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface TextBlockOptions { + name?: string; + color?: string; + fontFamily?: string; + fontSize?: number; + height?: number; + text?: string; + width?: number; + x?: number; + y?: number; + } + interface TextBlockEvent { + sender: TextBlock; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} +declare module kendo { + class Color extends Observable { + options: ColorOptions; + diff(): number; + equals(): boolean; + } + + interface ColorOptions { + name?: string; + } + interface ColorEvent { + sender: Color; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + module drawing { + function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void; + function drawDOM(element: HTMLElement): JQueryPromise; + function exportImage(group: kendo.drawing.Group, options: any): JQueryPromise; + function exportPDF(group: kendo.drawing.Group, options: kendo.drawing.PDFOptions): JQueryPromise; + function exportSVG(group: kendo.drawing.Group, options: any): JQueryPromise; + function fit(element: kendo.drawing.Element, rect: kendo.geometry.Rect): void; + function stack(elements: any): void; + function vAlign(elements: any, rect: kendo.geometry.Rect, alignment: string): void; + function vStack(elements: any): void; + function vWrap(elements: any, rect: kendo.geometry.Rect): any; + function wrap(elements: any, rect: kendo.geometry.Rect): any; + } + + module effects { + function box(element: HTMLElement): any; + function fillScale(firstElement: HTMLElement, secondElement: HTMLElement): number; + function fitScale(firstElement: HTMLElement, secondElement: HTMLElement): number; + function transformOrigin(firstElement: HTMLElement, secondElement: HTMLElement): any; + } + + function bind(element: string, viewModel: any, namespace?: any): void; + function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: JQuery, viewModel: any, namespace?: any): void; + function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: Element, viewModel: any, namespace?: any): void; + function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function observableHierarchy(array: any): void; + function culture(culture: string): void; + function destroy(element: string): void; + function destroy(element: JQuery): void; + function destroy(element: Element): void; + function htmlEncode(value: string): string; + function parseDate(value: string, formats?: string, culture?: string): Date; + function parseDate(value: string, formats?: any, culture?: string): Date; + function parseFloat(value: string, culture?: string): number; + function parseInt(value: string, culture?: string): number; + function parseColor(color: string, noerror: boolean): kendo.Color; + function resize(element: string, force: boolean): void; + function resize(element: JQuery, force: boolean): void; + function resize(element: Element, force: boolean): void; + function saveAs(options: any): void; + function stringify(value: any): string; + function throttle(fn: Function, timeout: number): void; + function touchScroller(element: string): void; + function touchScroller(element: JQuery): void; + function touchScroller(element: Element): void; + function toString(value: Date, format: string, culture?: string): string; + function toString(value: number, format: string, culture?: string): string; + function unbind(element: string): void; + function unbind(element: JQuery): void; + function unbind(element: Element): void; + +} +declare module kendo.dataviz.map { + class Extent extends kendo.Class { + options: ExtentOptions; + contains(location: kendo.dataviz.map.Location): boolean; + containsAny(locations: any): boolean; + center(): kendo.dataviz.map.Location; + include(location: kendo.dataviz.map.Location): void; + includeAll(locations: any): void; + edges(): any; + toArray(): any; + overlaps(extent: kendo.dataviz.map.Extent): boolean; + static create(a: kendo.dataviz.map.Location, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent; + static create(a: kendo.dataviz.map.Location, b?: any): kendo.dataviz.map.Extent; + static create(a: any, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent; + static create(a: any, b?: any): kendo.dataviz.map.Extent; + nw: kendo.dataviz.map.Location; + se: kendo.dataviz.map.Location; + } + + interface ExtentOptions { + name?: string; + } + interface ExtentEvent { + sender: Extent; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Layer extends kendo.Class { + options: LayerOptions; + show(): void; + hide(): void; + map: kendo.dataviz.ui.Map; + } + + interface LayerOptions { + name?: string; + } + interface LayerEvent { + sender: Layer; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Location extends kendo.Class { + options: LocationOptions; + clone(): kendo.dataviz.map.Location; + destination(destination: kendo.dataviz.map.Location): number; + distanceTo(distance: number, bearing: number): kendo.dataviz.map.Location; + equals(location: kendo.dataviz.map.Location): boolean; + round(digits: number): kendo.dataviz.map.Location; + toArray(): any; + toString(): string; + wrap(): kendo.dataviz.map.Location; + static create(lat: number, lng?: number): kendo.dataviz.map.Location; + static create(lat: any, lng?: number): kendo.dataviz.map.Location; + static create(lat: kendo.dataviz.map.Location, lng?: number): kendo.dataviz.map.Location; + static fromLngLat(lnglat: any): kendo.dataviz.map.Location; + static fromLatLng(lnglat: any): kendo.dataviz.map.Location; + lat: number; + lng: number; + } + + interface LocationOptions { + name?: string; + } + interface LocationEvent { + sender: Location; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} +declare module kendo.mobile.ui { + class ActionSheet extends kendo.mobile.ui.Widget { + static fn: ActionSheet; + static extend(proto: Object): ActionSheet; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ActionSheetOptions); + options: ActionSheetOptions; + close(): void; + destroy(): void; + open(target: JQuery, context: any): void; + } + + interface ActionSheetPopup { + direction?: any; + height?: any; + width?: any; + } + + interface ActionSheetOptions { + name?: string; + cancel?: string; + popup?: ActionSheetPopup; + type?: string; + close?(e: ActionSheetEvent): void; + open?(e: ActionSheetOpenEvent): void; + } + interface ActionSheetEvent { + sender: ActionSheet; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ActionSheetOpenEvent extends ActionSheetEvent { + target?: JQuery; + context?: JQuery; + } + + + class BackButton extends kendo.mobile.ui.Widget { + static fn: BackButton; + static extend(proto: Object): BackButton; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: BackButtonOptions); + options: BackButtonOptions; + destroy(): void; + } + + interface BackButtonOptions { + name?: string; + click?(e: BackButtonClickEvent): void; + } + interface BackButtonEvent { + sender: BackButton; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface BackButtonClickEvent extends BackButtonEvent { + target?: JQuery; + button?: JQuery; + } + + + class Button extends kendo.mobile.ui.Widget { + static fn: Button; + static extend(proto: Object): Button; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ButtonOptions); + options: ButtonOptions; + badge(value: string): string; + badge(value: boolean): string; + destroy(): void; + enable(enable: boolean): void; + } + + interface ButtonOptions { + name?: string; + badge?: string; + clickOn?: string; + enable?: boolean; + icon?: string; + click?(e: ButtonClickEvent): void; + } + interface ButtonEvent { + sender: Button; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ButtonClickEvent extends ButtonEvent { + target?: JQuery; + button?: JQuery; + } + + + class ButtonGroup extends kendo.mobile.ui.Widget { + static fn: ButtonGroup; + static extend(proto: Object): ButtonGroup; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ButtonGroupOptions); + options: ButtonGroupOptions; + badge(button: string, value: string): string; + badge(button: string, value: boolean): string; + badge(button: number, value: string): string; + badge(button: number, value: boolean): string; + current(): JQuery; + destroy(): void; + enable(enable: boolean): void; + select(li: JQuery): void; + select(li: number): void; + } + + interface ButtonGroupOptions { + name?: string; + enable?: boolean; + index?: number; + selectOn?: string; + select?(e: ButtonGroupSelectEvent): void; + } + interface ButtonGroupEvent { + sender: ButtonGroup; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ButtonGroupSelectEvent extends ButtonGroupEvent { + index?: number; + } + + + class Collapsible extends kendo.mobile.ui.Widget { + static fn: Collapsible; + static extend(proto: Object): Collapsible; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: CollapsibleOptions); + options: CollapsibleOptions; + collapse(instant: boolean): void; + destroy(): void; + expand(instant?: boolean): void; + resize(): void; + toggle(instant?: boolean): void; + } + + interface CollapsibleOptions { + name?: string; + animation?: boolean; + collapsed?: boolean; + expandIcon?: string; + iconPosition?: string; + inset?: boolean; + collapse?(e: CollapsibleEvent): void; + expand?(e: CollapsibleEvent): void; + } + interface CollapsibleEvent { + sender: Collapsible; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class DetailButton extends kendo.mobile.ui.Widget { + static fn: DetailButton; + static extend(proto: Object): DetailButton; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: DetailButtonOptions); + options: DetailButtonOptions; + destroy(): void; + } + + interface DetailButtonOptions { + name?: string; + click?(e: DetailButtonClickEvent): void; + } + interface DetailButtonEvent { + sender: DetailButton; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface DetailButtonClickEvent extends DetailButtonEvent { + target?: JQuery; + button?: JQuery; + } + + + class Drawer extends kendo.mobile.ui.Widget { + static fn: Drawer; + static extend(proto: Object): Drawer; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: DrawerOptions); + options: DrawerOptions; + destroy(): void; + hide(): void; + show(): void; + } + + interface DrawerOptions { + name?: string; + container?: JQuery; + position?: string; + swipeToOpen?: boolean; + swipeToOpenViews?: any; + title?: string; + views?: any; + afterHide?(e: DrawerAfterHideEvent): void; + beforeShow?(e: DrawerEvent): void; + hide?(e: DrawerHideEvent): void; + init?(e: DrawerInitEvent): void; + show?(e: DrawerShowEvent): void; + } + interface DrawerEvent { + sender: Drawer; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface DrawerAfterHideEvent extends DrawerEvent { + } + + interface DrawerHideEvent extends DrawerEvent { + } + + interface DrawerInitEvent extends DrawerEvent { + } + + interface DrawerShowEvent extends DrawerEvent { + } + + + class Layout extends kendo.mobile.ui.Widget { + static fn: Layout; + static extend(proto: Object): Layout; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: LayoutOptions); + options: LayoutOptions; + } + + interface LayoutOptions { + name?: string; + id?: string; + platform?: string; + hide?(e: LayoutHideEvent): void; + init?(e: LayoutInitEvent): void; + show?(e: LayoutShowEvent): void; + } + interface LayoutEvent { + sender: Layout; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface LayoutHideEvent extends LayoutEvent { + layout?: JQuery; + view?: JQuery; + } + + interface LayoutInitEvent extends LayoutEvent { + layout?: JQuery; + } + + interface LayoutShowEvent extends LayoutEvent { + layout?: JQuery; + view?: JQuery; + } + + + class ListView extends kendo.mobile.ui.Widget { + static fn: ListView; + static extend(proto: Object): ListView; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ListViewOptions); + options: ListViewOptions; + dataSource: kendo.data.DataSource; + append(dataItems: any): void; + prepend(dataItems: any): void; + replace(dataItems: any): void; + remove(dataItems: any): void; + setDataItem(item: JQuery, dataItem: kendo.data.Model): void; + destroy(): void; + items(): JQuery; + refresh(): void; + setDataSource(dataSource: kendo.data.DataSource): void; + } + + interface ListViewFilterable { + placeholder?: string; + autoFilter?: boolean; + field?: string; + ignoreCase?: boolean; + operator?: string; + } + + interface ListViewMessages { + loadMoreText?: string; + pullTemplate?: string; + refreshTemplate?: string; + releaseTemplate?: string; + } + + interface ListViewOptions { + name?: string; + appendOnRefresh?: boolean; + autoBind?: boolean; + dataSource?: any; + endlessScroll?: boolean; + fixedHeaders?: boolean; + headerTemplate?: any; + loadMore?: boolean; + messages?: ListViewMessages; + pullToRefresh?: boolean; + pullParameters?: Function; + style?: string; + template?: any; + type?: string; + filterable?: ListViewFilterable; + virtualViewSize?: number; + click?(e: ListViewClickEvent): void; + dataBound?(e: ListViewEvent): void; + dataBinding?(e: ListViewEvent): void; + itemChange?(e: ListViewEvent): void; + } + interface ListViewEvent { + sender: ListView; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ListViewClickEvent extends ListViewEvent { + item?: JQuery; + target?: JQuery; + dataItem?: any; + button?: kendo.mobile.ui.Button; + } + + + class Loader extends kendo.mobile.ui.Widget { + static fn: Loader; + static extend(proto: Object): Loader; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: LoaderOptions); + options: LoaderOptions; + hide(): void; + show(): void; + } + + interface LoaderOptions { + name?: string; + } + interface LoaderEvent { + sender: Loader; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class ModalView extends kendo.mobile.ui.Widget { + static fn: ModalView; + static extend(proto: Object): ModalView; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ModalViewOptions); + options: ModalViewOptions; + close(): void; + destroy(): void; + open(target: JQuery): void; + } + + interface ModalViewOptions { + name?: string; + height?: number; + modal?: boolean; + width?: number; + beforeOpen?(e: ModalViewBeforeOpenEvent): void; + close?(e: ModalViewCloseEvent): void; + init?(e: ModalViewInitEvent): void; + open?(e: ModalViewOpenEvent): void; + } + interface ModalViewEvent { + sender: ModalView; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ModalViewBeforeOpenEvent extends ModalViewEvent { + target?: JQuery; + } + + interface ModalViewCloseEvent extends ModalViewEvent { + } + + interface ModalViewInitEvent extends ModalViewEvent { + } + + interface ModalViewOpenEvent extends ModalViewEvent { + target?: JQuery; + } + + + class NavBar extends kendo.mobile.ui.Widget { + static fn: NavBar; + static extend(proto: Object): NavBar; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: NavBarOptions); + options: NavBarOptions; + destroy(): void; + title(value: string): void; + } + + interface NavBarOptions { + name?: string; + } + interface NavBarEvent { + sender: NavBar; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Pane extends kendo.mobile.ui.Widget { + static fn: Pane; + static extend(proto: Object): Pane; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: PaneOptions); + options: PaneOptions; + destroy(): void; + hideLoading(): void; + navigate(url: string, transition: string): void; + replace(url: string, transition: string): void; + Example(): void; + showLoading(): void; + view(): kendo.mobile.ui.View; + } + + interface PaneOptions { + name?: string; + collapsible?: boolean; + initial?: string; + layout?: string; + loading?: string; + portraitWidth?: number; + transition?: string; + navigate?(e: PaneNavigateEvent): void; + viewShow?(e: PaneViewShowEvent): void; + } + interface PaneEvent { + sender: Pane; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface PaneNavigateEvent extends PaneEvent { + url?: JQuery; + } + + interface PaneViewShowEvent extends PaneEvent { + view?: kendo.mobile.ui.View; + } + + + class PopOver extends kendo.mobile.ui.Widget { + static fn: PopOver; + static extend(proto: Object): PopOver; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: PopOverOptions); + options: PopOverOptions; + close(): void; + destroy(): void; + open(target: JQuery): void; + } + + interface PopOverPane { + initial?: string; + layout?: string; + loading?: string; + transition?: string; + } + + interface PopOverPopup { + height?: any; + width?: any; + } + + interface PopOverOptions { + name?: string; + pane?: PopOverPane; + popup?: PopOverPopup; + close?(e: PopOverCloseEvent): void; + open?(e: PopOverOpenEvent): void; + } + interface PopOverEvent { + sender: PopOver; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface PopOverCloseEvent extends PopOverEvent { + } + + interface PopOverOpenEvent extends PopOverEvent { + target?: JQuery; + } + + + class ScrollView extends kendo.mobile.ui.Widget { + static fn: ScrollView; + static extend(proto: Object): ScrollView; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ScrollViewOptions); + options: ScrollViewOptions; + dataSource: kendo.data.DataSource; + content(content: string): void; + content(content: JQuery): void; + destroy(): void; + next(): void; + prev(): void; + refresh(): void; + scrollTo(page: number, instant: boolean): void; + setDataSource(dataSource: kendo.data.DataSource): void; + value(dataItem: any): any; + } + + interface ScrollViewOptions { + name?: string; + autoBind?: boolean; + bounceVelocityThreshold?: number; + contentHeight?: any; + dataSource?: any; + duration?: number; + emptyTemplate?: string; + enablePager?: boolean; + itemsPerPage?: number; + page?: number; + pageSize?: number; + template?: string; + velocityThreshold?: number; + changing?(e: ScrollViewChangingEvent): void; + change?(e: ScrollViewChangeEvent): void; + refresh?(e: ScrollViewRefreshEvent): void; + } + interface ScrollViewEvent { + sender: ScrollView; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ScrollViewChangingEvent extends ScrollViewEvent { + currentPage?: number; + nextPage?: number; + } + + interface ScrollViewChangeEvent extends ScrollViewEvent { + page?: number; + element?: JQuery; + data?: any; + } + + interface ScrollViewRefreshEvent extends ScrollViewEvent { + pageCount?: number; + page?: number; + } + + + class Scroller extends kendo.mobile.ui.Widget { + static fn: Scroller; + static extend(proto: Object): Scroller; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ScrollerOptions); + options: ScrollerOptions; + animatedScrollTo(x: number, y: number): void; + destroy(): void; + disable(): void; + enable(): void; + height(): number; + pullHandled(): void; + reset(): void; + scrollHeight(): void; + scrollTo(x: number, y: number): void; + scrollWidth(): void; + zoomOut(): void; + } + + interface ScrollerMessages { + pullTemplate?: string; + refreshTemplate?: string; + releaseTemplate?: string; + } + + interface ScrollerOptions { + name?: string; + elastic?: boolean; + messages?: ScrollerMessages; + pullOffset?: number; + pullToRefresh?: boolean; + useNative?: boolean; + visibleScrollHints?: boolean; + zoom?: boolean; + pull?(e: ScrollerEvent): void; + resize?(e: ScrollerEvent): void; + scroll?(e: ScrollerScrollEvent): void; + } + interface ScrollerEvent { + sender: Scroller; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ScrollerScrollEvent extends ScrollerEvent { + scrollTop?: number; + scrollLeft?: number; + } + + + class SplitView extends kendo.mobile.ui.Widget { + static fn: SplitView; + static extend(proto: Object): SplitView; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: SplitViewOptions); + options: SplitViewOptions; + destroy(): void; + expandPanes(): void; + collapsePanes(): void; + } + + interface SplitViewOptions { + name?: string; + style?: string; + init?(e: SplitViewInitEvent): void; + show?(e: SplitViewShowEvent): void; + } + interface SplitViewEvent { + sender: SplitView; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SplitViewInitEvent extends SplitViewEvent { + view?: JQuery; + } + + interface SplitViewShowEvent extends SplitViewEvent { + view?: JQuery; + } + + + class Switch extends kendo.mobile.ui.Widget { + static fn: Switch; + static extend(proto: Object): Switch; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: SwitchOptions); + options: SwitchOptions; + check(): boolean; + check(check: boolean): void; + destroy(): void; + enable(enable: boolean): void; + refresh(): void; + toggle(): void; + } + + interface SwitchOptions { + name?: string; + checked?: boolean; + enable?: boolean; + offLabel?: string; + onLabel?: string; + change?(e: SwitchChangeEvent): void; + } + interface SwitchEvent { + sender: Switch; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SwitchChangeEvent extends SwitchEvent { + checked?: any; + } + + + class TabStrip extends kendo.mobile.ui.Widget { + static fn: TabStrip; + static extend(proto: Object): TabStrip; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: TabStripOptions); + options: TabStripOptions; + badge(tab: string, value: string): string; + badge(tab: string, value: boolean): string; + badge(tab: number, value: string): string; + badge(tab: number, value: boolean): string; + currentItem(): JQuery; + destroy(): void; + switchTo(url: string): void; + switchTo(url: number): void; + switchByFullUrl(url: string): void; + clear(): void; + } + + interface TabStripOptions { + name?: string; + selectedIndex?: number; + select?(e: TabStripSelectEvent): void; + } + interface TabStripEvent { + sender: TabStrip; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface TabStripSelectEvent extends TabStripEvent { + item?: JQuery; + } + + + class View extends kendo.mobile.ui.Widget { + static fn: View; + static extend(proto: Object): View; + + element: JQuery; + wrapper: JQuery; + constructor(element: Element, options?: ViewOptions); + options: ViewOptions; + contentElement(): void; + destroy(): void; + enable(enable: boolean): void; + } + + interface ViewOptions { + name?: string; + model?: string; + reload?: boolean; + scroller?: any; + stretch?: boolean; + title?: string; + useNativeScrolling?: boolean; + zoom?: boolean; + afterShow?(e: ViewAfterShowEvent): void; + beforeHide?(e: ViewBeforeHideEvent): void; + beforeShow?(e: ViewBeforeShowEvent): void; + hide?(e: ViewHideEvent): void; + init?(e: ViewInitEvent): void; + show?(e: ViewShowEvent): void; + transitionStart?(e: ViewTransitionStartEvent): void; + transitionEnd?(e: ViewTransitionEndEvent): void; + } + interface ViewEvent { + sender: View; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface ViewAfterShowEvent extends ViewEvent { + view?: kendo.mobile.ui.View; + } + + interface ViewBeforeHideEvent extends ViewEvent { + view?: kendo.mobile.ui.View; + } + + interface ViewBeforeShowEvent extends ViewEvent { + view?: kendo.mobile.ui.View; + } + + interface ViewHideEvent extends ViewEvent { + view?: kendo.mobile.ui.View; + } + + interface ViewInitEvent extends ViewEvent { + view?: kendo.mobile.ui.View; + } + + interface ViewShowEvent extends ViewEvent { + view?: kendo.mobile.ui.View; + } + + interface ViewTransitionStartEvent extends ViewEvent { + type?: string; + } + + interface ViewTransitionEndEvent extends ViewEvent { + type?: string; + } + + +} +declare module kendo.ooxml { + class Workbook extends Observable { + constructor(options?: WorkbookOptions); + options: WorkbookOptions; + toDataURL(): string; + sheets: WorkbookSheet[]; + } + + interface WorkbookSheetColumn { + autoWidth?: boolean; + width?: number; + } + + interface WorkbookSheetFilter { + from?: number; + to?: number; + } + + interface WorkbookSheetFreezePane { + colSplit?: number; + rowSplit?: number; + } + + interface WorkbookSheetRowCell { + background?: string; + bold?: boolean; + color?: string; + colSpan?: number; + fontName?: string; + fontSize?: number; + format?: string; + hAlign?: string; + italic?: boolean; + rowSpan?: number; + underline?: boolean; + wrap?: boolean; + vAlign?: string; + value?: any; + } + + interface WorkbookSheetRow { + cells?: WorkbookSheetRowCell[]; + } + + interface WorkbookSheet { + columns?: WorkbookSheetColumn[]; + freezePane?: WorkbookSheetFreezePane; + filter?: WorkbookSheetFilter; + rows?: WorkbookSheetRow[]; + title?: string; + } + + interface WorkbookOptions { + name?: string; + creator?: string; + date?: Date; + sheets?: WorkbookSheet[]; + } + interface WorkbookEvent { + sender: Workbook; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} + +declare module kendo.dataviz.drawing { + class Arc extends kendo.drawing.Element { + constructor(options?: ArcOptions); + options: ArcOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + geometry(): kendo.geometry.Arc; + geometry(value: kendo.geometry.Arc): void; + fill(color: string, opacity?: number): kendo.drawing.Arc; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Arc; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface ArcOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface ArcEvent { + sender: Arc; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Circle extends kendo.drawing.Element { + constructor(options?: CircleOptions); + options: CircleOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + geometry(): kendo.geometry.Circle; + geometry(value: kendo.geometry.Circle): void; + fill(color: string, opacity?: number): kendo.drawing.Circle; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Circle; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface CircleOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface CircleEvent { + sender: Circle; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Element extends kendo.Class { + constructor(options?: ElementOptions); + options: ElementOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + opacity(): number; + opacity(opacity: number): void; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface ElementOptions { + name?: string; + clip?: kendo.drawing.Path; + opacity?: number; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface ElementEvent { + sender: Element; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + interface FillOptions { + color: string; + opacity: number; + } + + + + class Gradient extends kendo.Class { + constructor(options?: GradientOptions); + options: GradientOptions; + addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop; + removeStop(stop: kendo.drawing.GradientStop): void; + stops: any; + } + + interface GradientOptions { + name?: string; + stops?: any; + } + interface GradientEvent { + sender: Gradient; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class GradientStop extends kendo.Class { + constructor(options?: GradientStopOptions); + options: GradientStopOptions; + } + + interface GradientStopOptions { + name?: string; + offset?: number; + color?: string; + opacity?: number; + } + interface GradientStopEvent { + sender: GradientStop; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Group extends kendo.drawing.Element { + constructor(options?: GroupOptions); + options: GroupOptions; + append(element: kendo.drawing.Element): void; + clear(): void; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + opacity(): number; + opacity(opacity: number): void; + remove(element: kendo.drawing.Element): void; + removeAt(index: number): void; + visible(): boolean; + visible(visible: boolean): void; + children: any; + } + + interface GroupOptions { + name?: string; + clip?: kendo.drawing.Path; + opacity?: number; + pdf?: kendo.drawing.PDFOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface GroupEvent { + sender: Group; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Image extends kendo.drawing.Element { + constructor(options?: ImageOptions); + options: ImageOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + opacity(): number; + opacity(opacity: number): void; + src(): string; + src(value: string): void; + rect(): kendo.geometry.Rect; + rect(value: kendo.geometry.Rect): void; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface ImageOptions { + name?: string; + clip?: kendo.drawing.Path; + opacity?: number; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface ImageEvent { + sender: Image; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Layout extends kendo.drawing.Group { + constructor(options?: LayoutOptions); + options: LayoutOptions; + rect(): kendo.geometry.Rect; + rect(rect: kendo.geometry.Rect): void; + reflow(): void; + } + + interface LayoutOptions { + name?: string; + alignContent?: string; + alignItems?: string; + justifyContent?: string; + lineSpacing?: number; + spacing?: number; + orientation?: string; + wrap?: boolean; + } + interface LayoutEvent { + sender: Layout; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class LinearGradient extends kendo.drawing.Gradient { + constructor(options?: LinearGradientOptions); + options: LinearGradientOptions; + addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop; + end(): kendo.geometry.Point; + end(end: any): void; + end(end: kendo.geometry.Point): void; + start(): kendo.geometry.Point; + start(start: any): void; + start(start: kendo.geometry.Point): void; + removeStop(stop: kendo.drawing.GradientStop): void; + stops: any; + } + + interface LinearGradientOptions { + name?: string; + stops?: any; + } + interface LinearGradientEvent { + sender: LinearGradient; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class MultiPath extends kendo.drawing.Element { + constructor(options?: MultiPathOptions); + options: MultiPathOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + close(): kendo.drawing.MultiPath; + curveTo(controlOut: any, controlIn: any): kendo.drawing.MultiPath; + curveTo(controlOut: any, controlIn: kendo.geometry.Point): kendo.drawing.MultiPath; + curveTo(controlOut: kendo.geometry.Point, controlIn: any): kendo.drawing.MultiPath; + curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point): kendo.drawing.MultiPath; + fill(color: string, opacity?: number): kendo.drawing.MultiPath; + lineTo(x: number, y?: number): kendo.drawing.MultiPath; + lineTo(x: any, y?: number): kendo.drawing.MultiPath; + lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath; + moveTo(x: number, y?: number): kendo.drawing.MultiPath; + moveTo(x: any, y?: number): kendo.drawing.MultiPath; + moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.MultiPath; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.MultiPath; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + paths: any; + } + + interface MultiPathOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface MultiPathEvent { + sender: MultiPath; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class OptionsStore extends kendo.Class { + options: OptionsStoreOptions; + get(field: string): any; + set(field: string, value: any): void; + observer: any; + } + + interface OptionsStoreOptions { + name?: string; + } + interface OptionsStoreEvent { + sender: OptionsStore; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + interface PDFOptions { + creator: string; + date: Date; + keywords: string; + landscape: boolean; + margin: any; + paperSize: any; + subject: string; + title: string; + } + + + + class Path extends kendo.drawing.Element { + constructor(options?: PathOptions); + options: PathOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + close(): kendo.drawing.Path; + curveTo(controlOut: any, controlIn: any): kendo.drawing.Path; + curveTo(controlOut: any, controlIn: kendo.geometry.Point): kendo.drawing.Path; + curveTo(controlOut: kendo.geometry.Point, controlIn: any): kendo.drawing.Path; + curveTo(controlOut: kendo.geometry.Point, controlIn: kendo.geometry.Point): kendo.drawing.Path; + fill(color: string, opacity?: number): kendo.drawing.Path; + lineTo(x: number, y?: number): kendo.drawing.Path; + lineTo(x: any, y?: number): kendo.drawing.Path; + lineTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path; + moveTo(x: number, y?: number): kendo.drawing.Path; + moveTo(x: any, y?: number): kendo.drawing.Path; + moveTo(x: kendo.geometry.Point, y?: number): kendo.drawing.Path; + opacity(): number; + opacity(opacity: number): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Path; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + static fromPoints(points: any): kendo.drawing.Path; + static fromRect(rect: kendo.geometry.Rect): kendo.drawing.Path; + static parse(svgPath: string, options?: any): kendo.drawing.Path; + segments: any; + } + + interface PathOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface PathEvent { + sender: Path; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class RadialGradient extends kendo.drawing.Gradient { + constructor(options?: RadialGradientOptions); + options: RadialGradientOptions; + addStop(offset: number, color: string, opacity: number): kendo.drawing.GradientStop; + center(): kendo.geometry.Point; + center(center: any): void; + center(center: kendo.geometry.Point): void; + radius(): number; + radius(value: number): void; + removeStop(stop: kendo.drawing.GradientStop): void; + stops: any; + } + + interface RadialGradientOptions { + name?: string; + center?: any; + radius?: number; + stops?: any; + } + interface RadialGradientEvent { + sender: RadialGradient; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Segment extends kendo.Class { + options: SegmentOptions; + anchor(): kendo.geometry.Point; + anchor(value: kendo.geometry.Point): void; + controlIn(): kendo.geometry.Point; + controlIn(value: kendo.geometry.Point): void; + controlOut(): kendo.geometry.Point; + controlOut(value: kendo.geometry.Point): void; + } + + interface SegmentOptions { + name?: string; + } + interface SegmentEvent { + sender: Segment; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + interface StrokeOptions { + color: string; + dashType: string; + lineCap: string; + lineJoin: string; + opacity: number; + width: number; + } + + + + class Surface extends kendo.Observable { + constructor(options?: SurfaceOptions); + options: SurfaceOptions; + clear(): void; + draw(element: kendo.drawing.Element): void; + eventTarget(e: any): kendo.drawing.Element; + resize(force?: boolean): void; + static create(element: JQuery, options?: any): kendo.drawing.Surface; + static create(element: Element, options?: any): kendo.drawing.Surface; + } + + interface SurfaceOptions { + name?: string; + type?: string; + height?: string; + width?: string; + click?(e: SurfaceClickEvent): void; + mouseenter?(e: SurfaceMouseenterEvent): void; + mouseleave?(e: SurfaceMouseleaveEvent): void; + } + interface SurfaceEvent { + sender: Surface; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + interface SurfaceClickEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + originalEvent?: any; + } + + interface SurfaceMouseenterEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + originalEvent?: any; + } + + interface SurfaceMouseleaveEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + originalEvent?: any; + } + + + class Text extends kendo.drawing.Element { + constructor(options?: TextOptions); + options: TextOptions; + bbox(): kendo.geometry.Rect; + clip(): kendo.drawing.Path; + clip(clip: kendo.drawing.Path): void; + clippedBBox(): kendo.geometry.Rect; + content(): string; + content(value: string): void; + fill(color: string, opacity?: number): kendo.drawing.Text; + opacity(): number; + opacity(opacity: number): void; + position(): kendo.geometry.Point; + position(value: kendo.geometry.Point): void; + stroke(color: string, width?: number, opacity?: number): kendo.drawing.Text; + transform(): kendo.geometry.Transformation; + transform(transform: kendo.geometry.Transformation): void; + visible(): boolean; + visible(visible: boolean): void; + } + + interface TextOptions { + name?: string; + clip?: kendo.drawing.Path; + fill?: kendo.drawing.FillOptions; + font?: string; + opacity?: number; + stroke?: kendo.drawing.StrokeOptions; + transform?: kendo.geometry.Transformation; + visible?: boolean; + } + interface TextEvent { + sender: Text; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} +declare module kendo.dataviz.geometry { + class Arc extends Observable { + options: ArcOptions; + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Circle extends Observable { + options: CircleOptions; + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + center: kendo.geometry.Point; + radius: number; + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Matrix extends Observable { + options: MatrixOptions; + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Point extends Observable { + options: PointOptions; + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + x: number; + y: number; + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Rect extends Observable { + options: RectOptions; + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; + static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Size extends Observable { + options: SizeOptions; + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + width: number; + height: number; + } + + interface SizeOptions { + name?: string; + } + interface SizeEvent { + sender: Size; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + + class Transformation extends Observable { + options: TransformationOptions; + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + isDefaultPrevented(): boolean; + preventDefault: Function; + } + + +} + +interface HTMLElement { + kendoBindingTarget: kendo.data.BindingTarget; +} + +interface JQueryXHR { +} + +interface JQueryEventObject { +} + +interface JQueryPromise { + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; + then(doneCallbacks: any, failCallbacks: any, progressCallbacks?: any): JQueryPromise; +} + +interface JQuery { + + kendoDraggable(): JQuery; + kendoDraggable(options: kendo.ui.DraggableOptions): JQuery; + + kendoDropTarget(): JQuery; + kendoDropTarget(options: kendo.ui.DropTargetOptions): JQuery; + + kendoDropTargetArea(): JQuery; + kendoDropTargetArea(options: kendo.ui.DropTargetAreaOptions): JQuery; + + data(key: any): any; + + kendoAutoComplete(): JQuery; + kendoAutoComplete(options: kendo.ui.AutoCompleteOptions): JQuery; + data(key: "kendoAutoComplete") : kendo.ui.AutoComplete; + + kendoBarcode(): JQuery; + kendoBarcode(options: kendo.dataviz.ui.BarcodeOptions): JQuery; + data(key: "kendoBarcode") : kendo.dataviz.ui.Barcode; + + kendoButton(): JQuery; + kendoButton(options: kendo.ui.ButtonOptions): JQuery; + data(key: "kendoButton") : kendo.ui.Button; + + kendoCalendar(): JQuery; + kendoCalendar(options: kendo.ui.CalendarOptions): JQuery; + data(key: "kendoCalendar") : kendo.ui.Calendar; + + kendoChart(): JQuery; + kendoChart(options: kendo.dataviz.ui.ChartOptions): JQuery; + data(key: "kendoChart") : kendo.dataviz.ui.Chart; + + kendoColorPalette(): JQuery; + kendoColorPalette(options: kendo.ui.ColorPaletteOptions): JQuery; + data(key: "kendoColorPalette") : kendo.ui.ColorPalette; + + kendoColorPicker(): JQuery; + kendoColorPicker(options: kendo.ui.ColorPickerOptions): JQuery; + data(key: "kendoColorPicker") : kendo.ui.ColorPicker; + + kendoComboBox(): JQuery; + kendoComboBox(options: kendo.ui.ComboBoxOptions): JQuery; + data(key: "kendoComboBox") : kendo.ui.ComboBox; + + kendoContextMenu(): JQuery; + kendoContextMenu(options: kendo.ui.ContextMenuOptions): JQuery; + data(key: "kendoContextMenu") : kendo.ui.ContextMenu; + + kendoDatePicker(): JQuery; + kendoDatePicker(options: kendo.ui.DatePickerOptions): JQuery; + data(key: "kendoDatePicker") : kendo.ui.DatePicker; + + kendoDateTimePicker(): JQuery; + kendoDateTimePicker(options: kendo.ui.DateTimePickerOptions): JQuery; + data(key: "kendoDateTimePicker") : kendo.ui.DateTimePicker; + + kendoDiagram(): JQuery; + kendoDiagram(options: kendo.dataviz.ui.DiagramOptions): JQuery; + data(key: "kendoDiagram") : kendo.dataviz.ui.Diagram; + + kendoDropDownList(): JQuery; + kendoDropDownList(options: kendo.ui.DropDownListOptions): JQuery; + data(key: "kendoDropDownList") : kendo.ui.DropDownList; + + kendoEditor(): JQuery; + kendoEditor(options: kendo.ui.EditorOptions): JQuery; + data(key: "kendoEditor") : kendo.ui.Editor; + + kendoFlatColorPicker(): JQuery; + kendoFlatColorPicker(options: kendo.ui.FlatColorPickerOptions): JQuery; + data(key: "kendoFlatColorPicker") : kendo.ui.FlatColorPicker; + + kendoGantt(): JQuery; + kendoGantt(options: kendo.ui.GanttOptions): JQuery; + data(key: "kendoGantt") : kendo.ui.Gantt; + + kendoGrid(): JQuery; + kendoGrid(options: kendo.ui.GridOptions): JQuery; + data(key: "kendoGrid") : kendo.ui.Grid; + + kendoLinearGauge(): JQuery; + kendoLinearGauge(options: kendo.dataviz.ui.LinearGaugeOptions): JQuery; + data(key: "kendoLinearGauge") : kendo.dataviz.ui.LinearGauge; + + kendoListView(): JQuery; + kendoListView(options: kendo.ui.ListViewOptions): JQuery; + data(key: "kendoListView") : kendo.ui.ListView; + + kendoMap(): JQuery; + kendoMap(options: kendo.dataviz.ui.MapOptions): JQuery; + data(key: "kendoMap") : kendo.dataviz.ui.Map; + + kendoMaskedTextBox(): JQuery; + kendoMaskedTextBox(options: kendo.ui.MaskedTextBoxOptions): JQuery; + data(key: "kendoMaskedTextBox") : kendo.ui.MaskedTextBox; + + kendoMenu(): JQuery; + kendoMenu(options: kendo.ui.MenuOptions): JQuery; + data(key: "kendoMenu") : kendo.ui.Menu; + + kendoMobileActionSheet(): JQuery; + kendoMobileActionSheet(options: kendo.mobile.ui.ActionSheetOptions): JQuery; + data(key: "kendoMobileActionSheet") : kendo.mobile.ui.ActionSheet; + + kendoMobileBackButton(): JQuery; + kendoMobileBackButton(options: kendo.mobile.ui.BackButtonOptions): JQuery; + data(key: "kendoMobileBackButton") : kendo.mobile.ui.BackButton; + + kendoMobileButton(): JQuery; + kendoMobileButton(options: kendo.mobile.ui.ButtonOptions): JQuery; + data(key: "kendoMobileButton") : kendo.mobile.ui.Button; + + kendoMobileButtonGroup(): JQuery; + kendoMobileButtonGroup(options: kendo.mobile.ui.ButtonGroupOptions): JQuery; + data(key: "kendoMobileButtonGroup") : kendo.mobile.ui.ButtonGroup; + + kendoMobileCollapsible(): JQuery; + kendoMobileCollapsible(options: kendo.mobile.ui.CollapsibleOptions): JQuery; + data(key: "kendoMobileCollapsible") : kendo.mobile.ui.Collapsible; + + kendoMobileDetailButton(): JQuery; + kendoMobileDetailButton(options: kendo.mobile.ui.DetailButtonOptions): JQuery; + data(key: "kendoMobileDetailButton") : kendo.mobile.ui.DetailButton; + + kendoMobileDrawer(): JQuery; + kendoMobileDrawer(options: kendo.mobile.ui.DrawerOptions): JQuery; + data(key: "kendoMobileDrawer") : kendo.mobile.ui.Drawer; + + kendoMobileLayout(): JQuery; + kendoMobileLayout(options: kendo.mobile.ui.LayoutOptions): JQuery; + data(key: "kendoMobileLayout") : kendo.mobile.ui.Layout; + + kendoMobileListView(): JQuery; + kendoMobileListView(options: kendo.mobile.ui.ListViewOptions): JQuery; + data(key: "kendoMobileListView") : kendo.mobile.ui.ListView; + + kendoMobileLoader(): JQuery; + kendoMobileLoader(options: kendo.mobile.ui.LoaderOptions): JQuery; + data(key: "kendoMobileLoader") : kendo.mobile.ui.Loader; + + kendoMobileModalView(): JQuery; + kendoMobileModalView(options: kendo.mobile.ui.ModalViewOptions): JQuery; + data(key: "kendoMobileModalView") : kendo.mobile.ui.ModalView; + + kendoMobileNavBar(): JQuery; + kendoMobileNavBar(options: kendo.mobile.ui.NavBarOptions): JQuery; + data(key: "kendoMobileNavBar") : kendo.mobile.ui.NavBar; + + kendoMobilePane(): JQuery; + kendoMobilePane(options: kendo.mobile.ui.PaneOptions): JQuery; + data(key: "kendoMobilePane") : kendo.mobile.ui.Pane; + + kendoMobilePopOver(): JQuery; + kendoMobilePopOver(options: kendo.mobile.ui.PopOverOptions): JQuery; + data(key: "kendoMobilePopOver") : kendo.mobile.ui.PopOver; + + kendoMobileScrollView(): JQuery; + kendoMobileScrollView(options: kendo.mobile.ui.ScrollViewOptions): JQuery; + data(key: "kendoMobileScrollView") : kendo.mobile.ui.ScrollView; + + kendoMobileScroller(): JQuery; + kendoMobileScroller(options: kendo.mobile.ui.ScrollerOptions): JQuery; + data(key: "kendoMobileScroller") : kendo.mobile.ui.Scroller; + + kendoMobileSplitView(): JQuery; + kendoMobileSplitView(options: kendo.mobile.ui.SplitViewOptions): JQuery; + data(key: "kendoMobileSplitView") : kendo.mobile.ui.SplitView; + + kendoMobileSwitch(): JQuery; + kendoMobileSwitch(options: kendo.mobile.ui.SwitchOptions): JQuery; + data(key: "kendoMobileSwitch") : kendo.mobile.ui.Switch; + + kendoMobileTabStrip(): JQuery; + kendoMobileTabStrip(options: kendo.mobile.ui.TabStripOptions): JQuery; + data(key: "kendoMobileTabStrip") : kendo.mobile.ui.TabStrip; + + kendoMobileView(): JQuery; + kendoMobileView(options: kendo.mobile.ui.ViewOptions): JQuery; + data(key: "kendoMobileView") : kendo.mobile.ui.View; + + kendoMultiSelect(): JQuery; + kendoMultiSelect(options: kendo.ui.MultiSelectOptions): JQuery; + data(key: "kendoMultiSelect") : kendo.ui.MultiSelect; + + kendoNotification(): JQuery; + kendoNotification(options: kendo.ui.NotificationOptions): JQuery; + data(key: "kendoNotification") : kendo.ui.Notification; + + kendoNumericTextBox(): JQuery; + kendoNumericTextBox(options: kendo.ui.NumericTextBoxOptions): JQuery; + data(key: "kendoNumericTextBox") : kendo.ui.NumericTextBox; + + kendoPager(): JQuery; + kendoPager(options: kendo.ui.PagerOptions): JQuery; + data(key: "kendoPager") : kendo.ui.Pager; + + kendoPanelBar(): JQuery; + kendoPanelBar(options: kendo.ui.PanelBarOptions): JQuery; + data(key: "kendoPanelBar") : kendo.ui.PanelBar; + + kendoPivotConfigurator(): JQuery; + kendoPivotConfigurator(options: kendo.ui.PivotConfiguratorOptions): JQuery; + data(key: "kendoPivotConfigurator") : kendo.ui.PivotConfigurator; + + kendoPivotGrid(): JQuery; + kendoPivotGrid(options: kendo.ui.PivotGridOptions): JQuery; + data(key: "kendoPivotGrid") : kendo.ui.PivotGrid; + + kendoProgressBar(): JQuery; + kendoProgressBar(options: kendo.ui.ProgressBarOptions): JQuery; + data(key: "kendoProgressBar") : kendo.ui.ProgressBar; + + kendoQRCode(): JQuery; + kendoQRCode(options: kendo.dataviz.ui.QRCodeOptions): JQuery; + data(key: "kendoQRCode") : kendo.dataviz.ui.QRCode; + + kendoRadialGauge(): JQuery; + kendoRadialGauge(options: kendo.dataviz.ui.RadialGaugeOptions): JQuery; + data(key: "kendoRadialGauge") : kendo.dataviz.ui.RadialGauge; + + kendoRangeSlider(): JQuery; + kendoRangeSlider(options: kendo.ui.RangeSliderOptions): JQuery; + data(key: "kendoRangeSlider") : kendo.ui.RangeSlider; + + kendoResponsivePanel(): JQuery; + kendoResponsivePanel(options: kendo.ui.ResponsivePanelOptions): JQuery; + data(key: "kendoResponsivePanel") : kendo.ui.ResponsivePanel; + + kendoScheduler(): JQuery; + kendoScheduler(options: kendo.ui.SchedulerOptions): JQuery; + data(key: "kendoScheduler") : kendo.ui.Scheduler; + + kendoSlider(): JQuery; + kendoSlider(options: kendo.ui.SliderOptions): JQuery; + data(key: "kendoSlider") : kendo.ui.Slider; + + kendoSortable(): JQuery; + kendoSortable(options: kendo.ui.SortableOptions): JQuery; + data(key: "kendoSortable") : kendo.ui.Sortable; + + kendoSparkline(): JQuery; + kendoSparkline(options: kendo.dataviz.ui.SparklineOptions): JQuery; + data(key: "kendoSparkline") : kendo.dataviz.ui.Sparkline; + + kendoSplitter(): JQuery; + kendoSplitter(options: kendo.ui.SplitterOptions): JQuery; + data(key: "kendoSplitter") : kendo.ui.Splitter; + + kendoStockChart(): JQuery; + kendoStockChart(options: kendo.dataviz.ui.StockChartOptions): JQuery; + data(key: "kendoStockChart") : kendo.dataviz.ui.StockChart; + + kendoTabStrip(): JQuery; + kendoTabStrip(options: kendo.ui.TabStripOptions): JQuery; + data(key: "kendoTabStrip") : kendo.ui.TabStrip; + + kendoTimePicker(): JQuery; + kendoTimePicker(options: kendo.ui.TimePickerOptions): JQuery; + data(key: "kendoTimePicker") : kendo.ui.TimePicker; + + kendoToolBar(): JQuery; + kendoToolBar(options: kendo.ui.ToolBarOptions): JQuery; + data(key: "kendoToolBar") : kendo.ui.ToolBar; + + kendoTooltip(): JQuery; + kendoTooltip(options: kendo.ui.TooltipOptions): JQuery; + data(key: "kendoTooltip") : kendo.ui.Tooltip; + + kendoTouch(): JQuery; + kendoTouch(options: kendo.ui.TouchOptions): JQuery; + data(key: "kendoTouch") : kendo.ui.Touch; + + kendoTreeList(): JQuery; + kendoTreeList(options: kendo.ui.TreeListOptions): JQuery; + data(key: "kendoTreeList") : kendo.ui.TreeList; + + kendoTreeMap(): JQuery; + kendoTreeMap(options: kendo.dataviz.ui.TreeMapOptions): JQuery; + data(key: "kendoTreeMap") : kendo.dataviz.ui.TreeMap; + + kendoTreeView(): JQuery; + kendoTreeView(options: kendo.ui.TreeViewOptions): JQuery; + data(key: "kendoTreeView") : kendo.ui.TreeView; + + kendoUpload(): JQuery; + kendoUpload(options: kendo.ui.UploadOptions): JQuery; + data(key: "kendoUpload") : kendo.ui.Upload; + + kendoValidator(): JQuery; + kendoValidator(options: kendo.ui.ValidatorOptions): JQuery; + data(key: "kendoValidator") : kendo.ui.Validator; + + kendoWindow(): JQuery; + kendoWindow(options: kendo.ui.WindowOptions): JQuery; + data(key: "kendoWindow") : kendo.ui.Window; + +} diff --git a/knockout-paging/knockout-paging-tests.ts b/knockout-paging/knockout-paging-tests.ts new file mode 100644 index 000000000..eae5490bb --- /dev/null +++ b/knockout-paging/knockout-paging-tests.ts @@ -0,0 +1,90 @@ +/// + +// Different option formats +var emptyOptions = {}; +var pageNumberOptions = { pageNumber: 2 }; +var pageSizeOptions = { pageSize: 10 }; +var generatorOptions = { pageGenerator: 'sliding' }; +var allOptions = { pageNumber: 2, pageSize: 10, pageGenerator: 'sliding' }; + +function defaults() { + ko.paging.defaults.pageNumber = 1; + ko.paging.defaults.pageSize = 50; +} + +function pageGenerators() { + + // Allow to set the windowSize on sliding page generator + ko.paging.generators['sliding'].windowSize(5); + + // Add custom page generator + ko.paging.generators['custom'] = { + generate: function(pagedObservable: KnockoutObservable) { + return [0, 1]; + } + } +} + +function usingPagedObservableArrayFunctionOnKnockoutStatic() { + var simplePaged = ko.pagedObservableArray(); + var initializedPaged = ko.pagedObservableArray([1, 2, 3]); + var emptyOptionsPaged = ko.pagedObservableArray([1, 2, 3], emptyOptions); + var pageNumberOptionsPaged = ko.pagedObservableArray([1, 2, 3], pageNumberOptions); + var pageSizeOptionsPaged = ko.pagedObservableArray([1, 2, 3], pageSizeOptions); + var generatorOptionsPaged = ko.pagedObservableArray([1, 2, 3], generatorOptions); + var allOptionsPaged = ko.pagedObservableArray([1, 2, 3], allOptions); + + // Here we verify that the returned type is the paged observable array + simplePaged.pageSize(); + initializedPaged.pageSize(); + emptyOptionsPaged.pageSize(); + pageNumberOptionsPaged.pageSize(); + pageSizeOptionsPaged.pageSize(); + generatorOptionsPaged.pageSize(); + allOptionsPaged.pageSize(); +} + +function usingExtend() { + var emptyOptionsPaged = ko.observableArray([]).extend({ paged: emptyOptions }); + var pageNumberOptionsPaged = ko.observableArray([]).extend({ paged: pageNumberOptions }); + var pageSizeOptionsPaged = ko.observableArray([]).extend({ paged: pageSizeOptions }); + var generatorOptionsPaged = ko.observableArray([]).extend({ paged: generatorOptions }); + var allOptionsPaged = ko.observableArray([]).extend({ paged: allOptions }); + var withInitialArrayValue = ko.observableArray([1, 2, 3]).extend({ paged: emptyOptions }); + + // Here we verify that the returned type is the paged observable array + emptyOptionsPaged.pageSize(); + pageNumberOptionsPaged.pageSize(); + pageSizeOptionsPaged.pageSize(); + generatorOptionsPaged.pageSize(); + allOptionsPaged.pageSize(); +} + +function observables() { + var paged = ko.pagedObservableArray([]); + var pageSize = paged.pageSize(); + var pageNumber = paged.pageNumber(); +} + +function computed() { + var paged = ko.pagedObservableArray([]); + var pageItems = paged.pageItems(); + var pageCount = paged.pageCount(); + var itemCount = paged.itemCount(); + var firstItemOnPage = paged.firstItemOnPage(); + var lastItemOnPage = paged.lastItemOnPage(); + var hasPreviousPage = paged.hasPreviousPage(); + var hasNextPage = paged.hasNextPage(); + var isFirstPage = paged.isFirstPage(); + var isLastPage = paged.isLastPage(); + var pages = paged.pages(); +} + +function functions() { + var paged = ko.pagedObservableArray([]); + paged.toNextPage(); + paged.toLastPage(); + paged.toNextPage(); + paged.toPreviousPage(); + paged.toFirstPage(); +} \ No newline at end of file diff --git a/knockout-paging/knockout-paging.d.ts b/knockout-paging/knockout-paging.d.ts new file mode 100644 index 000000000..b5f7627a6 --- /dev/null +++ b/knockout-paging/knockout-paging.d.ts @@ -0,0 +1,67 @@ +// Type definitions for knockout-paging +// Project: https://github.com/ErikSchierboom/knockout-paging +// Definitions by: Erik Schierboom +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface KnockoutStatic { + paging: KnockoutPagingOptions; + pagedObservableArray(initialValue?: T[], options?: KnockoutPagedOptions): KnockoutPagedObservableArray; +} + +interface KnockoutPagingOptions { + defaults: KnockoutPagingDefaultOptions; + generators: { + [name: string]: KnockoutPageGenerator; + 'sliding': KnockoutSlidingPageGenerator + } +} + +interface KnockoutPagingDefaultOptions { + pageNumber: number; + pageSize: number; +} + +interface KnockoutPagedObservableArray extends KnockoutObservableArray { + pageSize: KnockoutObservable; + pageNumber: KnockoutObservable; + + pageItems: KnockoutComputed; + pageCount: KnockoutComputed; + itemCount: KnockoutComputed; + firstItemOnPage: KnockoutComputed; + lastItemOnPage: KnockoutComputed; + hasPreviousPage: KnockoutComputed; + hasNextPage: KnockoutComputed; + isFirstPage: KnockoutComputed; + isLastPage: KnockoutComputed; + pages: KnockoutComputed; + + toNextPage(): void; + toPreviousPage(): void; + toLastPage(): void; + toFirstPage(): void; +} + +interface KnockoutPagedOptions { + pageSize?: number; + pageNumber?: number; + pageGenerator?: string; +} + +interface KnockoutObservableArray { + extend(requestedExtenders: { 'paged': any; }): KnockoutPagedObservableArray; +} + +interface KnockoutPageGenerator { + generate(pagedObservable: KnockoutPagedObservableArray): number[]; +} + +interface KnockoutSlidingPageGenerator extends KnockoutPageGenerator { + windowSize: KnockoutObservable; +} + +interface KnockoutExtenders { + paged(target: KnockoutObservableArray, options: KnockoutPagedOptions): KnockoutObservableArray; +} \ No newline at end of file diff --git a/knockout-pre-rendered/knockout-pre-rendered-tests.ts b/knockout-pre-rendered/knockout-pre-rendered-tests.ts new file mode 100644 index 000000000..f3a011e95 --- /dev/null +++ b/knockout-pre-rendered/knockout-pre-rendered-tests.ts @@ -0,0 +1,15 @@ +/// + +function initBindingHandler() { + ko.bindingHandlers.init = { + init: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {}, + update: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => {} + }; +} + +function foreachInitBindingHandler() { + ko.bindingHandlers.foreachInit = { + init: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { }, + update: (element: any, valueAccessor: () => any, allBindingsAccessor: KnockoutAllBindingsAccessor, viewModel: any, bindingContext: KnockoutBindingContext) => { } + }; +} \ No newline at end of file diff --git a/knockout-pre-rendered/knockout-pre-rendered.d.ts b/knockout-pre-rendered/knockout-pre-rendered.d.ts new file mode 100644 index 000000000..8c3641aa9 --- /dev/null +++ b/knockout-pre-rendered/knockout-pre-rendered.d.ts @@ -0,0 +1,11 @@ +// Type definitions for knockout-pre-rendered +// Project: https://github.com/ErikSchierboom/knockout-pre-rendered +// Definitions by: Erik Schierboom +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface KnockoutBindingHandlers { + init: KnockoutBindingHandler; + foreachInit: KnockoutBindingHandler; +} \ No newline at end of file diff --git a/knockout.postbox/knockout-postbox.d.ts b/knockout.postbox/knockout-postbox.d.ts index 1dfda1a25..edddd02a1 100644 --- a/knockout.postbox/knockout-postbox.d.ts +++ b/knockout.postbox/knockout-postbox.d.ts @@ -10,6 +10,7 @@ interface KnockoutPostBox { publish(topic: string, value?: T): void; defaultComparer(newValue: T, oldValue: T): boolean; serializer: (object: any) => string; + reset(): void; } interface KnockoutObservable { diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index a906348a6..94964950c 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -248,9 +248,9 @@ interface KnockoutUtils { removeDisposeCallback(node: Element, callback: Function): void; - cleanNode(node: Element): Element; + cleanNode(node: Node): Element; - removeNode(node: Element): void; + removeNode(node: Node): void; }; ////////////////////////////////// @@ -281,8 +281,6 @@ interface KnockoutUtils { extend(target: Object, source: Object): Object; - emptyDomNode(domNode: HTMLElement): void; - moveCleanedNodesToContainerElement(nodes: any[]): HTMLElement; cloneNodes(nodesArray: any[], shouldCleanNodes: boolean): any[]; @@ -576,6 +574,7 @@ declare module KnockoutComponentTypes { interface Config { viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; template: string | Node[]| DocumentFragment | TemplateElement | AMDModule; + synchronous?: boolean; } interface ComponentConfig { diff --git a/localForage/localForage-tests.ts b/localForage/localForage-tests.ts index f1a416dcf..15638c1cb 100644 --- a/localForage/localForage-tests.ts +++ b/localForage/localForage-tests.ts @@ -1,34 +1,68 @@ -/// +/// -declare var localForage: lf.ILocalForage -declare var callback: lf.ICallback -declare var promise: lf.IPromise +declare var localForage: lf.ILocalForage; +declare var callback: lf.ICallback; +declare var iterateCallback: lf.IIterateCallback; +declare var errorCallback: lf.IErrorCallback; +declare var keyCallback: lf.IKeyCallback; +declare var keysCallback: lf.IKeysCallback; +declare var numberCallback: lf.INumberCallback; +declare var promise: lf.IPromise; () => { - localForage.clear() - localForage.length - localForage.key(0) + localForage.clear((err: any) => { + var newError: any = err; + }); + + localForage.iterate((str: string, key: string, num: number) => { + var newStr: string = str; + var newKey: string = key; + var newNum: number = num; + }); + + localForage.length((err: any, num: number) => { + var newError: any = err; + var newNumber: number = num; + }); + + localForage.key(0,(err: any, value: string) => { + var newError: any = err; + var newValue: string = value; + }); + + localForage.keys((err: any, keys: Array) => { + var newError: any = err; + var newArray: Array = keys; + }); + + localForage.getItem("key",(err: any, str: string) => { + var newError: any = err; + var newStr: string = str + }); + + localForage.getItem("key").then((err: any, str: string) => { + var newError: any = err; + var newStr: string = str + }); - localForage.getItem("key", (str: string) => { - var newStr: string = str - }) - localForage.getItem("key").then((str: string) => { - var newStr: string = str - }) + localForage.setItem("key", "value",(err: any, str: string) => { + var newError: any = err; + var newStr: string = str + }); + + localForage.setItem("key", "value").then((err: any, str: string) => { + var newError: any = err; + var newStr: string = str; + }); - localForage.setItem("key", "value", (str: string) => { - var newStr: string = str - }) - localForage.setItem("key", "value").then((str: string) => { - var newStr: string = str - }) + localForage.removeItem("key",(err: any) => { + var newError: any = err; + }); + + localForage.removeItem("key").then((err: any, str: string) => { + var newError: any = err; + var newStr: string = str + }); - localForage.removeItem("key", (str: string) => { - var newStr: string = str - }) - localForage.removeItem("key").then((str: string) => { - var newStr: string = str - }) - - promise.then(callback) + promise.then(callback); } diff --git a/localForage/localForage.d.ts b/localForage/localForage.d.ts index c3d0371d0..b5c40dd61 100644 --- a/localForage/localForage.d.ts +++ b/localForage/localForage.d.ts @@ -1,23 +1,70 @@ -// Type definitions for Mozilla's localForage +// Type definitions for Mozilla's localForage // Project: https://github.com/mozilla/localforage -// Definitions by: david pichsenmeister +// Definitions by: yuichi david pichsenmeister // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module lf { interface ILocalForage { - clear(): void - key(index: number): T - length: number + /** + * Removes every key from the database, returning it to a blank slate. + */ + clear(callback: IErrorCallback): void + /** + * Iterate over all value/key pairs in datastore. + */ + iterate(iterateCallback: IIterateCallback): void + /** + * Get the name of a key based on its ID. + */ + key(keyIndex: number, callback: IKeyCallback): void + /** + * Get the list of all keys in the datastore. + */ + keys(callback: IKeysCallback): void; + /** + * Gets the number of keys in the offline store (i.e. its “length”). + */ + length(callback: INumberCallback): void + /** + * Gets an item from the storage library and supplies the result to a callback. + * If the key does not exist, getItem() will return null. + */ getItem(key: string, callback: ICallback): void getItem(key: string): IPromise + /** + * Saves data to an offline store. + */ setItem(key: string, value: T, callback: ICallback): void setItem(key: string, value: T): IPromise - removeItem(key: string, callback: ICallback): void + /** + * Removes the value of a key from the offline store. + */ + removeItem(key: string, callback: IErrorCallback): void removeItem(key: string): IPromise } interface ICallback { - (data: T): void + (err: any, value: T): void + } + + interface IIterateCallback { + (value: T, key: string, iterationNumber: number): void + } + + interface IErrorCallback { + (err: any): void + } + + interface IKeyCallback { + (err: any, keyName: string): void + } + + interface IKeysCallback { + (err: any, keys: Array): void + } + + interface INumberCallback { + (err: any, numberOfKeys: number): void } interface IPromise { diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 10900315f..6a48e20c1 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -39,6 +39,10 @@ interface IKey { code: number; } +interface IDictionary { + [index: string]: T; +} + var foodsOrganic: IFoodOrganic[] = [ { name: 'banana', organic: true }, { name: 'beet', organic: false }, @@ -61,7 +65,10 @@ var stoogesAges: IStoogesAge[] = [ { 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 } ]; - +var stoogesAgesDict: IDictionary = { + first: { 'name': 'moe', 'age': 40 }, + second: { 'name': 'larry', 'age': 50 } +}; var stoogesCombined: IStoogesCombined[] = [ { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } @@ -264,8 +271,14 @@ result = _.last(foodsType, { 'type': 'vegetable' }); result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); -result = <{ [key: string]: any }>_.zipObject(['moe', 'larry'], [30, 40]); -result = <{ [key: string]: any }>_.object(['moe', 'larry'], [30, 40]); +result = <_.Dictionary>_.zipObject(['moe', 'larry'], [30, 40]); +result = <_.LoDashObjectWrapper<_.Dictionary>>_(['moe', 'larry']).zipObject([30, 40]); +result = <_.Dictionary>_.object(['moe', 'larry'], [30, 40]); +result = <_.LoDashObjectWrapper<_.Dictionary>>_(['moe', 'larry']).object([30, 40]); +result = <_.Dictionary>_.zipObject([['moe', 30], ['larry', 40]]); +result = <_.LoDashObjectWrapper<_.Dictionary>>_([['moe', 30], ['larry', 40]]).zipObject(); +result = <_.Dictionary>_.object([['moe', 30], ['larry', 40]]); +result = <_.LoDashObjectWrapper<_.Dictionary>>_([['moe', 30], ['larry', 40]]).object(); result = _.pull([1, 2, 3, 1, 2, 3], 2, 3); @@ -501,6 +514,23 @@ result = <_.LoDashWrapper>_([4, 2, 8, 6]).min(); result = <_.LoDashWrapper>_(stoogesAges).min(function (stooge) { return stooge.age; }); result = <_.LoDashWrapper>_(stoogesAges).min('age'); +result = _.sum([4, 2, 8, 6]); +result = _.sum([4, 2, 8, 6], function(v) { return v; }); +result = _.sum({a: 2, b: 4}); +result = _.sum({a: 2, b: 4}, function(v) { return v; }); +result = _.sum(stoogesAges, function (stooge) { return stooge.age; }); +result = _.sum(stoogesAges, 'age'); +result = _.sum(stoogesAgesDict, function(stooge) { return stooge.age; }); +result = _.sum(stoogesAgesDict, 'age'); +result = _([4, 2, 8, 6]).sum(); +result = _([4, 2, 8, 6]).sum(function(v) { return v; }); +result = _({a: 2, b: 4}).sum(); +result = _({a: 2, b: 4}).sum(function(v) { return v; }); +result = _(stoogesAges).sum(function (stooge) { return stooge.age; }); +result = _(stoogesAges).sum('age'); +result = _(stoogesAgesDict).sum(function (stooge) { return stooge.age; }); +result = _(stoogesAgesDict).sum('age'); + result = _.pluck(stoogesAges, 'name'); result = _(stoogesAges).pluck('name').value(); @@ -611,6 +641,12 @@ result = _.where(stoogesCombined, { 'quotes': ['Poifect!'] } result = _(stoogesCombined).where({ 'age': 40 }).value(); result = _(stoogesCombined).where({ 'quotes': ['Poifect!'] }).value(); +/******** + * Date * + ********/ + +result = _.now(); + /************* * Functions * *************/ @@ -634,12 +670,16 @@ _.forEach(saves, function (type) { asyncSave({ 'type': type, 'complete': done }); }); -var funcBind = function (greeting: string) { return greeting + ' ' + this.name }; -var funcBind2: () => any = _.bind(funcBind, { 'name': 'moe' }, 'hi'); -funcBind2(); +var funcBind = function(greeting: string, punctuation: string) { return greeting + ' ' + this.user + punctuation; }; +var funcBound1: (punctuation: string) => any = _.bind(funcBind, { 'name': 'moe' }, 'hi'); +funcBound1('!'); -var funcBind3: () => any = _(funcBind).bind({ 'name': 'moe' }, 'hi').value(); -funcBind3(); +var funcBound2: (punctuation: string) => any = _(funcBind).bind({ 'name': 'moe' }, 'hi').value(); +funcBound2('!'); + +var addTwoNumbers = function (x: number, y: number) { return x + y }; +var plusTwo = _.bind(addTwoNumbers, null, 2); +plusTwo(100); var view = { 'label': 'docs', diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 01238b769..602b05d31 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -41,6 +41,7 @@ declare module _ { (value: number): LoDashWrapper; (value: string): LoDashWrapper; (value: boolean): LoDashWrapper; + (value: Array): LoDashNumberArrayWrapper; (value: Array): LoDashArrayWrapper; (value: T): LoDashObjectWrapper; (value: any): LoDashWrapper; @@ -98,7 +99,7 @@ declare module _ { **/ interface Support { /** - * Detect if an arguments object’s [[Class]] is resolvable (all but Firefox < 4, IE < 9). + * Detect if an arguments object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). **/ argsClass: boolean; @@ -205,6 +206,8 @@ declare module _ { unshift(...items: any[]): LoDashWrapper; } + interface LoDashNumberArrayWrapper extends LoDashArrayWrapper { } + //_.chain interface LoDashStatic { /** @@ -258,7 +261,7 @@ declare module _ { //_.chunk interface LoDashStatic { /** - * Creates an array of elements split into groups the length of size. If collection can’t be + * Creates an array of elements split into groups the length of size. If collection can't be * split evenly, the final chunk will be the remaining elements. * @param array The array to process. * @param size The length of each chunk. @@ -287,12 +290,12 @@ declare module _ { * @param array Array to compact. * @return (Array) Returns a new array of filtered values. **/ - compact(array: Array): T[]; + compact(array?: Array): T[]; /** * @see _.compact **/ - compact(array: List): T[]; + compact(array?: List): T[]; } interface LoDashArrayWrapper { @@ -312,13 +315,13 @@ declare module _ { * @return Returns a new array of filtered values. **/ difference( - array: Array, + array?: Array, ...others: Array[]): T[]; /** * @see _.difference **/ difference( - array: List, + array?: List, ...others: List[]): T[]; } @@ -456,12 +459,12 @@ declare module _ { * @param array Retrieves the first element of this array. * @return Returns the first element of `array`. **/ - first(array: Array): T; + first(array?: Array): T; /** * @see _.first **/ - first(array: List): T; + first(array?: List): T; /** * @see _.first @@ -2066,25 +2069,47 @@ declare module _ { //_.zipObject interface LoDashStatic { /** - * Creates an object composed from arrays of keys and values. Provide either a single - * two dimensional array, i.e. [[key1, value1], [key2, value2]] or two arrays, one of - * keys and one of corresponding values. - * @param keys The array of keys. - * @param values The array of values. - * @return An object composed of the given keys and corresponding values. + * The inverse of _.pairs; this method returns an object composed from arrays of property + * names and values. Provide either a single two dimensional array, e.g. [[key1, value1], + * [key2, value2]] or two arrays, one of property names and one of corresponding values. + * @param props The property names. + * @param values The property values. + * @return Returns the new object. **/ zipObject( - keys: List, - values: List): TResult; + props: List, + values?: List): TResult; /** - * @see _.object + * @see _.zipObject + **/ + zipObject(props: List>): Dictionary; + + /** + * @see _.zipObject **/ object( - keys: List, - values: List): TResult; - } + props: List, + values?: List): TResult; + /** + * @see _.zipObject + **/ + object(props: List>): Dictionary; + } + + interface LoDashArrayWrapper { + /** + * @see _.zipObject + **/ + zipObject(values?: List): _.LoDashObjectWrapper>; + + /** + * @see _.zipObject + **/ + object(values?: List): _.LoDashObjectWrapper>; + } + /* ************* * Collections * ************* */ @@ -2253,7 +2278,7 @@ declare module _ { **/ countBy( collection: Dictionary, - callback?: ListIterator, + callback?: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -2338,7 +2363,7 @@ declare module _ { **/ every( collection: Dictionary, - callback?: ListIterator, + callback?: DictionaryIterator, thisArg?: any): boolean; /** @@ -2410,7 +2435,7 @@ declare module _ { **/ all( collection: Dictionary, - callback?: ListIterator, + callback?: DictionaryIterator, thisArg?: any): boolean; /** @@ -2497,7 +2522,7 @@ declare module _ { **/ filter( collection: Dictionary, - callback: ListIterator, + callback: DictionaryIterator, thisArg?: any): T[]; /** @@ -2569,7 +2594,7 @@ declare module _ { **/ select( collection: Dictionary, - callback: ListIterator, + callback: DictionaryIterator, thisArg?: any): T[]; /** @@ -2709,7 +2734,7 @@ declare module _ { **/ find( collection: Dictionary, - callback: ListIterator, + callback: DictionaryIterator, thisArg?: any): T; /** @@ -2781,7 +2806,7 @@ declare module _ { **/ detect( collection: Dictionary, - callback: ListIterator, + callback: DictionaryIterator, thisArg?: any): T; /** @@ -2853,7 +2878,7 @@ declare module _ { **/ findWhere( collection: Dictionary, - callback: ListIterator, + callback: DictionaryIterator, thisArg?: any): T; /** @@ -2955,7 +2980,7 @@ declare module _ { **/ findLast( collection: Dictionary, - callback: ListIterator, + callback: DictionaryIterator, thisArg?: any): T; /** @@ -3057,7 +3082,7 @@ declare module _ { **/ forEach( object: Dictionary, - callback: ObjectIterator, + callback: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -3092,7 +3117,7 @@ declare module _ { **/ each( object: Dictionary, - callback: ObjectIterator, + callback: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -3163,7 +3188,7 @@ declare module _ { **/ forEachRight( object: Dictionary, - callback: ObjectIterator, + callback: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -3190,7 +3215,7 @@ declare module _ { **/ eachRight( object: Dictionary, - callback: ObjectIterator, + callback: DictionaryIterator, thisArg?: any): Dictionary; } @@ -3296,7 +3321,7 @@ declare module _ { **/ groupBy( collection: Dictionary, - callback?: ListIterator, + callback?: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -3518,7 +3543,7 @@ declare module _ { **/ map( object: Dictionary, - callback: ObjectIterator, + callback: DictionaryIterator, thisArg?: any): TResult[]; /** @@ -3558,7 +3583,7 @@ declare module _ { **/ collect( object: Dictionary, - callback: ObjectIterator, + callback: DictionaryIterator, thisArg?: any): TResult[]; /** @@ -3657,7 +3682,7 @@ declare module _ { **/ max( collection: Dictionary, - callback?: ListIterator, + callback?: DictionaryIterator, thisArg?: any): T; /** @@ -3842,6 +3867,131 @@ declare module _ { min( whereValue: W): LoDashWrapper; } + + //_.sum + interface LoDashStatic { + /** + * Gets the sum of the values in collection. + * + * @param collection The collection to iterate over. + * @param iteratee The function invoked per iteration. + * @param thisArg The this binding of iteratee. + * @return Returns the sum. + **/ + sum( + collection: Array): number; + + /** + * @see _.sum + **/ + sum( + collection: List): number; + + /** + * @see _.sum + **/ + sum( + collection: Dictionary): number; + + /** + * @see _.sum + **/ + sum( + collection: Array, + iteratee: ListIterator, + thisArg?: any): number; + + /** + * @see _.sum + **/ + sum( + collection: List, + iteratee: ListIterator, + thisArg?: any): number; + + /** + * @see _.sum + **/ + sum( + collection: Dictionary, + iteratee: ObjectIterator, + thisArg?: any): number; + + /** + * @see _.sum + * @param property _.property callback shorthand. + **/ + sum( + collection: Array, + property: string): number; + + /** + * @see _.sum + * @param property _.property callback shorthand. + **/ + sum( + collection: List, + property: string): number; + + /** + * @see _.sum + * @param property _.property callback shorthand. + **/ + sum( + collection: Dictionary, + property: string): number; + } + + interface LoDashNumberArrayWrapper { + /** + * @see _.sum + **/ + sum(): number + + /** + * @see _.sum + **/ + sum( + iteratee: ListIterator, + thisArg?: any): number; + } + + interface LoDashArrayWrapper { + /** + * @see _.sum + **/ + sum( + iteratee: ListIterator, + thisArg?: any): number; + + /** + * @see _.sum + * @param property _.property callback shorthand. + **/ + sum( + property: string): number; + } + + interface LoDashObjectWrapper { + /** + * @see _.sum + **/ + sum(): number + + /** + * @see _.sum + **/ + sum( + iteratee: ObjectIterator, + thisArg?: any): number; + + /** + * @see _.sum + * @param property _.property callback shorthand. + **/ + sum( + property: string): number; + } //_.pluck interface LoDashStatic { @@ -4290,7 +4440,7 @@ declare module _ { **/ reject( collection: Dictionary, - callback: ListIterator, + callback: DictionaryIterator, thisArg?: any): T[]; /** @@ -4501,7 +4651,7 @@ declare module _ { **/ some( collection: Dictionary, - callback?: ListIterator, + callback?: DictionaryIterator, thisArg?: any): boolean; /** @@ -4581,7 +4731,7 @@ declare module _ { **/ any( collection: Dictionary, - callback?: ListIterator, + callback?: DictionaryIterator, thisArg?: any): boolean; /** @@ -4795,6 +4945,20 @@ declare module _ { where(properties: U): LoDashArrayWrapper; } + /******** + * Date * + ********/ + + //_.now + interface LoDashStatic { + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * @return The number of milliseconds. + **/ + now(): number; + } + /************* * Functions * *************/ @@ -4833,7 +4997,7 @@ declare module _ { bind( func: Function, thisArg: any, - ...args: any[]): () => any; + ...args: any[]): (...args: any[]) => any; } interface LoDashObjectWrapper { @@ -4842,7 +5006,7 @@ declare module _ { **/ bind( thisArg: any, - ...args: any[]): LoDashObjectWrapper<() => any>; + ...args: any[]): LoDashObjectWrapper<(...args: any[]) => any>; } //_.bindAll @@ -4997,7 +5161,7 @@ declare module _ { * @param wait The number of milliseconds to delay. * @param options The options object. * @param options.leading Specify execution on the leading edge of the timeout. - * @param options.maxWait The maximum time func is allowed to be delayed before it’s called. + * @param options.maxWait The maximum time func is allowed to be delayed before it's called. * @param options.trailing Specify execution on the trailing edge of the timeout. * @return The new debounced function. **/ @@ -5023,7 +5187,7 @@ declare module _ { leading?: boolean; /** - * The maximum time func is allowed to be delayed before it’s called. + * The maximum time func is allowed to be delayed before it's called. **/ maxWait?: number; @@ -5524,7 +5688,7 @@ declare module _ { **/ forIn( object: Dictionary, - callback?: ObjectIterator, + callback?: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -5557,7 +5721,7 @@ declare module _ { **/ forInRight( object: Dictionary, - callback?: ObjectIterator, + callback?: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -5591,7 +5755,7 @@ declare module _ { **/ forOwn( object: Dictionary, - callback?: ObjectIterator, + callback?: DictionaryIterator, thisArg?: any): Dictionary; /** @@ -5624,7 +5788,7 @@ declare module _ { **/ forOwnRight( object: Dictionary, - callback?: ObjectIterator, + callback?: DictionaryIterator, thisArg?: any): Dictionary; /** * @see _.forOwnRight @@ -5701,7 +5865,7 @@ declare module _ { * @param value The value to check. * @return True if the value is an arguments object, else false. **/ - isArguments(value: any): boolean; + isArguments(value?: any): boolean; } //_.isArray @@ -5711,7 +5875,7 @@ declare module _ { * @param value The value to check. * @return True if the value is an array, else false. **/ - isArray(value: any): boolean; + isArray(value?: any): boolean; } //_.isBoolean @@ -5721,7 +5885,7 @@ declare module _ { * @param value The value to check. * @return True if the value is a boolean value, else false. **/ - isBoolean(value: any): boolean; + isBoolean(value?: any): boolean; } //_.isDate @@ -5731,7 +5895,7 @@ declare module _ { * @param value The value to check. * @return True if the value is a date, else false. **/ - isDate(value: any): boolean; + isDate(value?: any): boolean; } //_.isElement @@ -5741,7 +5905,7 @@ declare module _ { * @param value The value to check. * @return True if the value is a DOM element, else false. **/ - isElement(value: any): boolean; + isElement(value?: any): boolean; } //_.isEmpty @@ -5752,22 +5916,7 @@ declare module _ { * @param value The value to inspect. * @return True if the value is empty, else false. **/ - isEmpty(value: any[]): boolean; - - /** - * @see _.isEmpty - **/ - isEmpty(value: Dictionary): boolean; - - /** - * @see _.isEmpty - **/ - isEmpty(value: string): boolean; - - /** - * @see _.isEmpty - **/ - isEmpty(value: any): boolean; + isEmpty(value?: any[]|Dictionary|string|any): boolean; } //_.isError @@ -5796,8 +5945,8 @@ declare module _ { * @return True if the values are equivalent, else false. **/ isEqual( - a: any, - b: any, + a?: any, + b?: any, callback?: (a: any, b: any) => boolean, thisArg?: any): boolean; } @@ -5812,7 +5961,7 @@ declare module _ { * @param value The value to check. * @return True if the value is finite, else false. **/ - isFinite(value: any): boolean; + isFinite(value?: any): boolean; } //_.isFunction @@ -5822,7 +5971,7 @@ declare module _ { * @param value The value to check. * @return True if the value is a function, else false. **/ - isFunction(value: any): boolean; + isFunction(value?: any): boolean; } //_.isNaN @@ -5835,7 +5984,7 @@ declare module _ { * @param value The value to check. * @return True if the value is NaN, else false. **/ - isNaN(value: any): boolean; + isNaN(value?: any): boolean; } //_.isNull @@ -5845,7 +5994,7 @@ declare module _ { * @param value The value to check. * @return True if the value is null, else false. **/ - isNull(value: any): boolean; + isNull(value?: any): boolean; } //_.isNumber @@ -5857,7 +6006,7 @@ declare module _ { * @param value The value to check. * @return True if the value is a number, else false. **/ - isNumber(value: any): boolean; + isNumber(value?: any): boolean; } //_.isObject @@ -5868,7 +6017,7 @@ declare module _ { * @param value The value to check. * @return True if the value is an object, else false. **/ - isObject(value: any): boolean; + isObject(value?: any): boolean; } //_.isPlainObject @@ -5878,7 +6027,7 @@ declare module _ { * @param value The value to check. * @return True if value is a plain object, else false. **/ - isPlainObject(value: any): boolean; + isPlainObject(value?: any): boolean; } //_.isRegExp @@ -5888,7 +6037,7 @@ declare module _ { * @param value The value to check. * @return True if the value is a regular expression, else false. **/ - isRegExp(value: any): boolean; + isRegExp(value?: any): boolean; } //_.isString @@ -5898,7 +6047,7 @@ declare module _ { * @param value The value to check. * @return True if the value is a string, else false. **/ - isString(value: any): boolean; + isString(value?: any): boolean; } //_.isUndefined @@ -5908,7 +6057,7 @@ declare module _ { * @param value The value to check. * @return True if the value is undefined, else false. **/ - isUndefined(value: any): boolean; + isUndefined(value?: any): boolean; } //_.keys @@ -5918,7 +6067,7 @@ declare module _ { * @param object The object to inspect. * @return An array of property names. **/ - keys(object: any): string[]; + keys(object?: any): string[]; } interface LoDashObjectWrapper { @@ -6063,12 +6212,12 @@ declare module _ { //_.pairs interface LoDashStatic { /** - * Creates a two dimensional array of an object’s key-value pairs, + * Creates a two dimensional array of an object's key-value pairs, * i.e. [[key1, value1], [key2, value2]]. * @param object The object to inspect. * @return Aew array of key-value pairs. **/ - pairs(object: any): any[][]; + pairs(object?: any): any[][]; } interface LoDashObjectWrapper { @@ -6180,7 +6329,7 @@ declare module _ { * @param object The object to inspect. * @return Returns an array of property values. **/ - values(object: any): any[]; + values(object?: any): any[]; } /********** @@ -6206,10 +6355,8 @@ declare module _ { trimLeft(str?: string, chars?: string): string; trimRight(str?: string, chars?: string): string; trunc(str?: string, len?: number): string; - trunc(str?: string, options?: { length?: number; omission?: string; separator?: string }): string; - trunc(str?: string, options?: { length?: number; omission?: string; separator?: RegExp }): string; - words(str?: string, pattern?: string): string[]; - words(str?: string, pattern?: RegExp): string[]; + trunc(str?: string, options?: { length?: number; omission?: string; separator?: string|RegExp }): string; + words(str?: string, pattern?: string|RegExp): string[]; } //_.parseInt @@ -6224,7 +6371,7 @@ declare module _ { * @param radix The radix used to interpret the value to parse. * @return The new integer value. **/ - parseInt(value: string, radix?: number): number; + parseInt(value?: string, radix?: number): number; } /************* @@ -6237,7 +6384,7 @@ declare module _ { * @param string The string to escape. * @return The escaped string. **/ - escape(str: string): string; + escape(str?: string): string; } //_.identity @@ -6247,7 +6394,7 @@ declare module _ { * @param value Any value. * @return value. **/ - identity(value: T): T; + identity(value?: T): T; } //_.mixin @@ -6256,7 +6403,7 @@ declare module _ { * Adds function properties of a source object to the lodash function and chainable wrapper. * @param object The object of function properties to add to lodash. **/ - mixin(object: Dictionary<(value: any) => any>): void; + mixin(object?: Dictionary<(value: any) => any>): void; } //_.noConflict @@ -6271,7 +6418,7 @@ declare module _ { //_.property interface LoDashStatic { /** - * # Ⓢ + * # S * Creates a "_.pluck" style function, which returns the key value of a given object. * @param key (string) * @return the value of that key on the object @@ -6343,7 +6490,7 @@ declare module _ { * @param options.evaluate The "evaluate" delimiter. * @param options.import An object to import into the template as local variables. * @param options.interpolate The "interpolate" delimiter. - * @param sourceURL The sourceURL of the template’s compiled source. + * @param sourceURL The sourceURL of the template's compiled source. * @param variable The data object variable name. * @return Returns the compiled Lo-Dash HTML template or a TemplateExecutor if no data is passed. **/ @@ -6430,11 +6577,15 @@ declare module _ { } interface ListIterator { - (value: T, index: number, list: T[]): TResult; + (value: T, index: number, collection: T[]): TResult; + } + + interface DictionaryIterator { + (value: T, key: string, collection: Dictionary): TResult; } interface ObjectIterator { - (element: T, key: string, list: any): TResult; + (element: T, key: string, collection: any): TResult; } interface MemoVoidIterator { diff --git a/matter-js/matter-js-tests.ts b/matter-js/matter-js-tests.ts new file mode 100644 index 000000000..31649fc44 --- /dev/null +++ b/matter-js/matter-js-tests.ts @@ -0,0 +1,57 @@ +/// + +var Engine = Matter.Engine, + World = Matter.World, + Body = Matter.Body, + Bodies = Matter.Bodies, + Composites = Matter.Composites, + Constraint = Matter.Constraint, + Events = Matter.Events, + Query = Matter.Query + + +var engine = Engine.create(document.body) + +//Bodies +var box1 = Bodies.rectangle(400,200,80,80) +var box2 = Bodies.rectangle(400,610,810,60, { + angle: 10, + angularSpeed: 11, + angularVelocity: 1, + density: 4, + isStatic: true +}) + +var circle1 = Bodies.circle(100,100,50) + +World.addBody(engine.world, box1) +World.add(engine.world, [box2, circle1]) + + +//Composites +var stack = Composites.stack(0, 100, 5, 1, 20, 0, function(x:number, y:number, column:number, row:number) { + return Bodies.circle(x, y, 75, { restitution: 0.9 }); + }); + +World.add(engine.world, stack); + +//Constraints +var constraint1 = Constraint.create({ + bodyA: box1, + bodyB: box2, + stiffness: 0.02 +}) + +//Query +var collisions = Query.ray([box1, box2, circle1], {x:1, y:2}, {x:3, y:4}); + +World.addConstraint(engine.world, constraint1) + + +//events +Events.on(engine, "beforeTick", (e:any)=>{ + +}) + + +Engine.run(engine) diff --git a/matter-js/matter-js.d.ts b/matter-js/matter-js.d.ts new file mode 100644 index 000000000..5c4426ea2 --- /dev/null +++ b/matter-js/matter-js.d.ts @@ -0,0 +1,1532 @@ +// Type definitions for Matter.js 0.8.0 +// Project: https://github.com/liabru/matter-js +// Definitions by: Ivane Gegia +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module Matter +{ + export interface IEngineOptions + { + + } + + export interface IEngineTimingOptions + { + /** + *A Number that specifies the time correction factor to apply to the current timestep. It is automatically handled when using Engine.run, but is also only optional even if you use your own game loop. The value is defined as delta / lastDelta, i.e. the percentage change of delta between steps. This value is always 1 (no correction) when frame rate is constant or engine.timing.isFixed is true. If the framerate and hence delta are changing, then correction should be applied to the current update to account for the change. See the paper on Time Corrected Verlet for more information. + */ + correction:number; + + /** + * A Number that specifies the time step between updates in milliseconds. If engine.timing.isFixed is set to true, then delta is fixed. If it is false, then delta can dynamically change to maintain the correct apparant simulation speed. + */ + delta:number; + + /** + * A Number that specifies the global scaling factor of time for all bodies. A value of 0 freezes the simulation. A value of 0.1 gives a slow-motion effect. A value of 1.2 gives a speed-up effect. + */ + timeScale:number; + + /** + * A Number that specifies the current simulation-time in milliseconds starting from 0. It is incremented on every Engine.update by the timing.delta. + */ + timestamp:number; + + /** + * An integer Number that specifies the number of velocity iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + */ + velocityIterations:number; + + } + + export class Engine + { + /** + * Clears the engine including the world, pairs and broadphase. + * @param engine + */ + static clear(engine:Engine):void; + + /** + * Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults. All properties have default values, and many are pre-calculated automatically based on other properties. See the properites section below for detailed information on what you can pass via the options object. + * @param element + * @param options + */ + static create(element?: HTMLElement|IEngineOptions, options?:IEngineOptions):Engine; + + /** + * Merges two engines by keeping the configuration of engineA but replacing the world with the one from engineB. + * @param engineA + * @param engineB + */ + static merge(engineA:Engine, engineB:Engine):void; + + /** + * Renders the world by calling its defined renderer engine.render.controller. Triggers beforeRender and afterRender events. + * @param engineA + * @param engineB + */ + static render(engineA:Engine, engineB:Engine):void; + + /** + * An optional utility function that provides a game loop, that handles updating the engine for you. Calls Engine.update and Engine.render on the requestAnimationFrame event automatically. Handles time correction and non-fixed dynamic timing (if enabled). Triggers beforeTick, tick and afterTick events. + * @param engine + */ + static run(engine:Engine):void; + + /** + * Moves the simulation forward in time by delta ms. Triggers beforeUpdate and afterUpdate events. + * + * @param engine + * @param delta + * @param correction + */ + static update(engine:Engine, delta:number, correction?:number):void; + + /** + * An integer Number that specifies the number of constraint iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. The default value of 2 is usually very adequate. + */ + constraintIterations:number; + + /** + * A flag that specifies whether the engine is running or not. + */ + enabled:boolean; + + /** + * A flag that specifies whether the engine should allow sleeping via the Matter.Sleeping module. Sleeping can improve stability and performance, but often at the expense of accuracy. + */ + enableSleeping:boolean; + + /** + * An integer Number that specifies the number of position iterations to perform each update. The higher the value, the higher quality the simulation will be at the expense of performance. + */ + positionIterations:number; + + /** + * An instance of a Render controller. The default value is a Matter.Render instance created by Engine.create. One may also develop a custom renderer module based on Matter.Render and pass an instance of it to Engine.create via options.render. + A minimal custom renderer object must define at least three functions: create, clear and world (see Matter.Render). It is also possible to instead pass the module reference via options.render.controller and Engine.create will instantiate one for you. + */ + render:Render; + + /** + * An Object containing properties regarding the timing systems of the engine. + */ + timing:IEngineTimingOptions; + + /** + * A World composite object that will contain all simulated bodies and constraints. + */ + world:World; + } + + interface IWorldOptions + { + + } + + /** + * The Matter.World module contains methods for creating and manipulating the world composite. A Matter.World is a Matter.Composite body, which is a collection of Matter.Body, Matter.Constraint and other Matter.Composite. A Matter.World has a few additional properties including gravity and bounds. It is important to use the functions in the Matter.Composite module to modify the world composite, rather than directly modifying its properties. There are also a few methods here that alias those in Matter.Composite for easier readability. + */ + export class World + { + /** + * Add objects or arrays of objects of types: Body, Constraint, Composite + * @param world + * @param body + * @returns world + */ + static add(world:World, body:Body|Array|Composite|Array|Constraint|Array):World; + + /** + * An alias for Composite.addBody since World is also a Composite + * @param world + * @param body + * @returns world + */ + static addBody(world:World, body:Body):World; + + /** + * An alias for Composite.add since World is also a Composite + * @param world + * @param composite + */ + static addComposite(world:World, composite:Composite):World; + + /** + * An alias for Composite.addConstraint since World is also a Composite. + * @param world + * @param constraint + */ + static addConstraint(world:World, constraint:Constraint):World; + + /** + * An alias for Composite.clear since World is also a Composite. + * @param world + * @param keepStatic + */ + static clear(world:World, keepStatic:boolean):void; + + /** + * Creates a new world composite. The options parameter is an object that specifies any properties you wish to override the defaults. See the properites section below for detailed information on what you can pass via the options object. + * @param options + */ + static create(options:IWorldOptions):World; + + } + + export interface IBodyDefinition + { + angle?:number; + angularSpeed?:number; + angularVelocity?:number; + area?:number; + axes?:Array; + bounds?:Bounds; + density?:number; + force?:Vector; + friction?:number; + frictionAir?:number; + groupId?:number; + id?:number; + inertia?:number; + inverseInertia?:number; + inverseMass?:number; + isSleeping?:boolean; + isStatic?:boolean; + label?:string; + mass?:number; + motion?:number; + position?:Vector; + render?:IBodyRenderOptions; + restitution?:number; + sleepThreshold?:number; + slop?:number; + speed?:number; + timeScale?:number; + torque?:number; + type?:string; + velocity?:Vector; + vertices?:Array; + } + + /** + * The Matter.Body module contains methods for creating and manipulating body models. A Matter.Body is a rigid body that can be simulated by a Matter.Engine. Factories for commonly used body configurations (such as rectangles, circles and other polygons) can be found in the module Matter.Bodies. + */ + export class Body + { + /** + * Applies a force to a body from a given world-space position, including resulting torque. + * @param body + * @param position + * @param force + */ + static applyForce(body:Body, position:Vector, force:Vector):void; + + /** + * Applys a mass dependant force to all given bodies. + * @param bodies + * @param gravity + */ + static applyGravityAll(bodies:Array, gravity:Vector):void; + + /** + * Creates a new rigid body model. The options parameter is an object that specifies any properties you wish to override the defaults. All properties have default values, and many are pre-calculated automatically based on other properties. See the properites section below for detailed information on what you can pass via the options object. + * @param options + */ + static create(options:IBodyDefinition):Body; + + /** + * Returns the next unique groupID number. + */ + static nextGroupId():number; + + /** + * Zeroes the body.force and body.torque force buffers. + * @param bodies + */ + static resetForcesAll(bodies:Array):void; + + /** + * Rotates a body by a given angle relative to its current angle, without imparting any angular velocity. + * @param body + * @param angle + */ + static rotate(body:Body, angle:number):void; + + /** + * Sets the body as static, including isStatic flag and setting mass and inertia to Infinity. + * @param isStatic + */ + setStatic(isStatic:boolean):void; + + /** + * Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre). + * @param body + * @param scaleX + * @param scaleY + * @param poinst + */ + static scale(body:Body, scaleX:number, scaleY:number, poinst?:Vector):void; + + /** + * Moves a body by a given vector relative to its current position, without imparting any velocity. + * + * @param body + * @param translation + */ + static translate(body:Body, translation:Vector):void; + + /** + *Performs a simulation step for the given body, including updating position and angle using Verlet integration. + * + * @param body + * @param deltaTime + * @param timeScale + * @param correction + */ + static update(body:Body, deltaTime:number, timeScale:number, correction:number):void; + + /** + * Applys Body.update to all given bodies. + * + * @param bodies + * @param deltaTime + * @param timeScale + * @param correction + * @param worldBounds + */ + static updateAll ( bodies:Array, deltaTime:number, timeScale:number, correction:number, worldBounds:Bounds ):void; + + /** + * A Number specifying the angle of the body, in radians. + */ + angle:number; + + /** + * A Number that measures the current angular speed of the body after the last Body.update. It is read-only and always positive (it's the magnitude of body.angularVelocity). + */ + angularSpeed:number; + + /** + * A Number that measures the current angular velocity of the body after the last Body.update. It is read-only. If you need to modify a body's angular velocity directly, you should apply a torque or simply change the body's angle (as the engine uses position-Verlet integration). + */ + angularVelocity:number; + + /** + * A Number that measures the area of the body's convex hull, calculated at creation by Body.create. + */ + area:number; + + /** + * An array of unique axis vectors (edge normals) used for collision detection. These are automatically calculated from the given convex hull (vertices array) in Body.create. They are constantly updated by Body.update during the simulation. + */ + axes:Array; + + /** + * A Bounds object that defines the AABB region for the body. It is automatically calculated from the given convex hull (vertices array) in Body.create and constantly updated by Body.update during simulation. + */ + bounds:Bounds; + + /** + * A Number that defines the density of the body, that is its mass per unit area. If you pass the density via Body.create the mass property is automatically calculated for you based on the size (area) of the object. This is generally preferable to simply setting mass and allows for more intuitive definition of materials (e.g. rock has a higher density than wood). + */ + density:number; + + /** + * A Vector that specifies the force to apply in the current step. It is zeroed after every Body.update. See also Body.applyForce. + */ + force:Vector; + + /** + * A Number that defines the friction of the body. The value is always positive and is in the range (0, 1). A value of 0 means that the body may slide indefinitely. A value of 1 means the body may come to a stop almost instantly after a force is applied. + The effects of the value may be non-linear. High values may be unstable depending on the body. The engine uses a Coulomb friction model including static and kinetic friction. Note that collision response is based on pairs of bodies, and that friction values are combined with the following formula: + Math.min(bodyA.friction, bodyB.friction) + */ + friction:number; + + /** + * A Number that defines the air friction of the body (air resistance). A value of 0 means the body will never slow as it moves through space. The higher the value, the faster a body slows when moving through space. The effects of the value are non-linear. + Default: 0.01 + */ + frictionAir:number; + + /** + * An integer Number that specifies the collision group the body belongs to. Bodies with the same groupId are considered as-one body and therefore do not interact. This allows for creation of segmented bodies that can self-intersect, such as a rope. The default value 0 means the body does not belong to a group, and can interact with all other bodies. + Default: 0 + */ + groupId:number; + + /** + * An integer Number uniquely identifying number generated in Body.create by Common.nextId. + */ + id:number; + + /** + * A Number that defines the moment of inertia (i.e. second moment of area) of the body. It is automatically calculated from the given convex hull (vertices array) and density in Body.create. If you modify this value, you must also modify the body.inverseInertia property (1 / inertia). + */ + inertia:number; + + /** + * A Number that defines the inverse moment of inertia of the body (1 / inertia). If you modify this value, you must also modify the body.inertia property. + */ + inverseInertia:number; + + /** + * A Number that defines the inverse mass of the body (1 / mass). If you modify this value, you must also modify the body.mass property. + */ + inverseMass:number; + + /** + * A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken. If you need to set a body as sleeping, you should use Sleeping.set as this requires more than just setting this flag. + Default: false + */ + isSleeping:boolean; + + /** + * A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed. If you need to set a body as static after its creation, you should use Body.setStatic as this requires more than just setting this flag. + Default: false + */ + isStatic:boolean; + + /** + * An arbitrary String name to help the user identify and manage bodies. + Default: "Body" + */ + label:string; + + /** + * A Number that defines the mass of the body, although it may be more appropriate to specify the density property instead. If you modify this value, you must also modify the body.inverseMass property (1 / mass). + */ + mass:number; + + /** + * A Number that measures the amount of movement a body currently has (a combination of speed and angularSpeed). It is read-only and always positive. It is used and updated by the Matter.Sleeping module during simulation to decide if a body has come to rest. + Default: 0 + */ + motion:number; + + /** + * A Vector that specifies the current world-space position of the body. + Default: { x: 0, y: 0 } + */ + position:Vector; + + /** + * An Object that defines the rendering properties to be consumed by the module Matter.Render. + */ + render:IBodyRenderOptions; + + /** + * A Number that defines the restitution (elasticity) of the body. The value is always positive and is in the range (0, 1). A value of 0 means collisions may be perfectly inelastic and no bouncing may occur. A value of 0.8 means the body may bounce back with approximately 80% of its kinetic energy. Note that collision response is based on pairs of bodies, and that restitution values are combined with the following formula: + Math.max(bodyA.restitution, bodyB.restitution) + Default: 0 + */ + restitution:number; + + /** + * A Number that defines the number of updates in which this body must have near-zero velocity before it is set as sleeping by the Matter.Sleeping module (if sleeping is enabled by the engine). + Default: 60 + */ + sleepThreshold:number; + + /** + * A Number that specifies a tollerance on how far a body is allowed to 'sink' or rotate into other bodies. Avoid changing this value unless you understand the purpose of slop in physics engines. The default should generally suffice, although very large bodies may require larger values for stable stacking. + Default: 0.05 + */ + slop:number; + + /** + * A Number that measures the current speed of the body after the last Body.update. It is read-only and always positive (it's the magnitude of body.velocity). + Default: 0 + */ + speed:number; + + /** + * A Number that allows per-body time scaling, e.g. a force-field where bodies inside are in slow-motion, while others are at full speed. + Default: 1 + */ + timeScale:number; + + /** + * A Number that specifies the torque (turning force) to apply in the current step. It is zeroed after every Body.update. + Default: 0 + */ + torque:number; + + /** + *A String denoting the type of object. + Default: "body" + */ + type:string; + + /** + * A Vector that measures the current velocity of the body after the last Body.update. It is read-only. If you need to modify a body's velocity directly, you should either apply a force or simply change the body's position (as the engine uses position-Verlet integration). + Default: { x: 0, y: 0 } + */ + velocity:Vector; + + /** + * An array of Vector objects that specify the convex hull of the rigid body. These should be provided about the origin (0, 0). E.g. + [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + When passed via Body.create, the verticies are translated relative to body.position (i.e. world-space, and constantly updated by Body.update during simulation). The Vector objects are also augmented with additional properties required for efficient collision detection. + Other properties such as inertia and bounds are automatically calculated from the passed vertices (unless provided via options). Concave hulls are not currently supported. The module Matter.Vertices contains useful methods for working with vertices. + */ + vertices:Array; + + } + + export class Bodies { + /** + * Creates a new rigid body model with a circle hull. The options parameter is an object that specifies any properties you wish to override the defaults. See the properites section of the Matter.Body module for detailed information on what you can pass via the options object. + * + * @param x + * @param y + * @param radius + * @param options + * @param maxSides + */ + static circle(x:number, y:number, radius:number, options?:IBodyDefinition, maxSides?:number):Body; + + /** + * Creates a new rigid body model with a regular polygon hull with the given number of sides. The options parameter is an object that specifies any properties you wish to override the defaults. See the properites section of the Matter.Body module for detailed information on what you can pass via the options object. + * + * @param x + * @param y + * @param sides + * @param radius + * @param options + */ + static polygon(x:number, y:number, sides:number, radius:number, options?:IBodyDefinition):Body; + + /** + * Creates a new rigid body model with a rectangle hull. The options parameter is an object that specifies any properties you wish to override the defaults. See the properites section of the Matter.Body module for detailed information on what you can pass via the options object. + * + * @param x + * @param y + * @param width + * @param height + * @param options + */ + static rectangle(x:number, y:number, width:number, height:number, options?:IBodyDefinition):Body; + + /** + * Creates a new rigid body model with a trapezoid hull. The options parameter is an object that specifies any properties you wish to override the defaults. See the properites section of the Matter.Body module for detailed information on what you can pass via the options object. + * + * @param x + * @param y + * @param width + * @param height + * @param slope + * @param options + */ + static trapezoid(x:number, y:number, width:number, height:number, slope:number, options?:IBodyDefinition):Body; + + + } + + export interface IBodyRenderOptions + { + /** + * A String that defines the fill style to use when rendering the body (if a sprite is not defined). It is the same as when using a canvas, so it accepts CSS style property values. + Default: a random colour + */ + fillStyle:string; + + /** + * A Number that defines the line width to use when rendering the body outline (if a sprite is not defined). A value of 0 means no outline will be rendered. + Default: 1.5 + */ + lineWidth:number; + + /** + * An Object that defines the sprite properties to use when rendering, if any. + */ + sprite:IBodyRenderOptionsSprite; + + /** + * A String that defines the stroke style to use when rendering the body outline (if a sprite is not defined). It is the same as when using a canvas, so it accepts CSS style property values. + Default: a random colour + */ + strokeStyle:string; + + /** + * A flag that indicates if the body should be rendered. + Default: true + */ + visible:boolean; + + } + + export interface IBodyRenderOptionsSprite + { + /** + * An String that defines the path to the image to use as the sprite texture, if any. + */ + texture:string; + + /** + * A Number that defines the scaling in the x-axis for the sprite, if any. + Default: 1 + */ + xScale:number; + + /** + * A Number that defines the scaling in the y-axis for the sprite, if any. + Default: 1 + */ + yScale:number; + } + + export class Bounds + { + + } + + export class Vector + { + + x:number; + y:number; + + /** + * Adds the two vectors. + * + * @param vectorA + * @param vectorB + * @returns A new vector of vectorA and vectorB added. + */ + static add ( vectorA:Vector, vectorB:Vector ):Vector; + + /** + * Returns the angle in radians between the two vectors relative to the x-axis. + * + * @param vectorA + * @param vectorB + * @returns The angle in radians. + */ + static angle ( vectorA:Vector, vectorB:Vector ):number; + + /** + * Returns the cross-product of two vectors. + * + * @param vectorA + * @param vectorB + * @returns The cross product of the two vectors. + */ + static cross ( vectorA:Vector, vectorB:Vector ):number; + + /** + * Divides a vector and a scalar. + * + * @param vector + * @param scalar + * @returns A new vector divided by scalar. + */ + static div ( vector:Vector, scalar:number ):Vector; + + /** + * Returns the dot-product of two vectors. + * + * @param vectorA + * @param vectorB + * @returns The dot product of the two vectors + */ + static dot ( vectorA:Vector, vectorB:Vector ):Number; + + /** + * Returns the magnitude (length) of a vector. + * + * @param vector + * @returns The magnitude of the vector + */ + static magnitude ( vector:Vector ):number; + + /** + * Returns the magnitude (length) of a vector (therefore saving a sqrt operation). + * + * @param vector + * @returns The squared magnitude of the vector. + */ + static magnitudeSquared ( vector:Vector ):number; + + /** + * Multiplies a vector and a scalar. + * + * @param vector + * @param scalar + * @returns A new vector multiplied by scalar + */ + static mult ( vector:Vector, scalar:number ):Vector; + + /** + * Negates both components of a vector such that it points in the opposite direction. + * @param vector + * @returns The negated vector. + */ + static neg ( vector:Vector ):Vector; + + /** + * Normalises a vector (such that its magnitude is 1). + * + * @param vector + * @returns A new vector normalised + */ + static normalise ( vector:Vector ):Vector; + + /** + * Returns the perpendicular vector. Set negate to true for the perpendicular in the opposite direction. + * + * @param vector + * @param negate + * @returns The perpendicular vector + */ + static perp ( vector:Vector, negate?:boolean ):Vector; + + /** + * Rotates the vector about (0, 0) by specified angle. + * + * @param vector + * @param angle + * @returns A new vector rotated about (0, 0) + */ + static rotate ( vector:Vector, angle:number ):Vector; + + /** + * Rotates the vector about a specified point by specified angle. + * + * @param vector + * @param angle + * @param point + * @returns A new vector rotated about the point + */ + static rotateAbout ( vector:Vector, angle:number, point:Vector ):Vector; + + /** + * Subtracts the two vectors. + * + * @param vectorA + * @param vectorB + * @returns A new vector of vectorA and vectorB subtracted + */ + static sub ( vectorA:Vector, vectorB:Vector ):Vector; + } + + export class Constraint + { + /** + * Creates a new constraint. All properties have default values, and many are pre-calculated automatically based on other properties. See the properites section below for detailed information on what you can pass via the options object. + * + * @param options + * @returns constraint + */ + static create(options:IConstraintDefinition):Constraint; + + /** + * The first possible Body that this constraint is attached to. + */ + bodyA:Body; + + /** + * The second possible Body that this constraint is attached to. + */ + bodyB:Body; + + /** + * An integer Number uniquely identifying number generated in Composite.create by Common.nextId. + */ + id:number; + + /** + * An arbitrary String name to help the user identify and manage bodies. + * Default: "Constraint" + */ + label:string; + + /** + * A Number that specifies the target resting length of the constraint. It is calculated automatically in Constraint.create from intial positions of the constraint.bodyA and constraint.bodyB. + */ + length:number; + + /** + * A Vector that specifies the offset of the constraint from center of the constraint.bodyA if defined, otherwise a world-space position. + Default: { x: 0, y: 0 } + */ + pointA:Vector; + + /** + * A Vector that specifies the offset of the constraint from center of the constraint.bodyA if defined, otherwise a world-space position. + Default: { x: 0, y: 0 } + */ + pointB:Vector; + + /** + * An Object that defines the rendering properties to be consumed by the module Matter.Render. + */ + render:IConstraintRenderRefinition; + + /** + * A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting constraint.length. A value of 1 means the constraint should be very stiff. A value of 0.2 means the constraint acts like a soft spring. + Default: 1 + */ + stiffness:number; + + /** + * A String denoting the type of object. + Default: "constraint" + */ + type:string; + } + + export class MouseConstraint + { + create(engine:Engine, options:IMouseConstraintDefinition):MouseConstraint; + + /** + * The Constraint object that is used to move the body during interaction. + */ + constraint:Constraint; + + /** + * The Body that is currently being moved by the user, or null if no body. + Default: null + */ + dragBody:Body; + + /** + * The Vector offset at which the drag started relative to the dragBody, if any. + Default: null + */ + dragPoint:Vector; + + /** + * The Mouse instance in use. + Default: engine.input.mouse + */ + mouse:Mouse; + + /** + * A String denoting the type of object. + Default: "constraint" + */ + type:string; + } + + export interface IMouseConstraintDefinition + { + /** + * The Constraint object that is used to move the body during interaction. + */ + constraint?:Constraint; + + /** + * The Body that is currently being moved by the user, or null if no body. + Default: null + */ + dragBody?:Body; + + /** + * The Vector offset at which the drag started relative to the dragBody, if any. + Default: null + */ + dragPoint?:Vector; + + /** + * The Mouse instance in use. + Default: engine.input.mouse + */ + mouse?:Mouse; + + /** + * A String denoting the type of object. + Default: "constraint" + */ + type?:string; + } + + export class Query + { + /** + * Casts a ray segment against a set of bodies and returns all collisions, ray width is optional. Intersection points are not provided. + * + * @param bodies + * @param startPoint + * @param endPoint + * @param [rayWidth] + * + * @returns Object[] Collisions + */ + static ray( bodies:Array, startPoint:Vector, endPoint:Vector, rayWidth?:number ):Array; + + /** + * Returns all bodies whose bounds are inside (or outside if set) the given set of bounds, from the given set of bodies. + * + * @param bodies + * @param bounds + * @returns Body[] The bodies matching the query + */ + static region( bodies:Array, bounds:Bounds, outside?:boolean ):Array; + } + + export class Mouse + { + + } + + export interface IConstraintRenderRefinition + { + /** + * A Number that defines the line width to use when rendering the constraint outline. A value of 0 means no outline will be rendered. + Default: 2 + */ + lineWidth:number; + + /** + * A String that defines the stroke style to use when rendering the constraint outline. It is the same as when using a canvas, so it accepts CSS style property values. + Default: a random colour + */ + strokeStyle:string; + + /** + * A flag that indicates if the constraint should be rendered. + Default: true + */ + visible:boolean; + } + + export interface IConstraintDefinition + { + /** + * The first possible Body that this constraint is attached to. + */ + bodyA?:Body; + + /** + * The second possible Body that this constraint is attached to. + */ + bodyB?:Body; + + /** + * An integer Number uniquely identifying number generated in Composite.create by Common.nextId. + */ + id?:number; + + /** + * An arbitrary String name to help the user identify and manage bodies. + * Default: "Constraint" + */ + label?:string; + + /** + * A Number that specifies the target resting length of the constraint. It is calculated automatically in Constraint.create from intial positions of the constraint.bodyA and constraint.bodyB. + */ + length?:number; + + /** + * A Vector that specifies the offset of the constraint from center of the constraint.bodyA if defined, otherwise a world-space position. + Default: { x: 0, y: 0 } + */ + pointA?:Vector; + + /** + * A Vector that specifies the offset of the constraint from center of the constraint.bodyA if defined, otherwise a world-space position. + Default: { x: 0, y: 0 } + */ + pointB?:Vector; + + /** + * An Object that defines the rendering properties to be consumed by the module Matter.Render. + */ + render?:IConstraintRenderRefinition; + + /** + * A Number that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting constraint.length. A value of 1 means the constraint should be very stiff. A value of 0.2 means the constraint acts like a soft spring. + Default: 1 + */ + stiffness?:number; + + /** + * A String denoting the type of object. + Default: "constraint" + */ + type?:string; + } + + export class Composite + { + /** + * Generic add function. Adds one or many body(s), constraint(s) or a composite(s) to the given composite. + * + * @param composite + * @param object + * + * @returns The original composite with the objects added + */ + static add(composite:Composite, object:Body|Composite|Constraint ):Composite; + + /** + * Adds a body to the given composite + * + * @param composite + * @param body + * + * @returns Composite The original composite with the body added + */ + static addBody(composite:Composite, body:Body):Composite; + + /** + * Adds a composite to the given composite + * + * @param compositeA + * @param compositeB + * + * @returns The original compositeA with the objects from compositeB added + */ + static addComposite(compositeA:Composite, compositeB:Composite):Composite; + + /** + * + * @param composite + * @param constraint + * @returns The original composite with the constraint added + */ + static addConstraint(composite:Composite, constraint:Constraint):Composite; + + /** + * Returns all bodies in the given composite, including all bodies in its children, recursively. + * + * @param composite + * @returns Body[] All the bodies + */ + static allBodies(composite:Composite):Array; + + /** + * Returns all composites in the given composite, including all composites in its children, recursively. + * + * @param composite + * @returns Composite[] All the composites + */ + static allComposites(composite:Composite):Array; + + /** + * Returns all constraints in the given composite, including all constraints in its children, recursively. + * + * @param composite + * @returns Constraint[] All the constraints + */ + static allConstraints(composite:Composite):Array; + + /** + * Removes all bodies, constraints and composites from the given composite Optionally clearing its children recursively. + * + * @param world + * @param keepStatic + * @param deep + */ + static clear(world:World, keepStatic:boolean, deep?:boolean):void; + + /** + * Creates a new composite. The options parameter is an object that specifies any properties you wish to override the defaults. See the properites section below for detailed information on what you can pass via the options object. + * + * @param options + * @returns A new composite + */ + static create(options:ICompositeDefinition):Composite; + + /** + * Searches the composite recursively for an object matching the type and id supplied, null if not found + * + * @param composite + * @param id + * @param type + * @returns The requested object, if found. + */ + static get(composite:Composite,id:number,type:string):Body|Composite|Constraint; + + /** + * Moves the given object(s) from compositeA to compositeB (equal to a remove followed by an add) + * + * @param compositeA + * @param objects + * @param compositeB + * @returns Returns compositeA + */ + static move(compositeA:Composite, objects:Array, compositeB:Composite):Composite; + + /** + * Assigns new ids for all objects in the composite, recursively. + * + * @param composite + * @returns Returns composite + */ + static rebase(composite:Composite):Composite; + + /** + * Generic remove function. Removes one or many body(s), constraint(s) or a composite(s) to the given composite. Optionally searching its children recursively. + * + * @param composite + * @param object + * @param deep + * @returns The original composite with the objects removed. + */ + static remove(composite:Composite, object:Body|Composite|Constraint, deep?:boolean):Composite; + + /** + * Removes a body from the given composite, and optionally searching its children recursively. + * + * @param composite + * @param body + * @param deep + * @returns The original composite with the body removed. + */ + static removeBody(composite:Composite, body:Body, deep?:boolean):Composite; + + /** + * Removes a body from the given composite. + * + * @param composite + * @param position + * @returns The original composite with the body removed. + */ + static removeBodyAt(composite:Composite, position:number):Composite; + + /** + * Removes a composite from the given composite, and optionally searching its children recursively + * + * @param compositeA + * @param compositeB + * @returns The original compositeA with the composite removed. + */ + static removeComposite(compositeA:Composite, compositeB:Composite, deep?:boolean):Composite; + + /** + * Removes a composite from the given composite + * + * @param composite + * @param position + * @returns The original composite with the composite removed. + */ + static removeCompositeAt(composite:Composite, position:number):Composite; + + /** + * Removes a constraint from the given composite, and optionally searching its children recursively + * + * @param composite + * @param constraint + * @param deep + * + * @returns The original composite with the constraint removed + */ + static removeConstraint(composite:Composite, constraint:Constraint, deep?:boolean):Composite; + + /** + * Removes a body from the given composite + * @param composite + * @param position + * @returns The original composite with the constraint removed + */ + static removeConstraintAt(composite:Composite, position:number):Composite; + + /** + * Sets the composite's isModified flag. If updateParents is true, all parents will be set (default: false). If updateChildren is true, all children will be set (default: false). + * + * @param composite + * @param isModified + * @param updateParents + */ + static setModified(composite:Composite, isModified:boolean, updateParents?:boolean):void; + + /** + * An array of Body that are direct children of this composite. To add or remove bodies you should use Composite.add and Composite.remove methods rather than directly modifying this property. If you wish to recursively find all descendants, you should use the Composite.allBodies method. + */ + bodies:Array; + + /** + * An array of Composite that are direct children of this composite. To add or remove composites you should use Composite.add and Composite.remove methods rather than directly modifying this property. If you wish to recursively find all descendants, you should use the Composite.allComposites method. + */ + composites:Array; + + /** + * An array of Constraint that are direct children of this composite. To add or remove constraints you should use Composite.add and Composite.remove methods rather than directly modifying this property. If you wish to recursively find all descendants, you should use the Composite.allConstraints method. + */ + constraints:Array; + + /** + * An integer Number uniquely identifying number generated in Composite.create by Common.nextId. + */ + id:number; + + /** + * A flag that specifies whether the composite has been modified during the current step. Most Matter.Composite methods will automatically set this flag to true to inform the engine of changes to be handled. If you need to change it manually, you should use the Composite.setModified method. + */ + isModified:boolean; + + /** + * An arbitrary String name to help the user identify and manage composites. + * Default: "Composite" + */ + label:string; + + /** + * The Composite that is the parent of this composite. It is automatically managed by the Matter.Composite methods. + */ + parent:Composite; + + /** + * A String denoting the type of object. + */ + type:String; + + } + + export class Composites + { + /** + * It will create car composite, wheels, car body and constraints. + * + * @param xx + * @param yy + * @param width + * @param height + * @param wheelSize + * + * @returns A new composite car body + */ + static car ( xx:number, yy:number, width:number, height:number, wheelSize:number ):Composite; + + /** + * Creates chain + * @param composite + * @param xOffsetA + * @param yOffsetA + * @param xOffsetB + * @param yOffsetB + * @param options + */ + static chain ( composite:Composite, xOffsetA:number, yOffsetA:number, xOffsetB:number, yOffsetB:number, options:any ):Composite; + + /** + *Connects bodies in the composite with constraints in a grid pattern, with optional cross braces + * + * @param composite + * @param columns + * @param rows + * @param crossBrace + * @param options + * @returns The composite containing objects meshed together with constraints + */ + static mesh(composite:Composite, columns:number, rows:number, crossBrace:boolean, options:any ):Composite; + + /** + * Creates newton cradle + * @param xx + * @param yy + * @param _number + * @param size + * @param length + * @returns A new composite newtonsCradle body + */ + newtonsCradle(xx:number, yy:number, _number:number, size:number, length:number):Composite; + + /** + * Creates pyramid + * + * @param xx + * @param yy + * @param columns + * @param rows + * @param columnGap + * @param rowGap + * @param callback + * @return A new composite containing objects created in the callback + */ + static pyramid(xx:number, yy:number, columns:number, rows:number, columnGap:number, rowGap:number, callback:Function):Composite; + + /** + * Creates a simple soft body like object + * + * @param xx + * @param yy + * @param columns + * @param rows + * @param columnGap + * @param rowGap + * @param crossBrace + * @param particleRadius + * @param particleOptions + * @param constraintOptions + * + * @returns A new composite softBody + */ + static softBody ( xx:number, yy:number, columns:number, rows:number, columnGap:number, rowGap:number, crossBrace:boolean, particleRadius:number, particleOptions:any, constraintOptions:any ):Composite; + + /** + * Creates objects in and stacks them up. + * @param xx + * @param yy + * @param columns + * @param rows + * @param columnGap + * @param rowGap + * @param callback + * @returns A new composite containing objects created in the callback + */ + static stack ( xx:number, yy:number, columns:number, rows:number, columnGap:number, rowGap:number, callback:Function ):Composite; + } + + export interface ICompositeDefinition + { + /** + * An array of Body that are direct children of this composite. To add or remove bodies you should use Composite.add and Composite.remove methods rather than directly modifying this property. If you wish to recursively find all descendants, you should use the Composite.allBodies method. + */ + bodies?:Array; + + /** + * An array of Composite that are direct children of this composite. To add or remove composites you should use Composite.add and Composite.remove methods rather than directly modifying this property. If you wish to recursively find all descendants, you should use the Composite.allComposites method. + */ + composites?:Array; + + /** + * An array of Constraint that are direct children of this composite. To add or remove constraints you should use Composite.add and Composite.remove methods rather than directly modifying this property. If you wish to recursively find all descendants, you should use the Composite.allConstraints method. + */ + constraints?:Array; + + /** + * An integer Number uniquely identifying number generated in Composite.create by Common.nextId. + */ + id?:number; + + /** + * A flag that specifies whether the composite has been modified during the current step. Most Matter.Composite methods will automatically set this flag to true to inform the engine of changes to be handled. If you need to change it manually, you should use the Composite.setModified method. + */ + isModified?:boolean; + + /** + * An arbitrary String name to help the user identify and manage composites. + * Default: "Composite" + */ + label?:string; + + /** + * The Composite that is the parent of this composite. It is automatically managed by the Matter.Composite methods. + */ + parent?:Composite; + + /** + * A String denoting the type of object. + */ + type?:String; + } + + export class Vertices + { + /** + * Returns the area of the set of vertices. + * + * @param vertices + * @param signed + */ + static area ( vertices:Array, signed:boolean ):number; + + /** + * Returns the centre (centroid) of the set of vertices. + * @param vertices + * @returns The centre point + */ + static centre ( vertices:Array ):Vector; + + /** + * Chamfers a set of vertices by giving them rounded corners, returns a new set of vertices. The radius parameter is a single number or an array to specify the radius for each vertex. + * @param vertices + */ + static chamfer ( vertices:Array, radius:Array, quality:number, qualityMin:number, qualityMax:number ):void; + + + /** + * Returns true if the point is inside the set of vertices. + * + * @param vertices + * @returns True if the vertices contains point, otherwise false. + */ + static contains ( vertices:Array, point:Vector ):boolean; + + /** + * Creates a new set of Matter.Body compatible vertices. The vertices argument accepts an array of Matter.Vector orientated around the origin (0, 0), for example: + [{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }] + The Vertices.create method then inserts additional indexing properties required for efficient collision detection routines. + + * @param vertices + * @param body + */ + static create ( vertices:Array, body:Body):void; + + /** + * Parses a simple SVG-style path into a set of Matter.Vector points. + * + * @param path + * @returns vertices + */ + static fromPath ( path:string ):Array; + + /** + * Returns the moment of inertia (second moment of area) of the set of vertices given the total mass. + * + * @param vertices + * @returns The polygon's moment of inertia + */ + static inertia( vertices:Array, mass:number ):number; + + /** + * Rotates the set of vertices in-place. + * + * @param vertices + * @param angle + * @param point + */ + static static ( vertices:Array, angle:number, point:Vector ):void; + + /** + * Scales the vertices from a point (default is centre) in-place. + * + * @param vertices + * @param scaleX + * @param scaleY + * @param point + */ + static scale( vertices:Array, scaleX:number, scaleY:number, point:Vector ):void; + + /** + * Translates the set of vertices in-place. + * + * @param vertices + */ + static translate ( vertices:Array, vector:Vector, scalar:number ):void; + } + + export class Render + { + + } + + export class Events + { + /** + * Fired after rendering + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"afterRender", callback:(e:any) => void ):void; + + /** + * Fired after engine update and after rendering + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"afterUpdate", callback:(e:any) => void ):void; + + /** + * Fired just before rendering + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"beforeRender", callback:(e:any) => void ):void; + + /** + * Fired at the start of a tick, before any updates to the engine or timing + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"beforeTick", callback:(e:any) => void ):void; + + /** + * Fired just before an update + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"beforeUpdate", callback:(e:any) => void ):void; + + /** + * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"collisionActive", callback:(e:any) => void ):void; + + + /** + * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"collisionEnd", callback:(e:any) => void ):void; + + /** + * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"collisionStart", callback:(e:any) => void ):void; + + /** + * Fired when the mouse is down (or a touch has started) during the last step + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"mousedown", callback:(e:any) => void ):void; + + /** + * Fired when the mouse has moved (or a touch moves) during the last step + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"mousemove", callback:(e:any) => void ):void; + + /** + * Fired when the mouse is up (or a touch has ended) during the last step + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"mouseup", callback:(e:any) => void ):void; + + /** + * Fired after engine timing updated, but just before engine state updated + * @param obj + * @param name + * @param callback + */ + static on(obj:Engine, name:"tick", callback:(e:any) => void ):void; + + static on(obj:Engine, name:string, callback:(e:any) => void ):void; + + /** + * Removes the given event callback. If no callback, clears all callbacks in eventNames. If no eventNames, clears all events. + * + * @param obj + * @param eventName + * @param callback + */ + static off(obj:any, eventName:string, callback: (e:any) => void ):void; + + /** + * Fires all the callbacks subscribed to the given object's eventName, in the order they subscribed, if any. + * + * @param object + * @param eventNames + * @param event + */ + static trigger( object:any, eventNames:string, event: (e:any) => void ):void; + + } +} diff --git a/meteor/meteor-tests.ts b/meteor/meteor-tests.ts index ec2ad3b81..f26527911 100644 --- a/meteor/meteor-tests.ts +++ b/meteor/meteor-tests.ts @@ -272,7 +272,7 @@ Posts.allow({ Posts.deny({ update: function (userId, docs, fields, modifier) { // can't change owners - return docs.userId = userId; + return docs.userId !== userId; }, remove: function (userId, doc) { // can't remove locked documents diff --git a/meteor/meteor.d.ts b/meteor/meteor.d.ts index 4118fbe06..ed0c97b29 100644 --- a/meteor/meteor.d.ts +++ b/meteor/meteor.d.ts @@ -16,17 +16,17 @@ interface JSONable { interface EJSON extends EJSONable {} declare module Match { - var Any; - var String; - var Integer; - var Boolean; - var undefined; + var Any:any; + var String:any; + var Integer:any; + var Boolean:any; + var undefined:any; //function null(); // not allowed in TypeScript - var Object; - function Optional(pattern):boolean; - function ObjectIncluding(dico):boolean; - function OneOf(...patterns); - function Where(condition); + var Object:any; + function Optional(pattern:any):boolean; + function ObjectIncluding(dico:any):boolean; + function OneOf(...patterns:any[]):any; + function Where(condition:any):any; } declare module Meteor { @@ -89,8 +89,8 @@ declare module Meteor { } interface Tinytest { - add(name:string, func:Function); - addAsync(name:string, func:Function); + add(name:string, func:Function):any; + addAsync(name:string, func:Function):any; } enum StatusEnum { @@ -145,9 +145,9 @@ declare module Mongo { MONGO } interface AllowDenyOptions { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; + insert?: (userId:string, doc:any) => boolean; + update?: (userId:string, doc:any, fieldNames:string[], modifier:any) => boolean; + remove?: (userId:string, doc:any) => boolean; fetch?: string[]; transform?: Function; } @@ -184,10 +184,10 @@ declare module HTTP { declare module Email { interface EmailMessage { from: string; - to: any; // string or string[] - cc?: any; // string or string[] - bcc?: any; // string or string[] - replyTo?: any; // string or string[] + to: string|string[]; + cc?: string|string[]; + bcc?: string|string[]; + replyTo?: string|string[]; subject: string; text?: string; html?: string; @@ -197,14 +197,14 @@ declare module Email { declare module DDP { interface DDPStatic { - subscribe(name, ...rest); - call(method:string, ...parameters):void; - apply(method:string, ...parameters):void; - methods(IMeteorMethodsDictionary); + subscribe(name:string, ...rest:any[]):void; + call(method:string, ...parameters:any[]):void; + apply(method:string, ...parameters:any[]):void; + methods(IMeteorMethodsDictionary:any):any; status():DDPStatus; - reconnect(); - disconnect(); - onReconnect(); + reconnect():void; + disconnect():void; + onReconnect():void; } interface DDPStatus { @@ -344,7 +344,7 @@ declare module Accounts { declare module App { function accessRule(domainRule: string, options?: { launchExternal?: boolean; - }); /** TODO: add return value **/ + }):any; /** TODO: add return value **/ function configurePlugin(pluginName: string, config: Object): void; function icons(icons: Object): void; function info(options: { @@ -393,7 +393,7 @@ declare module Blaze { findAll(selector: string): Blaze.TemplateInstance[]; firstNode: Object; lastNode: Object; - subscribe(name: string, ...args): Meteor.SubscriptionHandle; + subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; subscriptionsReady(): boolean; view: Object; } @@ -475,7 +475,7 @@ declare module Meteor { wait?: boolean; onResultReceived?: Function; }, asyncCallback?: Function): any; - function call(name: string, ...args): any; + function call(name: string, ...args: any[]): any; function clearInterval(id: number): void; function clearTimeout(id: number): void; function disconnect(): void; @@ -503,7 +503,7 @@ declare module Meteor { var settings: {[id:string]: any}; function startup(func: Function): void; function status(): Meteor.StatusEnum; - function subscribe(name: string, ...args): Meteor.SubscriptionHandle; + function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; function user(): Meteor.User; function userId(): string; var users: Mongo.Collection; @@ -521,16 +521,16 @@ declare module Mongo { } interface Collection { allow(options: { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; + insert?: (userId:string, doc:any) => boolean; + update?: (userId:string, doc:any, fieldNames:string[], modifier:any) => boolean; + remove?: (userId:string, doc:any) => boolean; fetch?: string[]; transform?: Function; }): boolean; deny(options: { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; + insert?: (userId:string, doc:any) => boolean; + update?: (userId:string, doc:any, fieldNames:string[], modifier:any) => boolean; + remove?: (userId:string, doc:any) => boolean; fetch?: string[]; transform?: Function; }): boolean; @@ -684,30 +684,30 @@ interface CompileStepStatic { } interface CompileStep { addAsset(options: { - }, path: string, data: any /** Buffer **/ | string); /** TODO: add return value **/ + }, path: string, data: any /** Buffer **/ | string): any; /** TODO: add return value **/ addHtml(options: { section?: string; data?: string; - }); /** TODO: add return value **/ + }): any; /** TODO: add return value **/ addJavaScript(options: { path?: string; data?: string; sourcePath?: string; - }); /** TODO: add return value **/ + }): any; /** TODO: add return value **/ addStylesheet(options: { - }, path: string, data: string, sourceMap: string); /** TODO: add return value **/ - arch; /** TODO: add return value **/ - declaredExports; /** TODO: add return value **/ + }, path: string, data: string, sourceMap: string): any; /** TODO: add return value **/ + arch: any; /** TODO: add return value **/ + declaredExports: any; /** TODO: add return value **/ error(options: { - }, message: string, sourcePath?: string, line?: number, func?: string); /** TODO: add return value **/ - fileOptions; /** TODO: add return value **/ - fullInputPath; /** TODO: add return value **/ - inputPath; /** TODO: add return value **/ - inputSize; /** TODO: add return value **/ - packageName; /** TODO: add return value **/ - pathForSourceMap; /** TODO: add return value **/ + }, message: string, sourcePath?: string, line?: number, func?: string): any; /** TODO: add return value **/ + fileOptions: any; /** TODO: add return value **/ + fullInputPath: any; /** TODO: add return value **/ + inputPath: any; /** TODO: add return value **/ + inputSize: any; /** TODO: add return value **/ + packageName: any; /** TODO: add return value **/ + pathForSourceMap: any; /** TODO: add return value **/ read(n?: number): any; - rootOutputPath; /** TODO: add return value **/ + rootOutputPath: any; /** TODO: add return value **/ } declare var PackageAPI: PackageAPIStatic; @@ -777,5 +777,5 @@ interface Template { } declare function MethodInvocation(options: { -}); /** TODO: add return value **/ +}): any; /** TODO: add return value **/ declare function check(value: any, pattern: any): void; diff --git a/mocha/mocha-tests.ts b/mocha/mocha-tests.ts index dffd86e44..f90fefaf9 100644 --- a/mocha/mocha-tests.ts +++ b/mocha/mocha-tests.ts @@ -24,6 +24,18 @@ function test_context() { }); } +function test_suite() { + suite('some context', () => { }); + + suite.only('some context', () => { }); + + suite.skip('some context', () => { }); + + suite('some context', function() { + this.timeout(2000); + }); +} + function test_it() { it('does something', () => { }); @@ -39,6 +51,21 @@ function test_it() { }); } +function test_test() { + + test('does something', () => { }); + + test('does something', (done) => { done(); }); + + test.only('does something', () => { }); + + test.skip('does something', () => { }); + + test('does something', function () { + this.timeout(2000); + }); +} + function test_before() { before(() => { }); @@ -221,4 +248,4 @@ function test_run_withOnComplete() { instance.run((failures: number): void => { console.log(failures); }); -} \ No newline at end of file +} diff --git a/mocha/mocha.d.ts b/mocha/mocha.d.ts index 3f5d3e571..63ad66014 100644 --- a/mocha/mocha.d.ts +++ b/mocha/mocha.d.ts @@ -52,7 +52,7 @@ interface MochaDone { declare var mocha: Mocha; -declare var describe : { +declare var describe: { (description: string, spec: () => void): void; only(description: string, spec: () => void): void; skip(description: string, spec: () => void): void; @@ -60,12 +60,20 @@ declare var describe : { } // alias for `describe` -declare var context : { +declare var context: { (contextTitle: string, spec: () => void): void; only(contextTitle: string, spec: () => void): void; skip(contextTitle: string, spec: () => void): void; timeout(ms: number): void; -} +}; + +// alias for `describe` +declare var suite: { + (suiteTitle: string, spec: () => void): void; + only(suiteTitle: string, spec: () => void): void; + skip(suiteTitle: string, spec: () => void): void; + timeout(ms: number): void; +}; declare var it: { (expectation: string, assertion?: () => void): void; @@ -77,6 +85,17 @@ declare var it: { timeout(ms: number): void; }; +// alias for `it` +declare var test: { + (expectation: string, assertion?: () => void): void; + (expectation: string, assertion?: (done: MochaDone) => void): void; + only(expectation: string, assertion?: () => void): void; + only(expectation: string, assertion?: (done: MochaDone) => void): void; + skip(expectation: string, assertion?: () => void): void; + skip(expectation: string, assertion?: (done: MochaDone) => void): void; + timeout(ms: number): void; +}; + declare function before(action: () => void): void; declare function before(action: (done: MochaDone) => void): void; diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index 1b1d083ba..c5855c12c 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -188,6 +188,7 @@ moment(1318874398806).valueOf(); moment(1318874398806).unix(); moment([2000]).isLeapYear(); moment().zone(); +moment().utcOffset(); moment("2012-2", "YYYY-MM").daysInMonth(); moment([2011, 2, 12]).isDST(); diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index dc11eeac8..16490d2e1 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -188,6 +188,7 @@ moment(1318874398806).valueOf(); moment(1318874398806).unix(); moment([2000]).isLeapYear(); moment().zone(); +moment().utcOffset(); moment("2012-2", "YYYY-MM").daysInMonth(); moment([2011, 2, 12]).isDST(); diff --git a/moment/moment.d.ts b/moment/moment.d.ts index 834cc0462..e09aab1d5 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -224,7 +224,7 @@ declare module moment { diff(b: Moment): number; diff(b: Moment, unitOfTime: string): number; diff(b: Moment, unitOfTime: string, round: boolean): number; - + toArray(): number[]; toDate(): Date; toISOString(): string; @@ -235,6 +235,9 @@ declare module moment { zone(): number; zone(b: number): Moment; zone(b: string): Moment; + utcOffset(): number; + utcOffset(b: number): Moment; + utcOffset(b: string): Moment; daysInMonth(): number; isDST(): boolean; @@ -318,19 +321,27 @@ declare module moment { } - interface MomentLanguage { + interface BaseMomentLanguage { + months ?: any; + monthsShort ?: any; + weekdays ?: any; + weekdaysShort ?: any; + weekdaysMin ?: any; + relativeTime ?: MomentRelativeTime; + meridiem ?: (hour: number, minute: number, isLowercase: boolean) => string; + calendar ?: MomentCalendar; + ordinal ?: (num: number) => string; + } - months?: any; - monthsShort?: any; - weekdays?: any; - weekdaysShort?: any; - weekdaysMin?: any; + interface MomentLanguage extends BaseMomentLanguage { longDateFormat?: MomentLongDateFormat; - relativeTime?: MomentRelativeTime; - meridiem?: (hour: number, minute: number, isLowercase: boolean) => string; - calendar?: MomentCalendar; - ordinal?: (num: number) => string; + } + interface MomentLanguageData extends BaseMomentLanguage { + /** + * @param formatType should be L, LL, LLL, LLLL. + */ + longDateFormat(formatType: string): string; } interface MomentLongDateFormat { @@ -412,7 +423,7 @@ declare module moment { locale(language?: string[]): string; locale(language?: string, definition?: MomentLanguage): string; - localeData(language?: string): MomentLanguage; + localeData(language?: string): MomentLanguageData; longDateFormat: any; relativeTime: any; diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 1c8b804d6..de68f006a 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -146,6 +146,9 @@ Model.remove((err: any, res: IActor[]) => {}); Model.save((err: any, res: IActor, numberAffected: number) => {}); Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {}); Model.create({ type: 'jawbreaker' }); +Model.create({ type: 'muffin' }).then(function (res) { + res.name; +}); Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {}); Model.distinct('url'); @@ -364,5 +367,14 @@ schema.virtual('display_name') .get(function(): string { return this.name; }) .set((value: string): void => {}); -var id : mongoose.Types.ObjectId; +var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId('foo'); +var id2: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(123); +var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromTime(123); +var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('foo'); var s = id.toHexString(); +var valid = id.isValid(); +var eq = id.equals(id2); + +var kitty1 = new Kitty({}); +var kitty2 = new Kitty({}); +var kittyEq = kitty1._id.equals(kitty2._id); \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index fedd8fec6..29e167dcd 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -79,7 +79,13 @@ declare module "mongoose" { } export module Types { export class ObjectId { - toHexString(): string; + constructor(id: string|number); + toHexString(): string; + equals(other: ObjectId): boolean; + getTimestamp(): Date; + isValid(): boolean; + static createFromTime(time: number): ObjectId; + static createFromHexString(hexString: string): ObjectId; } } @@ -137,7 +143,7 @@ declare module "mongoose" { aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; count(conditions: Object, callback?: (err: any, count: number) => void): Query; - create(doc: Object, fn?: (err: any, res: T) => void): Promise; + create(doc: Object, fn?: (err: any, res: T) => void): Promise; create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; discriminator(name: string, schema: Schema): Model; @@ -374,7 +380,7 @@ declare module "mongoose" { export interface Document { id?: string; - _id: string; + _id: Types.ObjectId; equals(doc: Document): boolean; get(path: string, type?: new(...args: any[]) => any): any; diff --git a/ng-i18next/ng-i18next-tests.ts b/ng-i18next/ng-i18next-tests.ts new file mode 100644 index 000000000..243a39865 --- /dev/null +++ b/ng-i18next/ng-i18next-tests.ts @@ -0,0 +1,8 @@ +/// +/** +* @summary Test for "ng-i18next" with options. +*/ +function testOptions() { + var $provider: angular.i18next.I18nextProvider; + $provider.options = {}; +} diff --git a/ng-i18next/ng-i18next.d.ts b/ng-i18next/ng-i18next.d.ts new file mode 100644 index 000000000..33af5c42c --- /dev/null +++ b/ng-i18next/ng-i18next.d.ts @@ -0,0 +1,12 @@ +// Type definitions for i18next v0.3.6 +// Project: https://github.com/i18next/ng-i18next +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular.i18next { + interface I18nextProvider { + options: I18nextOptions; + } +} \ No newline at end of file diff --git a/node-gcm/node-gcm-tests.ts b/node-gcm/node-gcm-tests.ts new file mode 100644 index 000000000..b184949ed --- /dev/null +++ b/node-gcm/node-gcm-tests.ts @@ -0,0 +1,72 @@ +/// + +import gcm = require('node-gcm'); + +// Create a message +// ... with default values +var message = new gcm.Message(); + +// ... or some given values +var message = new gcm.Message({ + collapseKey: 'demo', + delayWhileIdle: true, + timeToLive: 3, + data: { + key1: 'message1', + key2: 'message2' + } +}); + +// Change the message data +// ... as key-value +message.addData('key1','message1'); +message.addData('key2','message2'); + +// ... or as a data object (overwrites previous data object) +message.addData({ + key1: 'message1', + key2: 'message2' +}); + +// Change the message variables +message.collapseKey = 'demo'; +message.delayWhileIdle = true; +message.timeToLive = 3; +message.dryRun = true; + +// Set up the sender with you API key +var sender = new gcm.Sender('insert Google Server API Key here'); + +// Add the registration IDs of the devices you want to send to +var registrationIds: string[] = []; +registrationIds.push('regId1'); +registrationIds.push('regId2'); + +// Send the message +// ... trying only once +sender.sendNoRetry(message, registrationIds, (err, result) => { + if (err) { + console.error(err); + } else { + console.log(result); + } +}); + +// ... or retrying +sender.send(message, registrationIds, (err, result) => { + if (err) { + console.error(err); + } else { + console.log(result); + } +}); + +// ... or retrying a specific number of times (10) +sender.send(message, registrationIds, 10, (err, result) => { + if (err) { + console.error(err); + } else { + console.log(result); + } +}); + diff --git a/node-gcm/node-gcm.d.ts b/node-gcm/node-gcm.d.ts new file mode 100644 index 000000000..3272acac4 --- /dev/null +++ b/node-gcm/node-gcm.d.ts @@ -0,0 +1,62 @@ +// Type definitions for node-gcm 0.9.15 +// Project: https://www.npmjs.org/package/node-gcm +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "node-gcm" { + + export interface IMessageOptions { + collapseKey?: string; + delayWhileIdle?: boolean; + timeToLive?: number; + dryRun?: boolean; + } + + export class Message { + constructor(options?: IMessageOptions); + collapseKey: string; + delayWhileIdle: boolean; + timeToLive: number; + dryRun: boolean; + + addData(key: string, value: string): void; + addData(data: any): void; + } + + + export interface ISenderOptions { + proxy?: any; + maxSockets?: number; + timeout?: number; + } + export interface ISenderSendOptions { + retries?: number; + backoff?: number; + } + + export class Sender { + constructor(key: string, options?: ISenderOptions); + key: string; + options: ISenderOptions; + + send(message: Message, registrationIds: string|string[], callback: (err: any, resJson: IResponseBody) => void): void; + send(message: Message, registrationIds: string|string[], retries: number, callback: (err: any, resJson: IResponseBody) => void): void; + send(message: Message, registrationIds: string|string[], options: ISenderSendOptions, callback: (err: any, resJson: IResponseBody) => void): void; + sendNoRetry(message: Message, registrationIds: string|string[], callback: (err: any, resJson: IResponseBody) => void): void; + } + + + export interface IResponseBody { + success: number; + failure: number; + canonical_ids: number; + multicast_id?: number; + results?: { + message_id?: string; + registration_id?: string; + error?: string; + }[]; + } + +} + diff --git a/node/node.d.ts b/node/node.d.ts index b0a7b77e5..2543ccaca 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -252,6 +252,7 @@ declare module NodeJS { setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; undefined: typeof undefined; unescape: (str: string) => string; + gc: () => void; } export interface Timer { diff --git a/papaparse/papaparse-tests.ts b/papaparse/papaparse-tests.ts new file mode 100644 index 000000000..14cc40bb3 --- /dev/null +++ b/papaparse/papaparse-tests.ts @@ -0,0 +1,55 @@ +/// + +import Papa = require("papaparse"); + +/** + * Parsing + */ +var res = Papa.parse("3,3,3"); + +res.errors[0].code; + +Papa.parse("3,3,3", { + delimiter: ';', + comments: false, + + step: function(results, p) { + p.abort(); + results.data.length; + } +}); + +var file = new File(); + +Papa.parse(file, { + complete: function(a, b) { + a.meta.fields; + b.name; + } +}); + +/** + * Unparsing + */ +Papa.unparse([{a: 1, b: 1, c: 1}]); +Papa.unparse([[1, 2, 3], [4, 5, 6]]); +Papa.unparse({ + fields: ["3"], + data: [] +}); + + + +/** + * Properties + */ +Papa.SCRIPT_PATH; +Papa.LocalChunkSize; + +/** + * Parser + */ +var parser = new Papa.Parser({}) +parser.getCharIndex(); +parser.abort(); +parser.parse("", 0, false); \ No newline at end of file diff --git a/papaparse/papaparse.d.ts b/papaparse/papaparse.d.ts new file mode 100644 index 000000000..028dd2aab --- /dev/null +++ b/papaparse/papaparse.d.ts @@ -0,0 +1,144 @@ +// Type definitions for PapaParse v4.1 +// Project: https://github.com/mholt/PapaParse +// Definitions by: Pedro Flemming +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module PapaParse { + interface Static { + /** + * Parse a csv string or a csv file + */ + parse(csvString: string, config?: ParseConfig): ParseResult; + + parse(file: File, config?: ParseConfig): ParseResult; + + /** + * Unparses javascript data objects and returns a csv string + */ + unparse(data: Array, config?: UnparseConfig): string; + + unparse(data: Array>, config?: UnparseConfig): string; + + unparse(data: UnparseObject, config?: UnparseConfig): string; + + /** + * Read-Only Properties + */ + // An array of characters that are not allowed as delimiters. + BAD_DELIMETERS: Array; + + // The true delimiter. Invisible. ASCII code 30. Should be doing the job we strangely rely upon commas and tabs for. + RECORD_SEP: string; + + // Also sometimes used as a delimiting character. ASCII code 31. + UNIT_SEP: string; + + // Whether or not the browser supports HTML5 Web Workers. If false, worker: true will have no effect. + WORKERS_SUPPORTED: boolean; + + // The relative path to Papa Parse. This is automatically detected when Papa Parse is loaded synchronously. + SCRIPT_PATH: string; + + /** + * Configurable Properties + */ + // The size in bytes of each file chunk. Used when streaming files obtained from the DOM that exist on the local computer. Default 10 MB. + LocalChunkSize: string; + + // Same as LocalChunkSize, but for downloading files from remote locations. Default 5 MB. + RemoteChunkSize: string; + + // The delimiter used when it is left unspecified and cannot be detected automatically. Default is comma. + DefaultDelimiter: string; + + /** + * On Papa there are actually more classes exposed + * but none of them are officially documented + * Since we can interact with the Parser from one of the callbacks + * I have included the API for this class. + */ + Parser: ParserConstructor; + } + + interface ParseConfig { + delimiter?: string; // default: "" + newline?: string; // default: "" + header?: boolean; // default: false + dynamicTyping?: boolean; // default: false + preview?: number; // default: 0 + encoding?: string; // default: "" + worker?: boolean; // default: false + comments?: boolean; // default: false + download?: boolean; // default: false + skipEmptyLines?: boolean; // default: false + fastMode?: boolean; // default: undefined + + // Callbacks + step?(results: ParseResult, parser: Parser): void; // default: undefined + complete?(results: ParseResult, file?: File): void; // default: undefined + error?(error: ParseError, file?: File): void; // default: undefined + chunk?(results: ParseResult, parser: Parser): void; // default: undefined + beforeFirstChunk?(chunk: string): string|void; // default: undefined + } + + interface UnparseConfig { + quotes: boolean; // default: false + delimiter: string; // default: "," + newline: string; // default: "\r\n" + } + + interface UnparseObject { + fields: Array; + data: string | Array; + } + + interface ParseError { + type: string; // A generalization of the error + code: string; // Standardized error code + message: string; // Human-readable details + row: number; // Row index of parsed data where error is + } + + interface ParseMeta { + delimiter: string; // Delimiter used + linebreak: string; // Line break sequence used + aborted: boolean; // Whether process was aborted + fields: Array; // Array of field names + truncated: boolean; // Whether preview consumed all input + } + + /** + * @interface ParseResult + * + * data: is an array of rows. If header is false, rows are arrays; otherwise they are objects of data keyed by the field name. + * errors: is an array of errors + * meta: contains extra information about the parse, such as delimiter used, the newline sequence, whether the process was aborted, etc. Properties in this object are not guaranteed to exist in all situations + */ + interface ParseResult { + data: Array; + errors: Array; + meta: ParseMeta; + } + + /** + * Parser + */ + interface ParserConstructor { new(config: ParseConfig): Parser; } + interface Parser { + // Parses the input + parse(input: string, baseIndex: number, ignoreLastRow: boolean): any; + + // Sets the abort flag + abort(): void; + + // Gets the cursor position + getCharIndex(): number; + } +} + +declare var Papa: PapaParse.Static; + +declare module "papaparse" { + var Papa: PapaParse.Static; + export = Papa; +} diff --git a/parse/parse.d.ts b/parse/parse.d.ts index 1aab10416..9f8df5c3f 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -842,7 +842,6 @@ declare module Parse { INVALID_CONTENT_LENGTH = 128, FILE_TOO_LARGE = 129, FILE_SAVE_ERROR = 130, - FILE_DELETE_ERROR = 153, DUPLICATE_VALUE = 137, INVALID_ROLE_NAME = 139, EXCEEDED_QUOTA = 140, @@ -851,6 +850,9 @@ declare module Parse { INVALID_IMAGE_DATA = 150, UNSAVED_FILE_ERROR = 151, INVALID_PUSH_TIME_ERROR = 152, + FILE_DELETE_ERROR = 153, + REQUEST_LIMIT_EXCEEDED = 155, + INVALID_EVENT_NAME = 160, USERNAME_MISSING = 200, PASSWORD_MISSING = 201, USERNAME_TAKEN = 202, @@ -860,6 +862,7 @@ declare module Parse { SESSION_MISSING = 206, MUST_CREATE_USER_THROUGH_SIGNUP = 207, ACCOUNT_ALREADY_LINKED = 208, + INVALID_SESSION_TOKEN = 209, LINKED_ID_MISSING = 250, INVALID_LINKED_SESSION = 251, UNSUPPORTED_SERVICE = 252, diff --git a/pickadate/pickadate-tests.ts b/pickadate/pickadate-tests.ts index 4700310b8..21bc5b074 100644 --- a/pickadate/pickadate-tests.ts +++ b/pickadate/pickadate-tests.ts @@ -1,279 +1,796 @@ -/// -/// +/// -function testApiMethods(api: Pickadate.Api) { - api.clear(); - api.close(); - api.close(true); - api.get('value'); - api.get('value', 'yyyy-mm-dd'); - api.off('open'); - api.off('open', 'close', 'render'); - api.on('set', (context: {[key: string]: any}) => { }); - api.on('get', () => { }); - api.open(); - api.open(true); - api.render(); - api.render(true); - api.set('value', '2014-09-23'); - api.set({ - value: '2014-09-23', - max: new Date(2014, 12, 1) - }); - api.start(); - api.stop(); - api.trigger('open'); +// Date picker tests from http://amsul.ca/pickadate.js/date/ - api.start().open().close().stop(); +$('.datepicker').pickadate(); - var pickerInputElement = api.$node; - pickerInputElement.show(); - - var pickerRootElement = api.$root; - pickerRootElement.show(); -} - -function testDateApiMethods(api: Pickadate.DateApi) { - api.get('select'); - api.get('select', 'yyyy/mm/dd'); - api.get('highlight'); - api.get('highlight', 'yyyy/mm/dd'); - api.get('view'); - api.get('view', 'yyyy/mm/dd'); - api.get('min'); - api.get('min', 'yyyy/mm/dd'); - api.get('max'); - api.get('max', 'yyyy/mm/dd'); -} - -function testTimeApiMethods(api: Pickadate.TimeApi) { - api.get('select'); - api.get('select', 'hh:i'); - api.get('highlight'); - api.get('highlight', 'hh:i'); - api.get('view'); - api.get('view', 'hh:i'); - api.get('min'); - api.get('min', 'hh:i'); - api.get('max'); - api.get('max', 'hh:i'); -} - -// ==================================================================================================================== - -var datePickerInput = $("input.date"); - -datePickerInput.pickadate(); - -datePickerInput.pickadate({ - monthsFull: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], - monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], - weekdaysFull: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], - weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], - showMonthsShort: true, - showWeekdaysFull: true, - - today: 'Today', - clear: 'Clear', - close: 'Close', - - labelMonthNext: 'Next month', - labelMonthPrev: 'Previous month', - labelMonthSelect: 'Select a month', - labelYearSelect: 'Select a year', - - // Formats - format: 'd mmmm, yyyy', - formatSubmit: 'yyyy-mm-dd', - hiddenPrefix: 'foo', - hiddenSuffix: '_submit', - hiddenName: 'bar', - - // Editable input - editable: true, - - // Dropdown selectors - selectYears: true, - selectMonths: 10, - - // First day of the week - firstDay: 0, - - // Date limits - min: new Date(2013, 3, 20), - max: [2013, 7, 14], - - // Disable dates - disable: [ new Date(2013, 3, 21) ], - - // Root container - container: '.root-container', - - // Events - onStart: () => { }, - onRender: () => { }, - onOpen: () => { }, - onClose: () => { }, - onSet: (context: {[key: string]: any}) => { }, - onStop: () => { } +// Change the month and weekday labels +$('.datepicker').pickadate({ + weekdaysShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + showMonthsShort: true }); -datePickerInput.pickadate({ - klass: { - // The element states - input: 'picker__input', - active: 'picker__input--active', +// Change button text or hide a button completely +$('.datepicker').pickadate({ + today: '', + clear: 'Clear selection', + close: 'Cancel' +}); - // The root picker and states * - picker: 'picker', - opened: 'picker--opened', - focused: 'picker--focused', +// Change the title attributes of several elements within the picker +$('.datepicker').pickadate({ + labelMonthNext: 'Go to the next month', + labelMonthPrev: 'Go to the previous month', + labelMonthSelect: 'Pick a month from the dropdown', + labelYearSelect: 'Pick a year from the dropdown', + selectMonths: true, + selectYears: true +}); - // The picker holder - holder: 'picker__holder', +// Extend the default picker options for all instances. +$.extend($.fn.pickadate.defaults, { + monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], + weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], + today: 'aujourd\'hui', + clear: 'effacer', + formatSubmit: 'yyyy/mm/dd' +}); - // The picker frame, wrapper, and box - frame: 'picker__frame', - wrap: 'picker__wrap', - box: 'picker__box', +// Or, pass the months and weekdays as an array for each invocation. +$('.datepicker').pickadate({ + monthsFull: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'], + weekdaysShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], + today: 'aujourd\'hui', + clear: 'effacer', + formatSubmit: 'yyyy/mm/dd' +}); - // The picker header - header: 'picker__header', +// Display a human-friendly format and use an alternate one to submit to the server +$('.datepicker').pickadate({ + // Escape any "rule" characters with an exclamation mark (!). + format: 'You selecte!d: dddd, dd mmm, yyyy', + formatSubmit: 'yyyy/mm/dd', + hiddenPrefix: 'prefix__', + hiddenSuffix: '__suffix' +}); - // Month navigation - navPrev: 'picker__nav--prev', - navNext: 'picker__nav--next', - navDisabled: 'picker__nav--disabled', +// Send the hidden value only +$('.datepicker').pickadate({ + formatSubmit: 'yyyy/mm/dd', + hiddenName: true +}); - // Month & year labels - month: 'picker__month', - year: 'picker__year', +// Editable input +$('.datepicker').pickadate({ + editable: true +}); - // Month & year dropdowns - selectMonth: 'picker__select--month', - selectYear: 'picker__select--year', +// Display select menus to pick the month and year +$('.datepicker').pickadate({ + selectYears: true, + selectMonths: true +}); - // Table of dates - table: 'picker__table', +// Specify the number of years to show in the dropdown using an +// even integer - half before and half after the year in focus: +$('.datepicker').pickadate({ + // `true` defaults to 10. + selectYears: 4 +}); - // Weekday labels - weekdays: 'picker__weekday', +// The first day of the week can be set to either Sunday or Monday. +// Anything truth-y sets it as Monday and anything false-y as Sunday. +$('.datepicker').pickadate({ + firstDay: 1 +}); - // Day states - day: 'picker__day', - disabled: 'picker__day--disabled', - selected: 'picker__day--selected', - highlighted: 'picker__day--highlighted', - now: 'picker__day--today', - infocus: 'picker__day--infocus', - outfocus: 'picker__day--outfocus', +// Date Limits - // The picker footer - footer: 'picker__footer', +// Using JavaScript dates +$('.datepicker').pickadate({ + min: new Date(2013, 3, 20), + max: new Date(2013, 7, 14) +}); - // Today, clear, & close buttons - buttonClear: 'picker__button--clear', - buttonClose: 'picker__button--close', - buttonToday: 'picker__button--today' +// Using arrays formatted as [YEAR,MONTH,DATE] +$('.datepicker').pickadate({ + min: [2013, 3, 20], + max: [2013, 7, 14] +}); + +// Using integers or a boolean +$('.datepicker').pickadate({ + // An integer (positive/negative) sets it relative to today. + min: -15, + // `true` sets it to today. `false` removes any limits. + max: true +}); + +// Disable dates + +// Using JavaScript dates +$('.datepicker').pickadate({ + disable: [ + new Date(2013, 3, 13), + new Date(2013, 3, 29) + ] +}); + +// Using arrays formatted as [YEAR,MONTH,DATE] +$('.datepicker').pickadate({ + disable: [ + [2015, 3, 3], + [2015, 3, 12], + [2015, 3, 20] + ] +}); + +// Using integers as days of the week (1 to 7) +$('.datepicker').pickadate({ + disable: [ + 1, 4, 7 + ] +}); + +// Using objects as a range of dates +$('.datepicker').pickadate({ + disable: [ + { from: [2016, 2, 14], to: [2016, 2, 27] } + ] +}); + +// Enable only a specific or arbitrary set of dates by setting true as the first item in the collection +$('.datepicker').pickadate({ + disable: [ + true, + 1, 4, 7, + [2013, 3, 3], + [2013, 3, 12], + [2013, 3, 20], + new Date(2015, 3, 13), + new Date(2015, 3, 29) + ] +}); + +// Enable dates that fall within a range of disabled dates by adding +// the inverted parameter to the item within the collection +$('.datepicker').pickadate({ + disable: [ + 5, + [2015, 10, 21, 'inverted'], + { from: [2016, 3, 15], to: [2016, 3, 25] }, + [2016, 3, 20, 'inverted'], + { from: [2016, 3, 17], to: [2016, 3, 18], inverted: true } + ] +}); + +// Specify where to insert the root element by passing any valid CSS selector to the container option +$('.datepicker').pickadate({ + container: '#root-picker-outlet' +}); + +// Specify where to insert the hidden element by passing any valid CSS selector to the containerHidden option +$('.datepicker').pickadate({ + containerHidden: '#hidden-input-outlet' +}); + +// Close on a user action +$('.datepicker').pickadate({ + closeOnSelect: false, + closeOnClear: false +}); + +// Fire off events as the user interacts with the picker +$('.datepicker').pickadate({ + onStart: function () { + console.log('Hello there :)') + }, + onRender: function () { + console.log('Whoa.. rendered anew') + }, + onOpen: function () { + console.log('Opened up') + }, + onClose: function () { + console.log('Closed now') + }, + onStop: function () { + console.log('See ya.') + }, + onSet: function (context) { + console.log('Just set stuff:', context) } }); -var datePickerApi = datePickerInput.pickadate('picker'); +// Time picker tests from http://amsul.ca/pickadate.js/time/ -datePickerInput.pickadate('open'); -datePickerInput.pickadate('get', 'value'); -datePickerInput.pickadate('$node').show(); -datePickerInput.pickadate('$root').show(); -datePickerInput.pickadate('_hidden').show(); +$('.timepicker').pickatime(); -testApiMethods(datePickerApi); -testDateApiMethods(datePickerApi); +// Extend the default picker options for all instances. +$.extend($.fn.pickatime.defaults, { + clear: 'Effacer' +}); -// ==================================================================================================================== +// Or, pass the months and weekdays as an array for each invocation. +$('.timepicker').pickatime({ + clear: 'Effacer' +}); -var timePickerInput = $("input.time"); +// Change the text or hide the button completely by passing a false-y value +$('.timepicker').pickatime({ + clear: '' +}); -timePickerInput.pickatime(); - -timePickerInput.pickatime({ - // Translations and clear button - clear: 'Clear', - - // Formats - format: 'h:i A', +// Display a human-friendly label and input format and use an alternate one to submit +$('.timepicker').pickatime({ + // Escape any "rule" characters with an exclamation mark (!). + format: 'T!ime selected: h:i a', formatLabel: 'h:i a', formatSubmit: 'HH:i', hiddenPrefix: 'prefix__', - hiddenSuffix: '__suffix', - - // Editable input - editable: true, - - // Time intervals - interval: 30, - - // Time limits - min: new Date(2013, 3, 20, 7), - max: [7, 14], - - // Disable times - disable: [ new Date(2013, 3, 21, 7) ], - - // Root container - container: '.root-container', - - // Events - onStart: () => { }, - onRender: () => { }, - onOpen: () => { }, - onClose: () => { }, - onSet: (context: {[key: string]: any}) => { }, - onStop: () => { } + hiddenSuffix: '__suffix' }); -timePickerInput.pickatime({ - klass: { - // The element states - input: 'picker__input', - active: 'picker__input--active', - - // The root picker and states * - picker: 'picker picker--time', - opened: 'picker--opened', - focused: 'picker--focused', - - // The picker holder - holder: 'picker__holder', - - // The picker frame, wrapper, and box - frame: 'picker__frame', - wrap: 'picker__wrap', - box: 'picker__box', - - // List of times - list: 'picker__list', - listItem: 'picker__list-item', - - // Time states - disabled: 'picker__list-item--disabled', - selected: 'picker__list-item--selected', - highlighted: 'picker__list-item--highlighted', - viewset: 'picker__list-item--viewset', - now: 'picker__list-item--now', - - // Clear button - buttonClear: 'picker__button--clear' +// The formatLabel option is unique. It can contain HTML and it can also +// be a function if you want to create the label during run-time: +$('.timepicker').pickatime({ + formatLabel: function (time) { + var hours = (time.pick - this.get('now').pick) / 60, + label = hours < 0 ? ' !hours to now' : hours > 0 ? ' !hours from now' : 'now' + return 'h:i a ' + (hours ? Math.abs(hours) : '') + label + '' } }); -var timePickerApi = timePickerInput.pickatime('picker'); +// Send the hidden value only +$('.timepicker').pickatime({ + formatSubmit: 'HH:i', + hiddenName: true +}); -timePickerInput.pickatime('open'); -timePickerInput.pickatime('get', 'value'); -timePickerInput.pickatime('$node').show(); -timePickerInput.pickatime('$root').show(); -timePickerInput.pickatime('_hidden').show(); +// Editable input +$('.timepicker').pickatime({ + editable: true +}); -testApiMethods(timePickerApi); -testTimeApiMethods(timePickerApi); +// Choose the minutes interval between each time in the list +$('.timepicker').pickatime({ + interval: 150 +}); +// Time Limits + +// Using JavaScript dates +$('.timepicker').pickatime({ + min: new Date(2015, 3, 20, 7), + max: new Date(2015, 7, 14, 18, 30) +}); + +// Using arrays formatted as [HOUR,MINUTE] +$('.timepicker').pickatime({ + min: [7, 30], + max: [14, 0] +}); + +// Using integers or a boolean +$('.timepicker').pickatime({ + // An integer (positive/negative) sets it as intervals relative from now. + min: -5, + // `true` sets it to now. `false` removes any limits. + max: true +}); + +// Disable Times + +// Using JavaScript dates +$('.timepicker').pickatime({ + disable: [ + new Date(2016, 3, 20, 4, 30), + new Date(2016, 3, 20, 9) + ] +}); + +// Using arrays formatted as [HOUR,MINUTE] +$('.timepicker').pickatime({ + disable: [ + [0, 30], + [2, 0], + [8, 30], + [9, 0] + ] +}); + +// Using integers as hours (0 to 23) +$('.timepicker').pickatime({ + disable: [ + 3, 5, 7 + ] +}); + +// Using objects as a range of times +$('.timepicker').pickatime({ + disable: [ + { from: [2, 0], to: [5, 30] } + ] +}); + +// Enable only a specific or arbitrary set of times by setting true as the first item in the collection +$('.timepicker').pickatime({ + disable: [ + true, + 3, 5, 7, + [0, 30], + [2, 0], + [8, 30], + [9, 0] + ] +}); + +// Enable times that fall within a range of disabled times by adding +// the inverted parameter to the item within the collection +$('.timepicker').pickatime({ + disable: [ + 1, + [1, 30, 'inverted'], + { from: [4, 30], to: [10, 30] }, + [6, 30, 'inverted'], + { from: [8, 0], to: [9, 0], inverted: true } + ] +}); + +// Specify where to insert the root element by passing any valid CSS selector to the container option +$('.timepicker').pickatime({ + container: '#root-picker-outlet' +}); + +// Specify where to insert the hidden element by passing any valid CSS selector to the containerHidden option +$('.timepicker').pickatime({ + containerHidden: '#hidden-input-outlet' +}); + +// Close on a user action +$('.timepicker').pickatime({ + closeOnSelect: false, + closeOnClear: false +}); + +// Fire off events as the user interacts with the picker +$('.timepicker').pickatime({ + onStart: function () { + console.log('Hello there :)') + }, + onRender: function () { + console.log('Whoa.. rendered anew') + }, + onOpen: function () { + console.log('Opened up') + }, + onClose: function () { + console.log('Closed now') + }, + onStop: function () { + console.log('See ya.') + }, + onSet: function (context) { + console.log('Just set stuff:', context) + } +}); + +// API tests from http://amsul.ca/pickadate.js/api/ + +var $input = $('.datepicker').pickadate(); + +// Use the picker object directly. +var picker = $input.pickadate('picker'); + +picker.$node; +picker.$root; +picker._hidden; + +// Or pass through the element’s plugin data. +$input.pickadate('open'); +$input.pickadate('close'); +$input.pickadate('close'); +$input.pickadate('start'); +$input.pickadate('stop'); +$input.pickadate('render'); +$input.pickadate('get'); +$input.pickadate('set', 'highlight', 1429970887654); +$input.pickadate('on', 'open', function () { }); +$input.pickadate('on', 'close', function () { }); +$input.pickadate('off', 'open', 'close'); +$input.pickadate('trigger', 'open'); + +$input.pickadate('$node'); +$input.pickadate('$root'); +$input.pickadate('_hidden'); + +picker.open().clear().close(); + +picker.open(); +picker.close(); +picker.close(true); + +picker.open(false); +$(document).on('click', function () { + picker.close(); +}); + +picker.start(); +picker.stop(); +picker.render(); +picker.render(true); +picker.clear(); + +picker.get(); // Short for `picker.get('value')` + +picker.get('select'); +picker.get('select', 'yyyy/mm/dd'); + +picker.get('highlight'); +picker.get('highlight', 'yyyy/mm/dd'); + +picker.get('view'); +picker.get('view', 'yyyy/mm/dd'); + +picker.get('min'); +picker.get('min', 'yyyy/mm/dd'); +picker.get('max'); +picker.get('max', 'yyyy/mm/dd'); + +picker.get('open'); +picker.get('start'); +picker.get('id'); +picker.get('enable'); +picker.get('disable'); + +// Set multiple at once +picker.set({ + select: new Date(2015, 3, 20), + highlight: [2015, 3, 20], + min: -4 +}); + +// Muted callbacks + +// One at a time +picker.set('disable', 'flip', { muted: true }); + +// Multiple at once +picker.set({ + select: [1988, 7, 14], + view: new Date(1988, 7, 14), + max: 4 +}, { muted: true }); + +// Clear the value in the picker’s input element. +picker.set('clear'); + +// Set select for a date item object + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('select', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('select', new Date(2013, 3, 20)); + +// Using positive integers as UNIX timestamps. +picker.set('select', 1365961912346); + +// Using a string along with the parsing format (defaults to `format` option). +picker.set('select', '2016-04-20', { format: 'yyyy-mm-dd' }); + +// Set select for a time item object + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('select', [3, 0]); + +// Using JavaScript Date objects. +picker.set('select', new Date(2015, 3, 20, 10, 30)); + +// Using positive integers as minutes. +picker.set('select', 540); + +// Using a string along with the parsing format (defaults to `format` option). +picker.set('select', '04-30', { format: 'hh-i' }); + +// Set highlight for a date item object + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('highlight', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('highlight', new Date(2015, 3, 30)); + +// Using positive integers as UNIX timestamps. +picker.set('highlight', 1365961912346); + +// Using a string along with the parsing format (defaults to `format` option). +picker.set('highlight', '2016-04-20', { format: 'yyyy-mm-dd' }); + +// Set highlight for a time item object + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('highlight', [15, 30]); + +// Using JavaScript Date objects. +picker.set('highlight', new Date(2015, 3, 20, 10, 30)); + +// Using positive integers as minutes. +picker.set('highlight', 1080); + +// Using a string along with the parsing format (defaults to `format` option). +picker.set('highlight', '04-30', { format: 'hh-i' }); + +// Set view for a date item object + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('view', [2000, 3, 20]); + +// Using JavaScript Date objects. +picker.set('view', new Date(1988, 7, 14)); + +// Using positive integers as UNIX timestamps. +picker.set('view', 1587355200000); + +// Using a string along with the parsing format (defaults to `format` option). +picker.set('view', '2016-04-20', { format: 'yyyy-mm-dd' }); + +// Set view for a time item object + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('view', [15, 30]); + +// Using JavaScript Date objects. +picker.set('view', new Date(2015, 3, 20, 10, 30)); + +// Using positive integers as minutes. +picker.set('view', 1080); + +// Using a string along with the parsing format (defaults to `format` option). +picker.set('view', '04-30', { format: 'hh-i' }); + +// Limit the min date + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('min', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('min', new Date(2015, 7, 14)); + +// Using formatted strings. +picker.set('min', '8 January, 2016'); + +// Using integers as days relative to today. +picker.set('min', -4); + +// Using `true` for "today". +picker.set('min', true); + +// Using `false` to remove. +picker.set('min', false); + +// Limit the min time + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('min', [15, 30]); + +// Using JavaScript Date objects. +picker.set('min', new Date(2015, 3, 20, 10, 30)); + +// Using formatted strings. +picker.set('min', '4:30 PM'); + +// Using integers as intervals relative from now. +picker.set('min', -4); + +// Using `true` for "now". +picker.set('min', true); + +// Using `false` to remove. +picker.set('min', false); + +// Limit the max date + +// Using arrays formatted as [YEAR,MONTH,DATE]. +picker.set('max', [2013, 3, 20]); + +// Using JavaScript Date objects. +picker.set('max', new Date(2015, 7, 14)); + +// Using formatted strings. +picker.set('max', '20 April, 2016'); + +// Using integers as days relative to today. +picker.set('max', 4); + +// Using `true` for "today". +picker.set('max', true); + +// Using `false` to remove. +picker.set('max', false); + +// Limit the max time + +// Using arrays formatted as [HOUR,MINUTE]. +picker.set('max', [15, 30]); + +// Using JavaScript Date objects. +picker.set('max', new Date(2015, 3, 20, 10, 30)); + +// Using formatted strings. +picker.set('max', '11:30 AM'); + +// Using integers as intervals relative from now. +picker.set('max', 4); + +// Using `true` for "now". +picker.set('max', true); + +// Using `false` to remove. +picker.set('max', false); + +// Disable/enable specific dates +picker.set('disable', [ + // Using a collection of arrays formatted as [YEAR,MONTH,DATE] + [2016, 9, 3], [2016, 9, 9], [2016, 9, 20], + + // Using JavaScript Date objects + new Date(2015, 9, 13), new Date(2015, 9, 24) +]); + +picker.set('enable', [ + [2016, 9, 9], + [2016, 9, 13], + new Date(2015, 9, 20) +]); + +// Disable/enable ranges of dates +picker.set('disable', [ + 1, 4, 7, // Using integers as the days of the week (1 to 7) + + // Using a range object with a "from" and "to" property + { from: [2016, 2, 14], to: [2016, 2, 27] } +]); + +picker.set('enable', [ + 4, + { from: [2016, 2, 24], to: [2016, 2, 27] } +]); + +// "Flip" the enabled and disabled dates: +picker.set('disable', 'flip'); +picker.set('enable', 'flip'); + +// Disable all the dates +picker.set('disable', true); +picker.set('enable', false); + +// Enable all the dates +picker.set('enable', true); +picker.set('disable', false); + +// Disable/enable specific times +picker.set('disable', [ + // Using a collection of arrays formatted as [HOUR,MINUTES] + [2, 30], [4, 30], [9, 0], + + // Using JavaScript Date objects + new Date(2015, 9, 13, 6), new Date(2015, 9, 13, 12, 30) +]); + +picker.set('enable', [ + [4, 30], [6, 0], + new Date(2015, 9, 13, 9) +]); + +// Disable/enable ranges of times +picker.set('disable', [ + 1, 4, 7, // Using integers as hours of the day (from 0 to 23) + + // Using a range object with a “from” and “to” property + { from: [10, 30], to: [18, 0] } +]); + +picker.set('enable', [ + 4, + { from: [14, 0], to: [16, 30] } +]); + +// "Flip" the enabled and disabled times: +picker.set('disable', 'flip'); +picker.set('enable', 'flip'); + +// Disable all the times +picker.set('disable', true); +picker.set('enable', true); + +// Enable all the times +picker.set('enable', true); +picker.set('disable', false); + +// Enable an element within a disabled range + +picker.set('disable', [ + // Disable all Mondays, except November 15th, 2015. + 1, [2015, 10, 15, 'inverted'], + + // Disable all dates from March 2nd, 2016 to March 28th, 2016 + // except for March 10th and all between March 14th and March 23rd. + { from: [2016, 2, 2], to: [2016, 2, 28] }, + [2016, 2, 10, 'inverted'], + { from: [2016, 2, 14], to: [2016, 2, 23], inverted: true } +]); + +picker.set('disable', [ + // Disable all times from 1:00 AM to 1:59 AM, except 1:30 AM. + 1, [1, 30, 'inverted'], + + // Disable all times from 3:00 AM to 6:00 PM except + // for 4:30 AM and all between 7:30 AM and 11:30 AM. + { from: [3, 0], to: [18, 0] }, + [4, 30, 'inverted'], + { from: [7, 30], to: [11, 30], inverted: true } +]); + +// For the time picker only, you can change the interval between each time display +// using integers representing the interval length in minutes. +picker.set('interval', 15); +picker.set('interval', 20); +picker.set('interval', 120); + + +picker.on({ + open: function () { + console.log('Opened up!') + }, + close: function () { + console.log('Closed now') + }, + render: function () { + console.log('Just rendered anew') + }, + stop: function () { + console.log('See ya') + }, + set: function (thingSet) { + console.log('Set stuff:', thingSet) + } +}); + +$('.datepicker').pickadate({ + onOpen: function () { + console.log('Opened up!') + }, + onClose: function () { + console.log('Closed now') + }, + onRender: function () { + console.log('Just rendered anew') + }, + onStart: function () { + console.log('Hello there :)') + }, + onStop: function () { + console.log('See ya') + }, + onSet: function (thingSet) { + console.log('Set stuff:', thingSet) + } +}); + +picker.on('open', function () { + console.log('Even when I’m opened, I’m not logged..'); +}); +picker.off('open'); + +// Trigger an event’s callbacks that have been queued up +picker.on('open', function () { + console.log('This logs without opening!'); +}); +picker.trigger('open'); + +// Optionally, you can also pass some data to the method being triggered +picker.on('open', function (data) { + console.log('This logs without opening with this data:', data); +}); +picker.trigger('open', { some: 'value' }); diff --git a/pickadate/pickadate.d.ts b/pickadate/pickadate.d.ts index 1f96085f7..ac8e7b181 100644 --- a/pickadate/pickadate.d.ts +++ b/pickadate/pickadate.d.ts @@ -1,474 +1,545 @@ -// Type definitions for pickadate.js 3.5.4 +// Type definitions for pickadate.js 3.5.5 // Project: https://github.com/amsul/pickadate.js -// Definitions by: Adi Dahiya +// Definitions by: Theodore Brown // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module Pickadate { + // KlassOptions shared between date and time pickers + interface KlassOptions { + // The element states + input?: string; // default 'picker__input' + active?: string; // default 'picker__input--active' - export interface Api { - /** - * Clear the value in the picker's input element. - */ - clear(): Pickadate.Api; + // The root picker and states + picker?: string; // default 'picker' or 'picker picker--time' + opened?: string; // default 'picker--opened' + focused?: string; // default 'picker--focused' - /** - * Close the picker. - * - * @param keepFocus whether to retain focus on the input element (default: false) - */ - close(keepFocus?: boolean): Pickadate.Api; + // The picker holder + holder?: string; // default 'picker__holder' - /** - * Get the properties, objects, and states of the picker. - * - * @param field one of [ "value", "select", "highlight", "view", "min", "max", "open", "start", "id", "disable", "enable" ] - * @param format string formatter (available for certain fields) - */ - get(field: string, format?: string): any; + // The picker frame, wrapper, and box + frame?: string; // default 'picker__frame' + wrap?: string; // default 'picker__wrap' + box?: string; // default 'picker__box' - /** - * Returns the string value of the picker’s input element. - */ - get(field: "value"): string; + // Day/Time states + disabled?: string; // default 'picker__day--disabled' or 'picker__list-item--disabled' + selected?: string // default 'picker__day--selected' or 'picker__list-item--selected' + highlighted?: string // default 'picker__day--highlighted' or 'picker__list-item--highlighted' + now?: string; // default 'picker__day--today' or 'picker__list-item--now' - /** - * Returns a boolean value of whether the picker is open or not. - */ - get(field: "open"): boolean; - - /** - * Returns a boolean value of whether the picker has started or not. - */ - get(field: "start"): boolean; - - /** - * Returns a unique string that is the ID of the picker and it’s element. If the element has no ID, it is set to something random. - */ - get(field: "id"): string; - - /** - * "enable" and "disable" work together to determine which item objects to disable on the picker. - * - * "enable" returns 1 to represent a base enabled state, meaning that specific dates or times are disabled and all others are enabled; - * or -1 to indicate a base disabled state, meaning that specific dates or times are enabled and all others are disabled. - */ - get(field: "enable"): number; - - /** - * If "enable" is 1, returns the collection of dates or times to disable. If "enable" is -1, returns the collection of dates or - * times to *not* disable. - */ - get(field: "disable"): any; - - /** - * Unbind callbacks that are bound using the `on` method. - * @param methodName one of [ "open, "close", "render", "start", "stop", "set" ] - */ - off(methodName: string, ...moreMethodNames: string[]): Pickadate.Api; - - /** - * Attach an event handler for the picker. Only "set" events callbacks receive a "context" object. - * - * @param methodName event to attach handler to, one of [ "open", "close", "render", "start", "stop", or "set" ] - * @param callback event handler - */ - on(methodName: string, callback: (context?: any) => void): Pickadate.Api; - - /** - * Open the picker. - * - * @param keepFocus whether to focus the input element (default: true) - */ - open(keepFocus?: boolean): Pickadate.Api; - - /** - * Refresh the picker after adding something to the holder. - * By default, only the "face" of the picker (i.e. the box element), has its contents re-rendered. - * - * @param fromRoot whether to render the entire picker from the root up (default: false) - */ - render(fromRoot?: boolean): Pickadate.Api; - - /** - * Set the properties, objects, and states of the picker. - * - * @param field one of [ "clear", "select", "highlight", "view", "min", "max", "disable", "enable", "interval" ] - * @param value the thing you want to set - */ - set(field: string, value: any, options?: {[key: string]: any}): Pickadate.Api; - /** - * Batch set picker options after initialization. - */ - set(values: {[field: string]: any}, options?: {[key: string]: any}): Pickadate.Api; - - /** - * Rebuild the picker. - */ - start(): Pickadate.Api; - - /** - * Destroy the picker. - */ - stop(): Pickadate.Api; - - /** - * Trigger a picker event. - * @param eventName the event to trigger - */ - trigger(eventName: string): Pickadate.Api; - - /** - * The picker's relative element. - */ - $node: JQuery; - - /** - * The picker's relative root holder element. - */ - $root: JQuery; - - /** - * The picker's relative hidden element, which is undefined if there's no formatSubmit option. - * This is meant to be mostly for internal use. - */ - _hidden: JQuery; + // Clear button + buttonClear?: string; // default 'picker__button--clear' } - export interface DateApi extends Api { - get(field: string, format?: string): any; + interface DateKlassOptions extends KlassOptions { + // The picker header + header?: string; // default 'picker__header' - /** - * Returns the item object or formatted string of the date that is visually selected. - * Defaults to null when there’s no value. - */ - get(field: "select"): DateItem; - get(field: "select", format: string): string; + // Month navigation + navPrev?: string; // default 'picker__nav--prev' + navNext?: string; // default 'picker__nav--next' + navDisabled?: string; // default 'picker__nav--disabled' - /** - * Returns the item object or formatted string of the date that is visually highlighted. - * Defaults to "today" when there’s no value. - */ - get(field: "highlight"): DateItem; - get(field: "highlight", format: string): string; + // Month & year labels + month?: string; // default 'picker__month' + year?: string; // default 'picker__year' - /** - * Returns the item object or formatted string of the date that determines the current view. - * Defaults to the first day of the current month when there’s no value. - */ - get(field: "view"): DateItem; - get(field: "view", format: string): string; + // Month & year dropdowns + selectMonth?: string; // default 'picker__select--month' + selectYear?: string; // default 'picker__select--year' - /** - * Returns the item object or formatted string of the date that determines the lower limit. - * Defaults to a -Infinity item object when it is not explicitly set in the options or through the picker’s API. - */ - get(field: "min"): DateItem; - get(field: "min", format: string): string; + // Table of dates + table?: string; // default 'picker__table' - /** - * Returns the item object or formatted string of the date that determines the upper limit. - * Defaults to an Infinity item object when it is not explicitly set in the options or through the picker’s API. - */ - get(field: "max"): DateItem; - get(field: "max", format: string): string; + // Weekday labels + weekdays?: string; // default 'picker__weekday' + + // Day states + day?: string; // default 'picker__day' + infocus?: string; // default 'picker__day--infocus' + outfocus?: string; // default 'picker__day--outfocus' + + // The picker footer + footer?: string; // default 'picker__footer' + + // Today & close buttons + buttonClose?: string; // default 'picker__button--close' + buttonToday?: string; // default 'picker__button--today' } - export interface DateItem { - // The full year. - year: number; + interface TimeKlassOptions extends KlassOptions { + // The root picker + picker?: string; // default 'picker picker--time' - // The month with zero-as-index. - month: number; + // List of times + list?: string; // default 'picker__list' + listItem?: string; // default 'picker__list-item' - // The date of the month. - date: number; - - // The day of the week with zero-as-index. - day: number; - - // The underlying JavaScript Date object. - obj: Date; - - // The "pick" value used for comparisons. - pick: number; + // Time states + viewset?: string; // default 'picker__list-item--viewset' } - export interface DateOptions { - // String and translations - monthsFull?: string[]; - monthsShort?: string[]; - weekdaysFull?: string[]; - weekdaysShort?: string[] + // options shared between date and time pickers + interface Options { + /** + * Set the clear button text. + * Defaults to 'Clear' + */ + clear?: string; + + /** + * The human-friendly display format. + * Escape any "rule" characters with an exclamation mark (!). + * Defaults to 'd mmmm, yyyy' + */ + format?: string; + + /** + * An alternate format to submit to the server. + * Defaults to undefined. + */ + formatSubmit?: string; + + /** + * An optional name prefix for the new hidden input element used + * when a custom human-friendly display format is specified. + * Defaults to undefined. + */ + hiddenPrefix?: string; + + /** + * An optional name suffix for the new hidden input element used + * when a custom human-friendly display format is specified. + * Defaults to '_submit' + */ + hiddenSuffix?: string; + + /** + * A majority of the time, the value that needs to be sent to the server + * is just the hidden value and not the visible one. To make this happen, + * use the hiddenName option. This essentially nullifies the hiddenPrefix + * and hiddenSuffix, strips the name attribute from the source input, and + * then sets it as the name of the hidden input. Defaults to undefined. + */ + hiddenName?: boolean; + + /** + * By default, typing into the input is disabled by giving it a readOnly + * attribute. Setting the editable option to true allows the input field + * to be edited directly. + */ + editable?: boolean; + + /** + * Specify where to insert the picker's root element by passing any + * valid CSS selector to this option. Defaults to undefined. + */ + container?: string; + + /** + * The hidden input container. + * Defaults to undefined. + */ + containerHidden?: string; + + /** + * Whether or not to close the picker when a date is selected. + * Defaults to `true`. + */ + closeOnSelect?: boolean; + + /** + * Whether or not to close the picker when the "clear" button is pressed. + * Defaults to `true`. + */ + closeOnClear?: boolean; + + // Events + onStart?: (event: any) => void; + onRender?: (event: any) => void; + onOpen?: (event: any) => void; + onClose?: (event: any) => void; + onSet?: (event: any) => void; + onStop?: (event: any) => void; + } + + type MinOrMaxDateOption = Date | [number, number, number] | number | boolean; + type MinOrMaxTimeOption = Date | [number, number] | number | boolean; + + export interface DateOptions extends Options { + // Strings and translations + monthsFull?: string[]; // default 'January' through 'December' + monthsShort?: string[]; // default 'Jan' through 'Dec' + weekdaysFull?: string[]; // default 'Sunday' through 'Saturday' + weekdaysShort?: string[]; // default 'Sun' through 'Sat' showMonthsShort?: boolean; showWeekdaysFull?: boolean; - // Button labels (if falsy, the corresponding button is disabled) - today?: string; - clear?: string; - close?: string; + // Buttons + today?: string; // default 'Today' + close?: string; // default 'Close' // Accessibility labels - labelMonthNext?: string; - labelMonthPrev?: string; - labelMonthSelect?: string; - labelYearSelect?: string; + labelMonthNext?: string; // default 'Next month' + labelMonthPrev?: string; // default 'Previous month' + labelMonthSelect?: string; // default 'Select a month' + labelYearSelect?: string; //default 'Select a year' - // Formats - format?: string; - formatSubmit?: string; - hiddenPrefix?: string; - hiddenSuffix?: string; - hiddenName?: string; + /** + * True enables the dropdown selector and false replaces it with text. + * You can also specify the number of years to show in the dropdown + * using an even integer - half before and half after the year in focus. + * If true the value will default to 10. + */ + selectYears?: boolean | number; - // Editable input - editable?: boolean; + /** + * True enables the dropdown selector and false replaces it with text + */ + selectMonths?: boolean; - // Number of months to show in the month selection dropdown OR a boolean - selectMonths?: any; - // Number of years to show in the month selection dropdown OR a boolean - selectYears?: any; + /** + * The first day of the week can be set to either Sunday or Monday. + * True or 1 sets it as Monday and false or 0 as Sunday. + */ + firstDay?: boolean | number; - // First day of the week - firstDay?: number + /** + * Set the minimum selectable date on the picker. Accepts a Date object, + * array formatted as [YEAR, MONTH, DATE], a positive or negative integer + * for a date relative to today, or a boolean (`true` sets it to today, + * `false` removes any limit). + */ + min?: MinOrMaxDateOption; - // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + /** + * Set the maximum selectable date on the picker. + * Accepts the same values as the `min` property. + */ + max?: MinOrMaxDateOption; + + /** + * Disable a specific or arbitrary set of dates selectable on the + * picker. Accepts an array of Date objects, arrays formatted as + * [YEAR, MONTH, DATE], integers representing days of the week + * (from 1 to 7), or objects with a range of dates. Switch to a + * whitelist by setting `true` as the first item in the collection. + * Enable dates that fall within a range of disabled dates by + * adding an `inverted` parameter to the item within the collection. + */ disable?: any[]; - // Root container selector (string) or element (JQuery) - container?: any; - - // Events - onStart?: () => void; - onRender?: () => void; - onOpen?: () => void; - onClose?: () => void; - onSet?: (context: {[key: string]: any}) => void; - onStop?: () => void; - // Classes klass?: DateKlassOptions; } - export interface DateKlassOptions { - // The element states - input?: string; - active?: string; - - // The root picker and states - picker?: string; - opened?: string; - focused?: string; - - // The picker holder - holder?: string; - - // The picker frame, wrapper, and box - frame?: string; - wrap?: string; - box?: string; - - // The picker header - header?: string; - - // Month navigation - navPrev?: string; - navNext?: string; - navDisabled?: string; - - // Month & year labels - month?: string; - year?: string; - - // Month & year dropdowns - selectMonth?: string; - selectYear?: string; - - // Table of dates - table?: string; - - // Weekday labels - weekdays?: string; - - // Day states - day?: string; - disabled?: string; - selected?: string; - highlighted?: string; - now?: string; - infocus?: string; - outfocus?: string; - - // The picker footer - footer?: string; - - // Today, clear, & close buttons - buttonClear?: string; - buttonClose?: string; - buttonToday?: string - } - - export interface TimeApi extends Api { - get(field: string, format?: string): any; + export interface TimeOptions extends Options { + /** + * The formatLabel option is unique. It can contain HTML and it can + * also be a function if you want to create the label during run-time. + */ + formatLabel?: string | ((time: TimeItem) => string); /** - * Returns the item object or formatted string of the date that is visually selected. - * Defaults to null when there’s no value. - */ - get(field: "select"): TimeItem; - get(field: "select", format: string): string; - - /** - * Returns the item object or formatted string of the date that is visually highlighted. - * Defaults to "now" when there’s no value. - */ - get(field: "highlight"): TimeItem; - get(field: "highlight", format: string): string; - - /** - * Returns the item object or formatted string of the date that determines the current view. - * Defaults to "now" when there’s no value. - */ - get(field: "view"): TimeItem; - get(field: "view", format: string): string; - - /** - * Returns the item object or formatted string of the date that determines the lower limit. - * Defaults to a -Infinity item object when it is not explicitly set in the options or through the picker’s API. - */ - get(field: "min"): TimeItem; - get(field: "min", format: string): string; - - /** - * Returns the item object or formatted string of the date that determines the upper limit. - * Defaults to an Infinity item object when it is not explicitly set in the options or through the picker’s API. - */ - get(field: "max"): TimeItem; - get(field: "max", format: string): string; - } - - export interface TimeItem { - // Hour of the day from 0 to 23. - hour: number; - - // The minutes of the hour from 0 to 59 (based on the interval). - mins: number; - - // The "pick" value used for comparisons. - pick: number; - } - - export interface TimeOptions { - // Translations and clear button - clear?: string; - - // Formats - format?: string; - formatLabel?: string; - formatSubmit?: string; - hiddenPrefix?: string; - hiddenSuffix?: string; - - // Editable input - editable?: boolean; - - // Time intervals + * Choose the interval in minutes between each time in the list. + * Default is 30. + */ interval?: number; - // Time limits (can be Dates, arrays formatted as [HOUR, MINUTE], integers, or booleans) - min?: any; - max?: any; + /** + * Set the minimum selectable time on the picker. Accepts a Date object, + * array formatted as [HOUR, MINUTE], a positive or negative integer + * for a time relative to now, or a boolean (`true` sets it to now, and + * `false` removes any limit). + */ + min?: MinOrMaxTimeOption; - // Disable dates (elements can be Dates, [YEAR, MONTH, DATE] arrays, or integers of the week) + /** + * Set the maximum selectable time on the picker. + * Accepts the same values as the `min` property. + */ + max?: MinOrMaxTimeOption; + + /** + * Disable a specific or arbitrary set of times selectable on the picker. + * Accepts an array of Date objects, arrays formatted as [HOUR, MINUTE], + * integers representing hours (from 0 to 23), or objects with a range of + * times. Switch to a whitelist by setting `true` as the first item in the + * collection. Enable times that fall within a range of disabled times by + * adding an `inverted` parameter to the item within the collection. + */ disable?: any[]; - // Root container selector (string) or element (JQuery) - container?: any; - - // Events - onStart?: () => void; - onRender?: () => void; - onOpen?: () => void; - onClose?: () => void; - onSet?: (context: {[key: string]: any}) => void; - onStop?: () => void; - // Classes klass?: TimeKlassOptions; } - export interface TimeKlassOptions { - // The element states - input?: string; - active?: string; - - // The root picker and states - picker?: string; - opened?: string; - focused?: string; - - // The picker holder - holder?: string; - - // The picker frame, wrapper, and box - frame?: string; - wrap?: string; - box?: string; - - // List of times - list?: string; - listItem?: string; - - // Time states - disabled?: string; - selected?: string; - highlighted?: string; - viewset?: string; - now?: string; - - // Clear button - buttonClear?: string; + interface Item { + /** + * The "pick" value used for comparisons. + */ + pick: number; } + + export interface DateItem extends Item { + /** + * The full year. + */ + year: number; + + /** + * The month with zero-as-index. + */ + month: number; + + /** + * The date of the month. + */ + date: number; + + /** + * The day of the week with zero-as-index. + */ + day: number; + + /** + * The underlying JavaScript Date object. + */ + obj: Date; + } + + export interface TimeItem extends Item { + /** + * Hour of the day from 0 to 23. + */ + hour: number; + + /** + * The minutes of the hour from 0 to 59 (based on the interval). + */ + mins: number; + } + + export interface CallbackObject { + open?: () => void; + close?: () => void; + render?: () => void; + start?: () => void; + stop?: () => void; + set?: (thingSet: any) => void; + } + + export interface SetObject { + clear?: any; + select?: any; + highlight?: any; + view?: any; + min?: any; + max?: any; + disable?: any; + enable?: any; + } + + export interface TimeSetObject extends SetObject { + /** + * Choose the minutes interval between each time in the list. + * Defaults to 30. + */ + interval?: number; + } + + export interface SetOptions { + /** + * By default, any callbacks bound with the on method will be fired + * when its relevant thing is set. To silently set a thing, pass an + * options object with the muted parameter set to true. + */ + muted?: boolean; + format?: string; + } + + interface Picker { + /** + * The picker's relative input element wrapped as a jQuery object. + */ + $node: JQuery; + + /** + * The picker's relative root holder element wrapped as a jQuery object. + */ + $root: JQuery; + + /** + * This is the picker’s relative hidden element, which is undefined if + * there’s no formatSubmit option. There should be no reason to use this + * – it's mostly for internal use. If you have a valid reason for using + * this, please mention it in the issues. + */ + _hidden: HTMLInputElement; + + open(withoutFocus?: boolean): TPickerObject; + close(withFocus?: boolean): TPickerObject; + + /** + * Rebuild the picker. + */ + start(): TPickerObject; + + /** + * Destroy the picker. + */ + stop(): TPickerObject; + + /** + * Refresh the picker box after adding something to the holder. + * By default, only the "face" of the picker (i.e. the box element) + * has it’s contents re-rendered. To render the entire picker from + * the root up, pass true as the first argument. + */ + render(entirePicker?: boolean): TPickerObject; + + /** + * Clear the value in the picker's input element. + */ + clear(): TPickerObject; + + /** + * Short for picker.get('value') + */ + get(): string; + + /** + * Get the properties, objects, and states that make up the current + * state of the picker. + */ + get(thing: string): any; + + /** + * Returns the string value of the picker's input element. + */ + get(thing: 'value'): string; + + /** + * Returns the item object that is visually selected. + */ + get(thing: 'select'): TItemObject; + + /** + * Returns the item object that is visually highlighted. + */ + get(thing: 'highlight'): TItemObject; + + /** + * Returns the item object that sets the current view. + */ + get(thing: 'view'): TItemObject; + + /** + * Returns the item object that limits the picker's lower range. + */ + get(thing: 'min'): TItemObject; + + /** + * Returns the item object that limits the picker's upper range. + */ + get(thing: 'max'): TItemObject; + + /** + * Returns a boolean value of whether the picker is open or not. + */ + get(thing: 'open'): boolean; + + /** + * Returns a boolean value of whether the picker has started or not. + */ + get(thing: 'start'): boolean; + + /** + * Returns a unique 9-digit integer that is the ID of the picker. + */ + get(thing: 'id'): number; + + /** + * Returns an array of items that determine which item objects to + * disable on the picker. + */ + get(thing: 'disable'): any[]; + + /** + * Returns a formatted string for the item object specified by `thing` + */ + get(thing: string, format: string): string; + + /** + * Set the properties, objects, and states to change the state of the picker. + */ + set(thing: string, value?: any, options?: SetOptions): TPickerObject; + set(things: TOptions, options?: SetOptions): TPickerObject; + + /** + * Bind callbacks to get fired off when the relative picker method is called. + */ + on(methodName: string, callback: (data?: any) => void): TPickerObject; + + /** + * Bind multiple callbacks at once to get fired off when the relative + * picker method is called. + */ + on(callbackObject: CallbackObject): TPickerObject; + + /** + * Unbind callbacks that are bound using the on method. + */ + off(...methodName: string[]): TPickerObject; + + /** + * Trigger callbacks that have been queued up using the the on method. + */ + trigger(event: string, data?: any): TPickerObject; + } + + export interface DatePicker extends Picker { } + export interface TimePicker extends Picker { } } interface JQuery { /** - * Access the API object after initialization. + * Access the API object on an initialized date picker element. */ - pickadate(keyword: "picker"): Pickadate.DateApi; + pickadate(keyword: "picker"): Pickadate.DatePicker; pickadate(objectName: "$node"): JQuery; pickadate(objectName: "$root"): JQuery; - pickadate(objectName: "_hidden"): JQuery; + pickadate(objectName: "_hidden"): HTMLInputElement; /** - * Invoke API methods after picker initialization. - * @param methodName - * @param arguments any arguments to pass to the method + * Invoke API methods after date picker initialization. */ pickadate(methodName: string, ...arguments: any[]): any; /** * Initialize a date picker. - * @returns the original JQuery selection */ pickadate(options?: Pickadate.DateOptions): JQuery; - - pickatime(keyword: "picker"): Pickadate.TimeApi; + /** + * Access the API object on an initialized time picker element. + */ + pickatime(keyword: "picker"): Pickadate.TimePicker; pickatime(objectName: "$node"): JQuery; pickatime(objectName: "$root"): JQuery; - pickatime(objectName: "_hidden"): JQuery; - + pickatime(objectName: "_hidden"): HTMLInputElement; + /** - * Invoke API methods after picker initialization. - * @param methodName - * @param arguments any arguments to pass to the method + * Invoke API methods after time picker initialization. */ pickatime(methodName: string, ...arguments: any[]): any; /** * Initialize a time picker. - * @returns the original JQuery selection */ pickatime(options?: Pickadate.TimeOptions): JQuery; } - diff --git a/qtip2/qtip2-tests.ts b/qtip2/qtip2-tests.ts new file mode 100644 index 000000000..144b4aa51 --- /dev/null +++ b/qtip2/qtip2-tests.ts @@ -0,0 +1,1051 @@ +/// + +var $a = $('_'); + + +/** + * Test core properties (http://qtip2.com/options#core) + */ +function testCoreProperties() { + // Test with all core options specififed + $a.qtip({ + content: 'Jan Jansen', + id: 'jan-jansen', + prerender: true, + overwrite: true, + suppress: true, + metadata: { + type: 'html5', + name: 'qtipopts' + } + }); + + // Test ID as boolean + $a.qtip({ + content: 'yoshimo', + id: false + }); + + // Test with no options specified + $a.qtip({ + content: 'aerie' + }); +} + + +/** + * http://qtip2.com/options#content.text + */ +function testContentText() { + // Shorthand string + $a.qtip({ + content: 'valygar' + }); + + // Regular string + $a.qtip({ + content: { text: 'kivan' } + }); + + // Shorthand boolean + $a.qtip({ + content: true + }); + + // Regular boolean + $a.qtip({ + content: { text: true } + }); + + // Shorthand Deferred / Promise + $a.qtip({ + content: $.Deferred().resolve('cernd') + }); + + $a.qtip({ + content: $.Deferred().reject().promise() + }); + + // Regular Deferred / Promise + $a.qtip({ + content: { text: $.Deferred().resolve('horatio') } + }); + + $a.qtip({ + content: { text: $.Deferred().reject().promise() } + }); + + // Shorthand function + $a.qtip({ + content: function(event: Event, api: QTip2.Api) { } + }); + + $a.qtip({ + content: function(event: Event) { return 2; } + }); + + $a.qtip({ + content: function() { } + }); + + // Regular function + $a.qtip({ + content: { text: function(event: Event, api: QTip2.Api) {} } + }); + + $a.qtip({ + content: { text: function(event: Event) { return 2; } } + }); + + $a.qtip({ + content: { text: function() { } } + }); + + // Shorthand jQuery elements + $a.qtip({ + content: $('.irenicus') + }); + + // Regular jQuery elements + $a.qtip({ + content: { text: $('.irenicus') } + }); +} + + +/** + * http://qtip2.com/options#content.title + */ +function testContentTitle() { + // Shorthand string + $a.qtip({ + content: { title: 'keldorn' } + }); + + // Regular string + $a.qtip({ + content: { + title: { text: 'nalia' } + } + }); + + // Shorthand boolean + $a.qtip({ + content: { title: true } + }); + + // Regular boolean + $a.qtip({ + content: { + title: { text: true } + } + }); + + // Shorthand Deferred / Promise + $a.qtip({ + content: { title: $.Deferred().resolve('mazzy') } + }); + + $a.qtip({ + content: { title: $.Deferred().reject().promise() } + }); + + // Regular Deferred / Promise + $a.qtip({ + content: { title: { text: $.Deferred().resolve('bodhi') } } + }); + + $a.qtip({ + content: { title: { text: $.Deferred().reject().promise() } } + }); + + // Shorthand function + $a.qtip({ + content: { title: function(event: Event, api: QTip2.Api) {} } + }); + + $a.qtip({ + content: { title: function(event: Event) { return 2; } } + }); + + $a.qtip({ + content: { title: function() { } } + }); + + // Regular function + $a.qtip({ + content: { title: { text: function(event: Event, api: QTip2.Api) { } } } + }); + + $a.qtip({ + content: { title: { text: function(event: Event) { return 2; } } } + }); + + $a.qtip({ + content: { title: { text: function() { } } } + }); + + // Shorthand jQuery elements + $a.qtip({ + content: { title: $('.irenicus') } + }); + + // Regular jQuery elements + $a.qtip({ + content: { title: { text: $('.irenicus') } } + }); +} + + +/** + * http://qtip2.com/options#content.button + */ +function testContentButtonProperty() { + $a.qtip({ + content: { button: $('.minsc') } + }); + + $a.qtip({ + content: { button: 'jaheira' } + }); + + $a.qtip({ + content: { button: true } + }); +} + + +/** + * http://qtip2.com/options#content.attr + */ +function testContentAttrProperty() { + $a.qtip({ + content: { attr: 'viconia' } + }); +} + + +/** + * http://qtip2.com/options#position + */ +function testPositionProperty() { + // Shorthand + $a.qtip({ position: 'top left' }); + + // The below four calls test all combinations of all sub-properties + $a.qtip({ + position: { + target: $('.khalid'), + my: 'top left', + at: 'bottom right', + container: $('.edwin-odesseiron'), + viewport: $('.dynaheir'), + effect: function(api: QTip2.Api, pos: any, viewport: any) { }, + adjust: { x: 2 } + } + }); + + $a.qtip({ + position: { + target: [2, 2], + my: true, + at: true, + container: false, + viewport: true, + effect: function(api: QTip2.Api, pos: any) { return 2; }, + adjust: { y: 2 } + } + }); + + $a.qtip({ + position: { + target: 'mouse', + effect: function(api: QTip2.Api) {}, + adjust: { x: 2, y: 2 } + } + }); + + $a.qtip({ + position: { + target: false, + effect: function() {}, + adjust: { + mouse: true, + resize: true, + scroll: false, + method: 'flipinvert' + } + } + }); + + $a.qtip({ + position: { + adjust: { } + } + }); +} + + +/** + * http://qtip2.com/options#show + */ +function testShowProperty() { + // Shorthand + $a.qtip({ show: true }); + $a.qtip({ show: 'mouseenter' }); + $a.qtip({ show: $('.korgan') }); + + // The below calls test all combinations of all sub-properties + $a.qtip({ + show: { + target: $('.gorion'), + event: false, + delay: 42, + solo: $('.imoen'), + ready: true, + effect: function(offset) { + }, + modal: true + } + }); + + $a.qtip({ + show: { + target: false, + event: 'mouseenter', + solo: '.qtips', + effect: true, + modal: { + on: true, + blur: false, + escape: true, + stealfocus: true, + effect: true + } + } + }); + + $a.qtip({ + show: { + solo: false, + modal: { + effect: function(state) {} + } + } + }); + + $a.qtip({ + show: { + modal: {} + } + }); +} + + +/** + * http://qtip2.com/options#hide + */ +function testHideProperty() { + // Shorthand + $a.qtip({ hide: 'mouseenter' }); + $a.qtip({ hide: $('.montaron') }); + + // The below calls test all combinations of all sub-properties + $a.qtip({ + hide: { + target: $('.gorion'), + event: false, + delay: 42, + inactive: 64, + fixed: true, + leave: 'window', + distance: 32, + effect: function(offset) { + }, + } + }); + + $a.qtip({ + hide: { + target: false, + event: 'mouseenter', + inactive: false, + leave: false, + distance: false, + effect: true, + } + }); +} + + +/** + * http://qtip2.com/options#style + */ +function testStyleProperty() { + // Shorthand + $a.qtip({ style: 'kagain' }); + + // The below calls test all combinations of all sub-properties + $a.qtip({ + style: { + classes: 'anomen', + def: true, + widget: true, + width: '24pt', + height: '24pt', + tip: 'top left' + } + }); + + $a.qtip({ + style: { + classes: false, + width: 24, + height: 24, + tip: false + } + }); + + $a.qtip({ + style: { + classes: false, + width: false, + height: false, + tip: { + corner: 'bottom right', + mimic: 'bottom right', + border: 3, + width: 27, + height: 32, + offset: 1 + } + } + }); + + $a.qtip({ + style: { + tip: { + corner: true, + mimic: true, + border: false + } + } + }); + + $a.qtip({ + style: { + tip: { } + } + }); +} + + +function baseCase() { + $a.qtip(); + $a.qtip({}); + + $a.qtip('horatio'); + $a.qtip('activate'); + $a.qtip('deactivate'); +} + + +/** + * Test with all options specified. Copied from http://qtip2.com/options#global and amended. + */ +function allTogetherNow() { + $a.qtip({ + prerender: false, + id: false, + overwrite: true, + suppress: true, + content: { + title: true, + attr: 'title', + text: false, + button: false + }, + position: { + my: 'top left', + at: 'bottom right', + target: false, + container: false, + viewport: false, + adjust: { + x: 0, y: 0, + mouse: true, + resize: true, + method: 'flip flip' + }, + effect: function(api, pos, viewport) { + $(this).animate(pos, { + duration: 200, + queue: false + }); + } + }, + show: { + target: false, + event: 'mouseenter', + effect: true, + delay: 90, + solo: false, + ready: false, + modal: { + on: false, + effect: true, + blur: true, + escape: true + } + }, + hide: { + target: false, + event: 'mouseleave', + effect: true, + delay: 0, + fixed: false, + inactive: false, + leave: 'window', + distance: false + }, + style: { + classes: '', + widget: false, + width: false, + height: false, + tip: { + corner: true, + mimic: false, + width: 8, + height: 8, + border: true, + offset: 0 + } + }, + events: { + render: null, + move: null, + show: null, + hide: null, + toggle: null, + visible: null, + hidden: null, + focus: null, + blur: null + } + }); +} + + +/** + * http://qtip2.com/api#api-methods.get + */ +function testApiGetViaObject() { + $a.qtip({}); + + var api = $a.qtip('api'); + + api.get('id'); + api.get('prerender'); + api.get('overwrite'); + api.get('suppress'); + api.get('metadata'); + + api.get('content'); + api.get('content.text'); + api.get('content.attr'); + api.get('content.title'); + api.get('content.button'); + + api.get('position'); + api.get('position.my'); + api.get('position.at'); + api.get('position.target'); + api.get('position.container'); + api.get('position.viewport'); + any)> + api.get('position.effect'); + api.get('position.adjust'); + + api.get('show'); + api.get('show.target'); + api.get('show.event'); + api.get('show.delay'); + api.get('show.solo'); + api.get('show.ready'); + any)> api.get('show.effect'); + api.get('show.modal'); + + api.get('hide'); + api.get('hide.target'); + api.get('hide.event'); + api.get('hide.delay'); + api.get('hide.leave'); + api.get('hide.distance'); + any)> api.get('hide.effect'); + + api.get('style'); + api.get('style.classes'); + api.get('style.def'); + api.get('style.widget'); + api.get('style.width'); + api.get('style.height'); + api.get('style.tip'); + + api.get('events'); + api.get('events.render'); + api.get('events.show'); + api.get('events.hide'); + api.get('events.toggle'); + api.get('events.visible'); + api.get('events.hidde'); + api.get('events.move'); + api.get('events.focus'); + api.get('events.blur'); +} + + +/** + * http://qtip2.com/api#api.updating + */ +function testApiGetViaString() { + $a.qtip({}); + + $a.qtip('option', 'id'); + $a.qtip('option', 'prerender'); + $a.qtip('option', 'overwrite'); + $a.qtip('option', 'suppress'); + $a.qtip('option', 'metadata'); + + $a.qtip('option', 'content'); + $a.qtip('option', 'content.text'); + $a.qtip('option', 'content.attr'); + $a.qtip('option', 'content.title'); + $a.qtip('option', 'content.button'); + + $a.qtip('option', 'position'); + $a.qtip('option', 'position.my'); + $a.qtip('option', 'position.at'); + $a.qtip('option', 'position.target'); + $a.qtip('option', 'position.container'); + $a.qtip('option', 'position.viewport'); + any)> + $a.qtip('option', 'position.effect'); + $a.qtip('option', 'position.adjust'); + + $a.qtip('option', 'show'); + $a.qtip('option', 'show.target'); + $a.qtip('option', 'show.event'); + $a.qtip('option', 'show.delay'); + $a.qtip('option', 'show.solo'); + $a.qtip('option', 'show.ready'); + any)> $a.qtip('option', 'show.effect'); + $a.qtip('option', 'show.modal'); + + $a.qtip('option', 'hide'); + $a.qtip('option', 'hide.target'); + $a.qtip('option', 'hide.event'); + $a.qtip('option', 'hide.delay'); + $a.qtip('option', 'hide.leave'); + $a.qtip('option', 'hide.distance'); + any)> $a.qtip('option', 'hide.effect'); + + $a.qtip('option', 'style'); + $a.qtip('option', 'style.classes'); + $a.qtip('option', 'style.def'); + $a.qtip('option', 'style.widget'); + $a.qtip('option', 'style.width'); + $a.qtip('option', 'style.height'); + $a.qtip('option', 'style.tip'); + + $a.qtip('option', 'events'); + $a.qtip('option', 'events.render'); + $a.qtip('option', 'events.show'); + $a.qtip('option', 'events.hide'); + $a.qtip('option', 'events.toggle'); + $a.qtip('option', 'events.visible'); + $a.qtip('option', 'events.hidde'); + $a.qtip('option', 'events.move'); + $a.qtip('option', 'events.focus'); + $a.qtip('option', 'events.blur'); +} + + +/** + * http://qtip2.com/api#api-methods.set + */ +function testApiSetViaObject() { + + // TODO + $a.qtip({}); + + var api = $a.qtip('api'); + + api.set({ + prerender: false, + id: false, + overwrite: true, + suppress: true, + content: { + title: true, + attr: 'title', + text: false, + button: false + }, + position: { + my: 'top left', + at: 'bottom right', + target: false, + container: false, + viewport: false, + adjust: { + x: 0, y: 0, + mouse: true, + resize: true, + method: 'flip flip' + }, + effect: function(api, pos, viewport) { + $(this).animate(pos, { + duration: 200, + queue: false + }); + } + }, + show: { + target: false, + event: 'mouseenter', + effect: true, + delay: 90, + solo: false, + ready: false, + modal: { + on: false, + effect: true, + blur: true, + escape: true + } + }, + hide: { + target: false, + event: 'mouseleave', + effect: true, + delay: 0, + fixed: false, + inactive: false, + leave: 'window', + distance: false + }, + style: { + classes: '', + widget: false, + width: false, + height: false, + tip: { + corner: true, + mimic: false, + width: 8, + height: 8, + border: true, + offset: 0 + } + }, + events: { + render: null, + move: null, + show: null, + hide: null, + toggle: null, + visible: null, + hidden: null, + focus: null, + blur: null + } + }); + + api.set('id', null); + api.set('prerender', null); + api.set('overwrite', null); + api.set('suppress', null); + api.set('metadata', null); + + api.set('content', null); + api.set('content.title', null); + api.set('content.text', null); + api.set('content.attr', null); + api.set('content.button', null); + + api.set('position', null); + api.set('position.my', null); + api.set('position.at', null); + api.set('position.target', null); + api.set('position.container', null); + api.set('position.viewport', null); + api.set('position.effect', void)> null); + api.set('position.adjust', null); + + api.set('show', null); + api.set('show.target', null); + api.set('show.event', null); + api.set('show.delay', null); + api.set('show.solo', null); + api.set('show.ready', null); + api.set('show.effect', void)> null); + api.set('show.modal', null); + + api.set('hide', null); + api.set('hide.target', null); + api.set('hide.event', null); + api.set('hide.inactive', null); + api.set('hide.fixed', null); + api.set('hide.leave', null); + api.set('hide.distance', null); + api.set('hide.effect', void)> null); + + api.set('style', null); + api.set('style.classes', null); + api.set('style.def', null); + api.set('style.widget', null); + api.set('style.width', null); + api.set('style.height', null); + api.set('style.tip', null); + + api.set('events', null); + api.set('events.render', null); + api.set('events.show', null); + api.set('events.hide', null); + api.set('events.toggle', null); + api.set('events.visible', null); + api.set('events.hidden', null); + api.set('events.move', null); + api.set('events.focus', null); + api.set('events.blur', null); +} + + +/** + * http://qtip2.com/api#api.updating + */ +function testApiSetViaString() { + $a.qtip({}); + + $a.qtip('option', { + prerender: false, + id: false, + overwrite: true, + suppress: true, + content: { + title: true, + attr: 'title', + text: false, + button: false + }, + position: { + my: 'top left', + at: 'bottom right', + target: false, + container: false, + viewport: false, + adjust: { + x: 0, y: 0, + mouse: true, + resize: true, + method: 'flip flip' + }, + effect: function(api: QTip2.Api, pos: any, viewport: any) { + $(this).animate(pos, { + duration: 200, + queue: false + }); + } + }, + show: { + target: false, + event: 'mouseenter', + effect: true, + delay: 90, + solo: false, + ready: false, + modal: { + on: false, + effect: true, + blur: true, + escape: true + } + }, + hide: { + target: false, + event: 'mouseleave', + effect: true, + delay: 0, + fixed: false, + inactive: false, + leave: 'window', + distance: false + }, + style: { + classes: '', + widget: false, + width: false, + height: false, + tip: { + corner: true, + mimic: false, + width: 8, + height: 8, + border: true, + offset: 0 + } + }, + events: { + render: null, + move: null, + show: null, + hide: null, + toggle: null, + visible: null, + hidden: null, + focus: null, + blur: null + } + }); + + $a.qtip('option', 'id', null); + $a.qtip('option', 'prerender', null); + $a.qtip('option', 'overwrite', null); + $a.qtip('option', 'suppress', null); + $a.qtip('option', 'metadata', null); + + $a.qtip('option', 'content', null); + $a.qtip('option', 'content.title', null); + $a.qtip('option', 'content.text', null); + $a.qtip('option', 'content.attr', null); + $a.qtip('option', 'content.button', null); + + $a.qtip('option', 'position', null); + $a.qtip('option', 'position.my', null); + $a.qtip('option', 'position.at', null); + $a.qtip('option', 'position.target', null); + $a.qtip('option', 'position.container', null); + $a.qtip('option', 'position.viewport', null); + $a.qtip('option', 'position.effect', void)> null); + $a.qtip('option', 'position.adjust', null); + + $a.qtip('option', 'show', null); + $a.qtip('option', 'show.target', null); + $a.qtip('option', 'show.event', null); + $a.qtip('option', 'show.delay', null); + $a.qtip('option', 'show.solo', null); + $a.qtip('option', 'show.ready', null); + $a.qtip('option', 'show.effect', void)> null); + $a.qtip('option', 'show.modal', null); + + $a.qtip('option', 'hide', null); + $a.qtip('option', 'hide.target', null); + $a.qtip('option', 'hide.event', null); + $a.qtip('option', 'hide.inactive', null); + $a.qtip('option', 'hide.fixed', null); + $a.qtip('option', 'hide.leave', null); + $a.qtip('option', 'hide.distance', null); + $a.qtip('option', 'hide.effect', void)> null); + + $a.qtip('option', 'style', null); + $a.qtip('option', 'style.classes', null); + $a.qtip('option', 'style.def', null); + $a.qtip('option', 'style.widget', null); + $a.qtip('option', 'style.width', null); + $a.qtip('option', 'style.height', null); + $a.qtip('option', 'style.tip', null); + + $a.qtip('option', 'events', null); + $a.qtip('option', 'events.render', null); + $a.qtip('option', 'events.show', null); + $a.qtip('option', 'events.hide', null); + $a.qtip('option', 'events.toggle', null); + $a.qtip('option', 'events.visible', null); + $a.qtip('option', 'events.hidden', null); + $a.qtip('option', 'events.move', null); + $a.qtip('option', 'events.focus', null); + $a.qtip('option', 'events.blur', null); +} + + +/** + * http://qtip2.com/api#api-methods + */ +function testApiViaObject() { + $a.qtip({}); + + var api = $a.qtip('api'); + + api.toggle(); + api.toggle(true); + api.toggle(false, null); + + api.show(); + api.show( null); + + api.hide(); + api.hide( null); + + api.disable(); + api.disable(true); + + api.enable(); + + api.reposition(); + api.reposition( null); + api.reposition( null, true); + + api.focus(); + api.focus( null); + + api.blur(); + api.blur( null); + + api.destroy(); + api.destroy(true); +} + + +/** + * http://qtip2.com/api#api.updating + */ +function testApiMethodsViaString() { + $a.qtip('toggle'); + $a.qtip('toggle', true); + $a.qtip('toggle', true, null); + + $a.qtip('show'); + $a.qtip('show', null); + + $a.qtip('hide'); + $a.qtip('hide', null); + + $a.qtip('disable'); + $a.qtip('disable', true); + + $a.qtip('enable'); + + $a.qtip('reposition'); + $a.qtip('reposition', null); + $a.qtip('reposition', null, true); + + $a.qtip('focus'); + $a.qtip('focus', null); + + $a.qtip('blur'); + $a.qtip('blur', null); + + $a.qtip('destroy'); + $a.qtip('destroy', true); +} + + +/** + * http://qtip2.com/options#global + * + * $.fn is of type any, therefore we can't (and don't need to) add type bindings for QTip2 globals under it. + */ +function testGlobals() { + $.fn.qtip.defaults.prerender = true; +} \ No newline at end of file diff --git a/qtip2/qtip2-tests.ts.tscparams b/qtip2/qtip2-tests.ts.tscparams new file mode 100644 index 000000000..2280b0116 --- /dev/null +++ b/qtip2/qtip2-tests.ts.tscparams @@ -0,0 +1,2 @@ + +--noImplicitAny \ No newline at end of file diff --git a/qtip2/qtip2.d.ts b/qtip2/qtip2.d.ts new file mode 100644 index 000000000..3d1f841f2 --- /dev/null +++ b/qtip2/qtip2.d.ts @@ -0,0 +1,409 @@ +// Type definitions for qtip2 v2.2.1 +// Project: http://qtip2.com/ +// Definitions by: Nathan Pitman +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Notes: +// - Type bindings for the QTip2 API and options are included. Bindings for global settings aren't required. +// - Deprecated functionality is not supported. +// - Where possible, things are strongly typed and 'any' is avoided. +// - QTip2 includes a lot of shorthand notation for various expressions. These bindings support it all. + +/// + +declare module QTip2 { + type EventApiFunc = (event: Event, api: Api) => void; + + + /** + * Content property + */ + type Title = string | JQuery | EventApiFunc | boolean | JQueryGenericPromise; + type Text = string | JQuery | EventApiFunc | boolean | JQueryGenericPromise; + + interface Content { + title?: Title | { text: Title }; + text?: Text; + attr?: string; + button?: string | JQuery | boolean; + } + + + /** + * Position property + */ + interface PositionAdjust { + x?: number; + y?: number; + mouse?: boolean; + resize?: boolean; + scroll?: boolean; + method?: string; + } + + type Target = JQuery | number[] | string; + + interface Position { + my?: string | boolean; + at?: string | boolean; + target?: Target | boolean; + container?: JQuery | boolean; + viewport?: JQuery | boolean; + effect?: boolean | ((api: Api, pos: any, viewport: any) => void); + adjust?: PositionAdjust; + } + + + /** + * Show property + */ + interface Show { + target?: JQuery | boolean; + event?: string | boolean; + delay?: number; + solo?: JQuery | string | boolean; + ready?: boolean; + effect?: boolean | ((offset: any) => void); + modal?: boolean | Modal; + } + + interface Modal + { + on?: boolean; + blur?: boolean; + escape?: boolean; + stealfocus?: boolean; + effect?: boolean | ((state: any) => void); + } + + + /** + * Hide property + */ + interface Hide { + target?: JQuery | boolean; + event?: string | boolean; + delay?: number; + inactive?: number | boolean; + fixed?: boolean; + leave?: string | boolean; + distance?: number | boolean; + effect?: boolean | ((offset: any) => void); + } + + + /** + * Style property + */ + interface Style { + classes?: string | boolean; + def?: boolean; + widget?: boolean; + width?: string | number | boolean; + height?: string | number | boolean; + tip?: string | boolean | Tip; + } + + interface Tip { + corner?: string | boolean; + mimic?: string | boolean; + border?: number | boolean; + width?: number; + height?: number; + offset?: number; + } + + + /** + * Events property + */ + interface Events { + render?: EventApiFunc; + show?: EventApiFunc; + hide?: EventApiFunc; + toggle?: EventApiFunc; + visible?: EventApiFunc; + hidden?: EventApiFunc; + move?: EventApiFunc; + focus?: EventApiFunc; + blur?: EventApiFunc; + } + + + /** + * Options + */ + interface QTipOptions { + id?: string | boolean; + prerender?: boolean; + overwrite?: boolean; + suppress?: boolean; + metadata?: any; + content?: Text | Content; + position?: string | Position; + style?: string | Style; + show?: string | boolean | JQuery | Show; + hide?: string | JQuery | Hide; + events?: Events; + } + + + /** + * API + */ + interface Api { + get(propertyName: 'id'): string | boolean; + get(propertyName: 'prerender'): boolean; + get(propertyName: 'overwrite'): boolean; + get(propertyName: 'suppress'): boolean; + get(propertyName: 'metadata'): any; + get(propertyName: 'content'): Content; + get(propertyName: 'content.text'): Text; + get(propertyName: 'content.attr'): string; + get(propertyName: 'content.title'): Title; + get(propertyName: 'content.button'): string | JQuery | boolean; + get(propertyName: 'position'): Position; + get(propertyName: 'position.my'): string | boolean; + get(propertyName: 'position.at'): string | boolean; + get(propertyName: 'position.target'): Target | boolean; + get(propertyName: 'position.container'): JQuery | boolean; + get(propertyName: 'position.viewport'): JQuery | boolean; + get(propertyName: 'position.effect'): boolean | ((api: any, pos: any, viewport: any) => void); + get(propertyName: 'position.adjust'): PositionAdjust; + get(propertyName: 'show'): Show; + get(propertyName: 'show.target'): JQuery | boolean; + get(propertyName: 'show.event'): string | boolean; + get(propertyName: 'show.delay'): number; + get(propertyName: 'show.solo'): JQuery | string | boolean; + get(propertyName: 'show.ready'): boolean; + get(propertyName: 'show.effect'): boolean | ((offset: any) => void); + get(propertyName: 'show.modal'): boolean | Modal; + get(propertyName: 'hide'): Hide; + get(propertyName: 'hide.target'): JQuery | boolean; + get(propertyName: 'hide.event'): string | boolean; + get(propertyName: 'hide.delay'): number; + get(propertyName: 'hide.leave'): string | boolean; + get(propertyName: 'hide.distance'): number | boolean; + get(propertyName: 'hide.effect'): boolean | ((offset: any) => void); + get(propertyName: 'style'): Style; + get(propertyName: 'style.classes'): string | boolean; + get(propertyName: 'style.def'): boolean; + get(propertyName: 'style.widget'): boolean; + get(propertyName: 'style.width'): string | number | boolean; + get(propertyName: 'style.height'): string | number | boolean; + get(propertyName: 'style.tip'): string | boolean | Tip; + get(propertyName: 'events'): Events; + get(propertyName: 'events.render'): EventApiFunc; + get(propertyName: 'events.show'): EventApiFunc; + get(propertyName: 'events.hide'): EventApiFunc; + get(propertyName: 'events.toggle'): EventApiFunc; + get(propertyName: 'events.visible'): EventApiFunc; + get(propertyName: 'events.hidden'): EventApiFunc; + get(propertyName: 'events.move'): EventApiFunc; + get(propertyName: 'events.focus'): EventApiFunc; + get(propertyName: 'events.blur'): EventApiFunc; + get(propertyName: string): any; + + set(properties: QTipOptions): Api; + set(propertyName: 'id', value: string | boolean): Api; + set(propertyName: 'prerender', value: boolean): Api; + set(propertyName: 'overwrite', value: boolean): Api; + set(propertyName: 'suppress', value: boolean): Api; + set(propertyName: 'metadata', value: any): Api; + set(propertyName: 'content', value: Text | Content): Api; + set(propertyName: 'content.title', value: Title | { text: Title }): Api; + set(propertyName: 'content.text', value: Text): Api; + set(propertyName: 'content.attr', value: string): Api; + set(propertyName: 'content.button', value: string | JQuery | boolean): Api; + set(propertyName: 'position', value: Position): Api; + set(propertyName: 'position.my', value: string | boolean): Api; + set(propertyName: 'position.at', value: string | boolean): Api; + set(propertyName: 'position.target', value: Target | boolean): Api; + set(propertyName: 'position.container', value: JQuery | boolean): Api; + set(propertyName: 'position.viewport', value: JQuery | boolean): Api; + set(propertyName: 'position.effect', value: boolean | ((api: Api, pos: any, viewport: any) => void) ): Api; + set(propertyName: 'position.adjust', value: PositionAdjust): Api; + set(propertyName: 'show', value: Show): Api; + set(propertyName: 'show.target', value: JQuery | boolean): Api; + set(propertyName: 'show.event', value: string | boolean): Api; + set(propertyName: 'show.delay', value: number): Api; + set(propertyName: 'show.solo', value: JQuery | string | boolean): Api; + set(propertyName: 'show.ready', value: boolean): Api; + set(propertyName: 'show.effect', value: boolean | ((offset: any) => void)): Api; + set(propertyName: 'show.modal', value: boolean | Modal): Api; + set(propertyName: 'hide', value: Hide): Api; + set(propertyName: 'hide.target', value: JQuery | boolean): Api; + set(propertyName: 'hide.event', value: string | boolean): Api; + set(propertyName: 'hide.inactive', value: number | boolean): Api; + set(propertyName: 'hide.fixed', value: boolean): Api; + set(propertyName: 'hide.leave', value: string | boolean): Api; + set(propertyName: 'hide.distance', value: number | boolean): Api; + set(propertyName: 'hide.effect', value: boolean | ((offset: any) => void)): Api + set(propertyName: 'style', value: Style): Api; + set(propertyName: 'style.classes', value: string | boolean): Api; + set(propertyName: 'style.def', value: boolean): Api; + set(propertyName: 'style.widget', value: boolean): Api; + set(propertyName: 'style.width', value: string | number | boolean): Api; + set(propertyName: 'style.height', value: string | number | boolean): Api; + set(propertyName: 'style.tip', value: string | boolean | Tip): Api; + set(propertyName: 'events', value: Events): Api; + set(propertyName: 'events.render', value: EventApiFunc): Api; + set(propertyName: 'events.show', value: EventApiFunc): Api; + set(propertyName: 'events.hide', value: EventApiFunc): Api; + set(propertyName: 'events.toggle', value: EventApiFunc): Api; + set(propertyName: 'events.visible', value: EventApiFunc): Api; + set(propertyName: 'events.hidden', value: EventApiFunc): Api; + set(propertyName: 'events.move', value: EventApiFunc): Api; + set(propertyName: 'events.focus', value: EventApiFunc): Api; + set(propertyName: 'events.blur', value: EventApiFunc): Api; + set(propertyName: string, value: any): Api; + + toggle(state?: boolean, event?: Event): Api; + + show(event?: Event): Api; + + hide(event?: Event): Api; + + disable(state?: boolean): Api; + + enable(): Api; + + reposition(event?: Event, effect?: boolean): Api; + + focus(event?: Event): Api; + + blur(event?: Event): Api; + + destroy(immediate?: boolean): Api; + } +} + + +interface JQuery { + qtip(options?: QTip2.QTipOptions): JQuery; + + qtip(methodName: 'api'): QTip2.Api; + + qtip(methodName: 'option', propertyName: 'id'): string | boolean; + qtip(methodName: 'option', propertyName: 'prerender'): boolean; + qtip(methodName: 'option', propertyName: 'overwrite'): boolean; + qtip(methodName: 'option', propertyName: 'suppress'): boolean; + qtip(methodName: 'option', propertyName: 'metadata'): any; + qtip(methodName: 'option', propertyName: 'content'): QTip2.Content; + qtip(methodName: 'option', propertyName: 'content.text'): QTip2.Text; + qtip(methodName: 'option', propertyName: 'content.attr'): string; + qtip(methodName: 'option', propertyName: 'content.title'): QTip2.Title; + qtip(methodName: 'option', propertyName: 'content.button'): string | JQuery | boolean; + qtip(methodName: 'option', propertyName: 'position'): QTip2.Position; + qtip(methodName: 'option', propertyName: 'position.my'): string | boolean; + qtip(methodName: 'option', propertyName: 'position.at'): string | boolean; + qtip(methodName: 'option', propertyName: 'position.target'): QTip2.Target | boolean; + qtip(methodName: 'option', propertyName: 'position.container'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'position.viewport'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'position.effect'): boolean | ((api: QTip2.Api, pos: any, viewport: any) => void); + qtip(methodName: 'option', propertyName: 'position.adjust'): QTip2.PositionAdjust; + qtip(methodName: 'option', propertyName: 'show'): QTip2.Show; + qtip(methodName: 'option', propertyName: 'show.target'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'show.event'): string | boolean; + qtip(methodName: 'option', propertyName: 'show.delay'): number; + qtip(methodName: 'option', propertyName: 'show.solo'): JQuery | string | boolean; + qtip(methodName: 'option', propertyName: 'show.ready'): boolean; + qtip(methodName: 'option', propertyName: 'show.effect'): boolean | ((offset: any) => void); + qtip(methodName: 'option', propertyName: 'show.modal'): boolean | QTip2.Modal; + qtip(methodName: 'option', propertyName: 'hide'): QTip2.Hide; + qtip(methodName: 'option', propertyName: 'hide.target'): JQuery | boolean; + qtip(methodName: 'option', propertyName: 'hide.event'): string | boolean; + qtip(methodName: 'option', propertyName: 'hide.delay'): number; + qtip(methodName: 'option', propertyName: 'hide.leave'): string | boolean; + qtip(methodName: 'option', propertyName: 'hide.distance'): number | boolean; + qtip(methodName: 'option', propertyName: 'hide.effect'): boolean | ((offset: any) => void); + qtip(methodName: 'option', propertyName: 'style'): QTip2.Style; + qtip(methodName: 'option', propertyName: 'style.classes'): string | boolean; + qtip(methodName: 'option', propertyName: 'style.def'): boolean; + qtip(methodName: 'option', propertyName: 'style.widget'): boolean; + qtip(methodName: 'option', propertyName: 'style.width'): string | number | boolean; + qtip(methodName: 'option', propertyName: 'style.height'): string | number | boolean; + qtip(methodName: 'option', propertyName: 'style.tip'): string | boolean | QTip2.Tip; + qtip(methodName: 'option', propertyName: 'events'): QTip2.Events; + qtip(methodName: 'option', propertyName: 'events.render'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.show'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.hide'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.toggle'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.visible'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.hidden'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.move'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.focus'): QTip2.EventApiFunc; + qtip(methodName: 'option', propertyName: 'events.blur'): QTip2.EventApiFunc; + + qtip(methodName: 'option', properties: QTip2.QTipOptions): QTip2.Api; + qtip(methodName: 'option', propertyName: 'id', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'prerender', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'overwrite', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'suppress', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'metadata', value: any): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content', value: QTip2.Text | QTip2.Content): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.title', value: QTip2.Title | { text: QTip2.Title }): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.text', value: QTip2.Text): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.attr', value: string): QTip2.Api; + qtip(methodName: 'option', propertyName: 'content.button', value: string | JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position', value: QTip2.Position): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.my', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.at', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.target', value: QTip2.Target | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.container', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.viewport', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.effect', value: boolean | ((api: QTip2.Api, pos: any, viewport: any) => void) ): QTip2.Api; + qtip(methodName: 'option', propertyName: 'position.adjust', value: QTip2.PositionAdjust): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show', value: QTip2.Show): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.target', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.event', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.delay', value: number): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.solo', value: JQuery | string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.ready', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.effect', value: boolean | ((offset: any) => void)): QTip2.Api; + qtip(methodName: 'option', propertyName: 'show.modal', value: boolean | QTip2.Modal): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide', value: QTip2.Hide): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.target', value: JQuery | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.event', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.inactive', value: number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.fixed', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.leave', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.distance', value: number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'hide.effect', value: boolean | ((offset: any) => void)): QTip2.Api + qtip(methodName: 'option', propertyName: 'style', value: QTip2.Style): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.classes', value: string | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.def', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.widget', value: boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.width', value: string | number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.height', value: string | number | boolean): QTip2.Api; + qtip(methodName: 'option', propertyName: 'style.tip', value: string | boolean | QTip2.Tip): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events', value: QTip2.Events): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.render', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.show', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.hide', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.toggle', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.visible', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.hidden', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.move', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.focus', value: QTip2.EventApiFunc): QTip2.Api; + qtip(methodName: 'option', propertyName: 'events.blur', value: QTip2.EventApiFunc): QTip2.Api; + + qtip(methodName: 'toggle', state?: boolean, event?: Event): JQuery; + + qtip(methodName: 'show', event?: Event): JQuery; + + qtip(methodName: 'hide', event?: Event): JQuery; + + qtip(methodName: 'disable', state?: boolean): JQuery; + + qtip(methodName: 'enable'): JQuery + + qtip(methodName: 'reposition', event?: Event, effect?: boolean): JQuery; + + qtip(methodName: 'focus', event?: Event): JQuery; + + qtip(methodName: 'blur', event?: Event): JQuery; + + qtip(methodName: 'destroy', immediate?: boolean): JQuery; + + qtip(methodName: string, p1?: any, p2?: any, p3?: any): any; +} diff --git a/raphael/raphael.d.ts b/raphael/raphael.d.ts index bef33d99c..593d5eb61 100644 --- a/raphael/raphael.d.ts +++ b/raphael/raphael.d.ts @@ -104,79 +104,79 @@ interface RaphaelSet { exclude(element: RaphaelElement): boolean; forEach(callback: Function, thisArg?: any): RaphaelSet; pop(): RaphaelElement; - push(...RaphaelElement: any[]): RaphaelElement; + push(...RaphaelElement: any[]): RaphaelSet; splice(index: number, count: number): RaphaelSet; splice(index: number, count: number, ...insertion: RaphaelElement[]): RaphaelSet; length: number; [key: number]: RaphaelElement; - animate(params: { [key: string]: any; }, ms: number, easing?: string, callback?: Function): RaphaelElement; - animate(animation: RaphaelAnimation): RaphaelElement; - animateWith(el: RaphaelElement, anim: RaphaelAnimation, params: any, ms: number, easing?: string, callback?: Function): RaphaelElement; - animateWith(el: RaphaelElement, anim: RaphaelAnimation, animation: RaphaelAnimation): RaphaelElement; - attr(attrName: string, value: any): RaphaelElement; - attr(params: { [key: string]: any; }): RaphaelElement; + animate(params: { [key: string]: any; }, ms: number, easing?: string, callback?: Function): RaphaelSet; + animate(animation: RaphaelAnimation): RaphaelSet; + animateWith(el: RaphaelElement, anim: RaphaelAnimation, params: any, ms: number, easing?: string, callback?: Function): RaphaelSet; + animateWith(el: RaphaelElement, anim: RaphaelAnimation, animation: RaphaelAnimation): RaphaelSet; + attr(attrName: string, value: any): RaphaelSet; + attr(params: { [key: string]: any; }): RaphaelSet; attr(attrName: string): any; attr(attrNames: string[]): any[]; - click(handler: Function): RaphaelElement; - clone(): RaphaelElement; + click(handler: Function): RaphaelSet; + clone(): RaphaelSet; data(key: string): any; - data(key: string, value: any): RaphaelElement; - dblclick(handler: Function): RaphaelElement; - drag(onmove: (dx: number, dy: number, x: number, y: number, event: DragEvent) =>{ }, onstart: (x: number, y: number, event: DragEvent) =>{ }, onend: (DragEvent: any) =>{ }, mcontext?: any, scontext?: any, econtext?: any): RaphaelElement; + data(key: string, value: any): RaphaelSet; + dblclick(handler: Function): RaphaelSet; + drag(onmove: (dx: number, dy: number, x: number, y: number, event: DragEvent) =>{ }, onstart: (x: number, y: number, event: DragEvent) =>{ }, onend: (DragEvent: any) =>{ }, mcontext?: any, scontext?: any, econtext?: any): RaphaelSet; getBBox(isWithoutTransform?: boolean): BoundingBox; glow(glow?: { width?: number; fill?: boolean; opacity?: number; offsetx?: number; offsety?: number; color?: string; }): RaphaelSet; - hide(): RaphaelElement; - hover(f_in: Function, f_out: Function, icontext?: any, ocontext?: any): RaphaelElement; + hide(): RaphaelSet; + hover(f_in: Function, f_out: Function, icontext?: any, ocontext?: any): RaphaelSet; id: string; - insertAfter(): RaphaelElement; - insertBefore(): RaphaelElement; + insertAfter(): RaphaelSet; + insertBefore(): RaphaelSet; isPointInside(x: number, y: number): boolean; isVisible(): boolean; matrix: RaphaelMatrix; - mousedown(handler: Function): RaphaelElement; - mousemove(handler: Function): RaphaelElement; - mouseout(handler: Function): RaphaelElement; - mouseover(handler: Function): RaphaelElement; - mouseup(handler: Function): RaphaelElement; - next: RaphaelElement; - onDragOver(f: Function): RaphaelElement; + mousedown(handler: Function): RaphaelSet; + mousemove(handler: Function): RaphaelSet; + mouseout(handler: Function): RaphaelSet; + mouseover(handler: Function): RaphaelSet; + mouseup(handler: Function): RaphaelSet; + next: RaphaelSet; + onDragOver(f: Function): RaphaelSet; paper: RaphaelPaper; - pause(anim?: RaphaelAnimation): RaphaelElement; - prev: RaphaelElement; + pause(anim?: RaphaelAnimation): RaphaelSet; + prev: RaphaelSet; raphael: RaphaelStatic; remove(): void; - removeData(key?: string): RaphaelElement; - resume(anim?: RaphaelAnimation): RaphaelElement; + removeData(key?: string): RaphaelSet; + resume(anim?: RaphaelAnimation): RaphaelSet; setTime(anim: RaphaelAnimation): void; - setTime(anim: RaphaelAnimation, value: number): RaphaelElement; - show(): RaphaelElement; + setTime(anim: RaphaelAnimation, value: number): RaphaelSet; + show(): RaphaelSet; status(): { anim: RaphaelAnimation; status: number; }[]; status(anim: RaphaelAnimation): number; - status(anim: RaphaelAnimation, value: number): RaphaelElement; - stop(anim?: RaphaelAnimation): RaphaelElement; - toBack(): RaphaelElement; - toFront(): RaphaelElement; - touchcancel(handler: Function): RaphaelElement; - touchend(handler: Function): RaphaelElement; - touchmove(handler: Function): RaphaelElement; - touchstart(handler: Function): RaphaelElement; + status(anim: RaphaelAnimation, value: number): RaphaelSet; + stop(anim?: RaphaelAnimation): RaphaelSet; + toBack(): RaphaelSet; + toFront(): RaphaelSet; + touchcancel(handler: Function): RaphaelSet; + touchend(handler: Function): RaphaelSet; + touchmove(handler: Function): RaphaelSet; + touchstart(handler: Function): RaphaelSet; transform(): string; - transform(tstr: string): RaphaelElement; - unclick(handler: Function): RaphaelElement; - undblclick(handler: Function): RaphaelElement; - undrag(): RaphaelElement; - unhover(): RaphaelElement; - unhover(f_in: Function, f_out: Function): RaphaelElement; - unmousedown(handler: Function): RaphaelElement; - unmousemove(handler: Function): RaphaelElement; - unmouseout(handler: Function): RaphaelElement; - unmouseover(handler: Function): RaphaelElement; - unmouseup(handler: Function): RaphaelElement; - untouchcancel(handler: Function): RaphaelElement; - untouchend(handler: Function): RaphaelElement; - untouchmove(handler: Function): RaphaelElement; - untouchstart(handler: Function): RaphaelElement; + transform(tstr: string): RaphaelSet; + unclick(handler: Function): RaphaelSet; + undblclick(handler: Function): RaphaelSet; + undrag(): RaphaelSet; + unhover(): RaphaelSet; + unhover(f_in: Function, f_out: Function): RaphaelSet; + unmousedown(handler: Function): RaphaelSet; + unmousemove(handler: Function): RaphaelSet; + unmouseout(handler: Function): RaphaelSet; + unmouseover(handler: Function): RaphaelSet; + unmouseup(handler: Function): RaphaelSet; + untouchcancel(handler: Function): RaphaelSet; + untouchend(handler: Function): RaphaelSet; + untouchmove(handler: Function): RaphaelSet; + untouchstart(handler: Function): RaphaelSet; } interface RaphaelMatrix { diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts index c220b3c24..41b352af3 100644 --- a/react-router/react-router-test.ts +++ b/react-router/react-router-test.ts @@ -263,6 +263,7 @@ class CreateTest { v: Router.Router; constructor() { + // React.createElement() version this.v = Router.create({ routes: React.createElement(Router.Route, null) }); @@ -271,6 +272,16 @@ class CreateTest { location: Router.HistoryLocation, scrollBehavior: Router.ImitateBrowserBehavior }); + + // React.createFactory() version + this.v = Router.create({ + routes: React.createFactory(Router.Route)() + }); + this.v = Router.create({ + routes: React.createFactory(Router.Route)(), + location: Router.HistoryLocation, + scrollBehavior: Router.ImitateBrowserBehavior + }); } run() { @@ -281,12 +292,21 @@ class CreateTest { class RunTest { constructor() { + // React.createElement() version var v1: Router.Router = Router.run(React.createElement(Router.Route, null), (Handler) => { React.render(React.createElement(Handler, null), document.body); }); var v2: Router.Router = Router.run(React.createElement(Router.Route, null), Router.HistoryLocation, (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); + + // React.createFactory() version + var v3: Router.Router = Router.run(React.createFactory(Router.Route)(), (Handler) => { + React.render(React.createElement(Handler, null), document.body); + }); + var v4: Router.Router = Router.run(React.createFactory(Router.Route)(), Router.HistoryLocation, (Handler, state) => { + React.render(React.createElement(Handler, null), document.body); + }); } } diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 8f63f2d69..58ec9069a 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -179,7 +179,7 @@ declare module ReactRouter { } interface RouterCreateOption { - routes: Route; + routes: React.ReactElement; location?: LocationBase; scrollBehavior?: ScrollBehaviorBase; } @@ -187,8 +187,8 @@ declare module ReactRouter { type RouterRunCallback = (Handler: Router, state: RouterState) => void; function create(options: RouterCreateOption): Router; - function run(routes: Route, callback: RouterRunCallback): Router; - function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; + function run(routes: React.ReactElement, callback: RouterRunCallback): Router; + function run(routes: React.ReactElement, location: LocationBase, callback: RouterRunCallback): Router; // diff --git a/react/react-addons-global.d.ts b/react/react-addons-global.d.ts index 891e0d101..bccd3f427 100644 --- a/react/react-addons-global.d.ts +++ b/react/react-addons-global.d.ts @@ -77,9 +77,9 @@ declare module React { // ---------------------------------------------------------------------- interface UpdateSpec { - $set: any; - $merge: {}; - $apply(value: any): any; + $set?: any; + $merge?: {}; + $apply?(value: any): any; // [key: string]: UpdateSpec; } diff --git a/react/react-addons.d.ts b/react/react-addons.d.ts index caf0fa8e0..c4e768f27 100644 --- a/react/react-addons.d.ts +++ b/react/react-addons.d.ts @@ -812,9 +812,9 @@ declare module "react/addons" { // ---------------------------------------------------------------------- interface UpdateSpec { - $set: any; - $merge: {}; - $apply(value: any): any; + $set?: any; + $merge?: {}; + $apply?(value: any): any; // [key: string]: UpdateSpec; } diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index f2388fc12..4f48101d8 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -95,6 +95,7 @@ declare module restangular { restangularizeCollection(parent: any, element: any, route: string): ICollection; service(route: string, parent?: any): IService; stripRestangular(element: any): any; + extendModel(route: string, extender: (model: IElement) => any): void; } interface IElement extends IService { diff --git a/sinon-chai/sinon-chai-tests.ts b/sinon-chai/sinon-chai-tests.ts index 48ac47ee9..65036219e 100644 --- a/sinon-chai/sinon-chai-tests.ts +++ b/sinon-chai/sinon-chai-tests.ts @@ -1,19 +1,17 @@ -/// /// -declare var expect: chai.ExpectStatic; - import chai = require('chai'); import sinonChai = require('sinon-chai'); chai.use(sinonChai); +var expect = chai.expect; +declare var spy: Sinon.SinonSpy; +declare var anotherSpy: Sinon.SinonSpy; +declare var context: {}; +declare var match: RegExp; +// ReSharper disable WrongExpressionStatement function test() { - var spy: Function; - var anotherSpy: Function; - var context: any; - var match: any; - expect(spy).to.have.been.called; expect(spy).to.have.been.calledOnce; expect(spy).to.have.been.calledTwice; @@ -32,6 +30,10 @@ function test() { expect(spy).to.always.have.been.calledWithMatch(match); expect(spy).to.have.returned(1); expect(spy).to.have.always.returned(1); + expect(spy).to.have.thrown(new Error()); + expect(spy).to.have.thrown(Error); expect(spy).to.have.thrown('an error'); + expect(spy).to.have.always.thrown(new Error()); + expect(spy).to.have.always.thrown(Error); expect(spy).to.have.always.thrown('an error'); } diff --git a/sinon-chai/sinon-chai.d.ts b/sinon-chai/sinon-chai.d.ts index d16969dd9..03bd0e81d 100644 --- a/sinon-chai/sinon-chai.d.ts +++ b/sinon-chai/sinon-chai.d.ts @@ -1,34 +1,84 @@ -// Type definitions for sinon-chai 2.4.0 +// Type definitions for sinon-chai 2.7.0 // Project: https://github.com/domenic/sinon-chai -// Definitions by: Kazi Manzur Rashid +// Definitions by: Kazi Manzur Rashid , Jed Mao // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// -declare module chai { - interface Expect { - called: Expect; - calledOnce: Expect; - calledTwice: Expect; - calledThrice: Expect; - callCount(count: number): Expect; - calledBefore(spy: Function): Expect; - calledAfter(spy: Function): Expect; - calledWithNew: Expect; - calledOn(context: any): Expect; - calledWith(...args: any[]): Expect; - calledWithExactly(...args: any[]): Expect; - calledWithMatch(...args: any[]): Expect; - returned(returnVal: any): Expect; - thrown(errorObjOrErrorTypeStringOrNothing: any): Expect; - } +declare module Chai { interface LanguageChains { - always: Expect; + always: Assertion; + } + + interface Assertion { + /** + * true if the spy was called at least once. + */ + called: Assertion; + /** + * @param count The number of recorded calls. + */ + callCount(count: number): Assertion; + /** + * true if the spy was called exactly once. + */ + calledOnce: Assertion; + /** + * true if the spy was called exactly twice. + */ + calledTwice: Assertion; + /** + * true if the spy was called exactly thrice. + */ + calledThrice: Assertion; + /** + * Returns true if the spy was called before anotherSpy. + */ + calledBefore(anotherSpy: Sinon.SinonSpy): Assertion; + /** + * Returns true if the spy was called after anotherSpy. + */ + calledAfter(anotherSpy: Sinon.SinonSpy): Assertion; + /** + * Returns true if spy/stub was called with the new operator. Beware that + * this is inferred based on the value of the this object and the spy + * function's prototype, so it may give false positives if you actively + * return the right kind of object. + */ + calledWithNew: Assertion; + /** + * Returns true if context was this for this call. + */ + calledOn(context: any): Assertion; + /** + * Returns true if call received provided arguments (and possibly others). + */ + calledWith(...args: any[]): Assertion; + /** + * Returns true if call received provided arguments and no others. + */ + calledWithExactly(...args: any[]): Assertion; + /** + * Returns true if call received matching arguments (and possibly others). + * This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...). + */ + calledWithMatch(...args: any[]): Assertion; + /** + * Returns true if spy returned the provided value at least once. Uses + * deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) + * for strict comparison (see matchers). + */ + returned(obj: any): Assertion; + /** + * Returns true if spy threw the provided exception object at least once. + */ + thrown(obj?: Error|typeof Error|string): Assertion; } } declare module "sinon-chai" { - function exports(_chai: typeof chai, utils: any): void; - export = exports; + function sinonChai(chai: any, utils: any): void; + export = sinonChai; } diff --git a/sinon/sinon-tests.ts b/sinon/sinon-tests.ts index b9b71c10e..ccc9819e5 100644 --- a/sinon/sinon-tests.ts +++ b/sinon/sinon-tests.ts @@ -1,95 +1,91 @@ /// function once(fn: Function) { - var returnValue: any, called = false; - return function () { - if (!called) { - called = true; - returnValue = fn.apply(this, arguments); - } - return returnValue; - }; + var returnValue: any, called = false; + return function () { + if (!called) { + called = true; + returnValue = fn.apply(this, arguments); + } + return returnValue; + }; } function testOne() { - var callback = sinon.spy(); - var proxy = once(callback); - proxy(); - if (callback.calledOnce) { console.log("test1 calledOnce success"); } else { console.log("test1 calledOnce failure"); } + var callback = sinon.spy(); + var proxy = once(callback); + proxy(); + if (callback.calledOnce) { console.log("test1 calledOnce success"); } else { console.log("test1 calledOnce failure"); } } function testTwo() { - var callback = sinon.spy(() => {}); - var proxy = once(callback); - proxy(); - proxy(); - if (callback.calledOnce) { console.log("test2 calledOnce success"); } else { console.log("test2 calledOnce failure"); } + var callback = sinon.spy(() => {}); + var proxy = once(callback); + proxy(); + proxy(); + if (callback.calledOnce) { console.log("test2 calledOnce success"); } else { console.log("test2 calledOnce failure"); } } function testThree() { - var obj = { thisObj: true }; - var callback = sinon.spy({}, "method"); - var proxy = once(callback); - proxy.call(obj, callback, 1, 2, 3); - if (callback.calledOn(obj)) { console.log("test3 calledOn success"); } else { console.log("test3 calledOn failure"); } - if (callback.calledWith(callback, 1, 2, 3)) { console.log("test3 calledWith success"); } else { console.log("test3 calledWith failure"); } + var obj = { thisObj: true }; + var callback = sinon.spy({}, "method"); + var proxy = once(callback); + proxy.call(obj, callback, 1, 2, 3); + if (callback.calledOn(obj)) { console.log("test3 calledOn success"); } else { console.log("test3 calledOn failure"); } + if (callback.calledWith(callback, 1, 2, 3)) { console.log("test3 calledWith success"); } else { console.log("test3 calledWith failure"); } } function testFour() { - var obj = { thisObj: true }; - var callback = sinon.stub().returns(42); - var proxy = once(callback); - var val = proxy.apply(callback, [1, 2, 3]); - if (val == 42) { console.log("test4 returns success"); } else { console.log("test4 returns failure"); } + var callback = sinon.stub().returns(42); + var proxy = once(callback); + var val = proxy.apply(callback, [1, 2, 3]); + if (val === 42) { console.log("test4 returns success"); } else { console.log("test4 returns failure"); } } function testFive() { - var obj = { thisObj: true }; - var callback = sinon.stub().returnsArg(1); - var proxy = once(callback); - var val = proxy.apply(callback, [1, 2, 3]); - if (val == 2) { console.log("test5 returnsArg success"); } else { console.log("test5 returnsArg failure"); } + var callback = sinon.stub().returnsArg(1); + var proxy = once(callback); + var val = proxy.apply(callback, [1, 2, 3]); + if (val === 2) { console.log("test5 returnsArg success"); } else { console.log("test5 returnsArg failure"); } } var objectUnderTest: any = { - process: function (obj: any) { - // It doesn't really matter what's here because the stub is going to replace this function - var dummy = true; - if (dummy) { return obj.success(99); } else { obj.failure(99); } - } + process: (obj: any) => { + // It doesn't really matter what's here because the stub is going to replace this function + return obj.success(99); + } }; function testSix() { - var obj = { thisObj: true }; - var stub = sinon.stub(objectUnderTest, "process").yieldsTo("success"); - var val = objectUnderTest.process({ - success: function () { console.log("test6 yieldsTo success"); }, - failure: function () { console.log("test6 yieldsTo failure"); } - }); - stub.restore(); + var stub = sinon.stub(objectUnderTest, "process").yieldsTo("success"); + objectUnderTest.process({ + success: () => { console.log("test6 yieldsTo success"); }, + failure: () => { console.log("test6 yieldsTo failure"); } + }); + stub.restore(); } function testSeven() { - var obj = { functionToTest : function () { } }; - var mockObj = sinon.mock(obj); - obj.functionToTest(); - mockObj.expects('functionToTest').once(); + var obj = { functionToTest : () => { } }; + var mockObj = sinon.mock(obj); + obj.functionToTest(); + mockObj.expects('functionToTest').once(); } function testEight() { - var combinedMatcher = sinon.match.typeOf("object").and(sinon.match.has("pages")); + sinon.match.typeOf("object").and(sinon.match.has("pages")); } function testSandbox() { - var sandbox = sinon.sandbox.create(); - if (sandbox.spy().called) { - sandbox.stub(objectUnderTest, "process").yieldsTo("success"); - sandbox.mock(objectUnderTest).expects("process").once(); - } - sandbox.useFakeTimers(); - sandbox.useFakeXMLHttpRequest(); - sandbox.useFakeServer(); - sandbox.restore(); + var sandbox = sinon.sandbox.create(); + if (sandbox.spy().called) { + sandbox.stub(objectUnderTest, "process").yieldsTo("success"); + sandbox.mock(objectUnderTest).expects("process").once(); + } + sandbox.useFakeTimers(); + sandbox.useFakeXMLHttpRequest(); + sandbox.useFakeServer(); + sandbox.restore(); } testOne(); diff --git a/sinon/sinon.d.ts b/sinon/sinon.d.ts index 4b8656661..7dc5bc1d6 100644 --- a/sinon/sinon.d.ts +++ b/sinon/sinon.d.ts @@ -3,415 +3,417 @@ // Definitions by: William Sears // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface SinonSpyCallApi { - // Properties - thisValue: any; - args: any[]; - exception: any; - returnValue: any; +declare module Sinon { + interface SinonSpyCallApi { + // Properties + thisValue: any; + args: any[]; + exception: any; + returnValue: any; - // Methods - calledOn(obj: any): boolean; - calledWith(...args: any[]): boolean; - calledWithExactly(...args: any[]): boolean; - calledWithMatch(...args: SinonMatcher[]): boolean; - notCalledWith(...args: any[]): boolean; - notCalledWithMatch(...args: SinonMatcher[]): boolean; - returned(value: any): boolean; - threw(): boolean; - threw(type: string): boolean; - threw(obj: any): boolean; - callArg(pos: number): void; - callArgOn(pos: number, obj: any, ...args: any[]): void; - callArgWith(pos: number, ...args: any[]): void; - callArgOnWith(pos: number, obj: any, ...args: any[]): void; - yield(...args: any[]): void; - yieldOn(obj: any, ...args: any[]): void; - yieldTo(property: string, ...args: any[]): void; - yieldToOn(property: string, obj: any, ...args: any[]): void; + // Methods + calledOn(obj: any): boolean; + calledWith(...args: any[]): boolean; + calledWithExactly(...args: any[]): boolean; + calledWithMatch(...args: SinonMatcher[]): boolean; + notCalledWith(...args: any[]): boolean; + notCalledWithMatch(...args: SinonMatcher[]): boolean; + returned(value: any): boolean; + threw(): boolean; + threw(type: string): boolean; + threw(obj: any): boolean; + callArg(pos: number): void; + callArgOn(pos: number, obj: any, ...args: any[]): void; + callArgWith(pos: number, ...args: any[]): void; + callArgOnWith(pos: number, obj: any, ...args: any[]): void; + yield(...args: any[]): void; + yieldOn(obj: any, ...args: any[]): void; + yieldTo(property: string, ...args: any[]): void; + yieldToOn(property: string, obj: any, ...args: any[]): void; + } + + interface SinonSpyCall extends SinonSpyCallApi { + calledBefore(call: SinonSpyCall): boolean; + calledAfter(call: SinonSpyCall): boolean; + calledWithNew(call: SinonSpyCall): boolean; + } + + interface SinonSpy extends SinonSpyCallApi { + // Properties + callCount: number; + called: boolean; + notCalled: boolean; + calledOnce: boolean; + calledTwice: boolean; + calledThrice: boolean; + firstCall: SinonSpyCall; + secondCall: SinonSpyCall; + thirdCall: SinonSpyCall; + lastCall: SinonSpyCall; + thisValues: any[]; + args: any[][]; + exceptions: any[]; + returnValues: any[]; + + // Methods + (...args: any[]): any; + calledBefore(anotherSpy: SinonSpy): boolean; + calledAfter(anotherSpy: SinonSpy): boolean; + calledWithNew(spy: SinonSpy): boolean; + withArgs(...args: any[]): SinonSpy; + alwaysCalledOn(obj: any): boolean; + alwaysCalledWith(...args: any[]): boolean; + alwaysCalledWithExactly(...args: any[]): boolean; + alwaysCalledWithMatch(...args: SinonMatcher[]): boolean; + neverCalledWith(...args: any[]): boolean; + neverCalledWithMatch(...args: SinonMatcher[]): boolean; + alwaysThrew(): boolean; + alwaysThrew(type: string): boolean; + alwaysThrew(obj: any): boolean; + alwaysReturned(): boolean; + invokeCallback(...args: any[]): void; + getCall(n: number): SinonSpyCall; + reset(): void; + printf(format: string, ...args: any[]): string; + restore(): void; + } + + interface SinonSpyStatic { + (): SinonSpy; + (func: any): SinonSpy; + (obj: any, method: string): SinonSpy; + } + + interface SinonStatic { + spy: SinonSpyStatic; + } + + interface SinonStub extends SinonSpy { + resetBehavior(): void; + returns(obj: any): SinonStub; + returnsArg(index: number): SinonStub; + throws(type?: string): SinonStub; + throws(obj: any): SinonStub; + callsArg(index: number): SinonStub; + callsArgOn(index: number, context: any): SinonStub; + callsArgWith(index: number, ...args: any[]): SinonStub; + callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; + callsArgAsync(index: number): SinonStub; + callsArgOnAsync(index: number, context: any): SinonStub; + callsArgWithAsync(index: number, ...args: any[]): SinonStub; + callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; + onCall(n: number): SinonStub; + onFirstCall(): SinonStub; + onSecondCall(): SinonStub; + onThirdCall(): SinonStub; + yields(...args: any[]): SinonStub; + yieldsOn(context: any, ...args: any[]): SinonStub; + yieldsTo(property: string, ...args: any[]): SinonStub; + yieldsToOn(property: string, context: any, ...args: any[]): SinonStub; + yieldsAsync(...args: any[]): SinonStub; + yieldsOnAsync(context: any, ...args: any[]): SinonStub; + yieldsToAsync(property: string, ...args: any[]): SinonStub; + yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; + withArgs(...args: any[]): SinonStub; + } + + interface SinonStubStatic { + (): SinonStub; + (obj: any): SinonStub; + (obj: any, method: string): SinonStub; + (obj: any, method: string, func: any): SinonStub; + } + + interface SinonStatic { + stub: SinonStubStatic; + } + + interface SinonExpectation extends SinonStub { + atLeast(n: number): SinonExpectation; + atMost(n: number): SinonExpectation; + never(): SinonExpectation; + once(): SinonExpectation; + twice(): SinonExpectation; + thrice(): SinonExpectation; + exactly(n: number): SinonExpectation; + withArgs(...args: any[]): SinonExpectation; + withExactArgs(...args: any[]): SinonExpectation; + on(obj: any): SinonExpectation; + verify(): SinonExpectation; + restore(): void; + } + + interface SinonExpectationStatic { + create(methodName?: string): SinonExpectation; + } + + interface SinonMock { + expects(method: string): SinonExpectation; + restore(): void; + verify(): void; + } + + interface SinonMockStatic { + (): SinonExpectation; + (obj: any): SinonMock; + } + + interface SinonStatic { + expectation: SinonExpectationStatic; + mock: SinonMockStatic; + } + + interface SinonFakeTimers { + now: number; + create(now: number): SinonFakeTimers; + setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; + clearTimeout(id: number): void; + setInterval(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number; + clearInterval(id: number): void; + tick(ms: number): number; + reset(): void; + Date(): Date; + Date(year: number): Date; + Date(year: number, month: number): Date; + Date(year: number, month: number, day: number): Date; + Date(year: number, month: number, day: number, hour: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; + restore(): void; + } + + interface SinonFakeTimersStatic { + (): SinonFakeTimers; + (...timers: string[]): SinonFakeTimers; + (now: number, ...timers: string[]): SinonFakeTimers; + } + + interface SinonStatic { + useFakeTimers: SinonFakeTimersStatic; + clock: SinonFakeTimers; + } + + interface SinonFakeUploadProgress { + eventListeners: { + progress: any[]; + load: any[]; + abort: any[]; + error: any[]; + }; + + addEventListener(event: string, listener: (e: Event) => any): void; + removeEventListener(event: string, listener: (e: Event) => any): void; + dispatchEvent(event: Event): void; + } + + interface SinonFakeXMLHttpRequest { + // Properties + onCreate: (xhr: SinonFakeXMLHttpRequest) => void; + url: string; + method: string; + requestHeaders: any; + requestBody: string; + status: number; + statusText: string; + async: boolean; + username: string; + password: string; + withCredentials: boolean; + upload: SinonFakeUploadProgress; + responseXML: Document; + getResponseHeader(header: string): string; + getAllResponseHeaders(): any; + + // Methods + restore(): void; + useFilters: boolean; + addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; + setResponseHeaders(headers: any): void; + setResponseBody(body: string): void; + respond(status: number, headers: any, body: string): void; + autoRespond(ms: number): void; + } + + interface SinonFakeXMLHttpRequestStatic { + (): SinonFakeXMLHttpRequest; + } + + interface SinonStatic { + useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; + FakeXMLHttpRequest: SinonFakeXMLHttpRequest; + } + + interface SinonFakeServer { + // Properties + autoRespond: boolean; + autoRespondAfter: number; + fakeHTTPMethods: boolean; + getHTTPMethod: (request: SinonFakeXMLHttpRequest) => string; + requests: SinonFakeXMLHttpRequest[]; + + // Methods + respondWith(body: string): void; + respondWith(response: any[]): void; + respondWith(fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(url: string, body: string): void; + respondWith(url: string, response: any[]): void; + respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(method: string, url: string, body: string): void; + respondWith(method: string, url: string, response: any[]): void; + respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(url: RegExp, body: string): void; + respondWith(url: RegExp, response: any[]): void; + respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respondWith(method: string, url: RegExp, body: string): void; + respondWith(method: string, url: RegExp, response: any[]): void; + respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + respond(): void; + restore(): void; + } + + interface SinonFakeServerStatic { + create(): SinonFakeServer; + } + + interface SinonStatic { + fakeServer: SinonFakeServerStatic; + fakeServerWithClock: SinonFakeServerStatic; + } + + interface SinonExposeOptions { + prefix?: string; + includeFail?: boolean; + } + + interface SinonAssert { + // Properties + failException: string; + fail: (message?: string) => void; // Overridable + pass: (assertion: any) => void; // Overridable + + // Methods + notCalled(spy: SinonSpy): void; + called(spy: SinonSpy): void; + calledOnce(spy: SinonSpy): void; + calledTwice(spy: SinonSpy): void; + calledThrice(spy: SinonSpy): void; + callCount(spy: SinonSpy, count: number): void; + callOrder(...spies: SinonSpy[]): void; + calledOn(spy: SinonSpy, obj: any): void; + alwaysCalledOn(spy: SinonSpy, obj: any): void; + calledWith(spy: SinonSpy, ...args: any[]): void; + alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; + neverCalledWith(spy: SinonSpy, ...args: any[]): void; + calledWithExactly(spy: SinonSpy, ...args: any[]): void; + alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; + calledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void; + alwaysCalledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void; + neverCalledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void; + threw(spy: SinonSpy): void; + threw(spy: SinonSpy, exception: string): void; + threw(spy: SinonSpy, exception: any): void; + alwaysThrew(spy: SinonSpy): void; + alwaysThrew(spy: SinonSpy, exception: string): void; + alwaysThrew(spy: SinonSpy, exception: any): void; + expose(obj: any, options?: SinonExposeOptions): void; + } + + interface SinonStatic { + assert: SinonAssert; + } + + interface SinonMatcher { + and(expr: SinonMatcher): SinonMatcher; + or(expr: SinonMatcher): SinonMatcher; + } + + interface SinonMatch { + (value: number): SinonMatcher; + (value: string): SinonMatcher; + (expr: RegExp): SinonMatcher; + (obj: any): SinonMatcher; + (callback: (value: any) => boolean): SinonMatcher; + any: SinonMatcher; + defined: SinonMatcher; + truthy: SinonMatcher; + falsy: SinonMatcher; + bool: SinonMatcher; + number: SinonMatcher; + string: SinonMatcher; + object: SinonMatcher; + func: SinonMatcher; + array: SinonMatcher; + regexp: SinonMatcher; + date: SinonMatcher; + same(obj: any): SinonMatcher; + typeOf(type: string): SinonMatcher; + instanceOf(type: any): SinonMatcher; + has(property: string, expect?: any): SinonMatcher; + hasOwn(property: string, expect?: any): SinonMatcher; + } + + interface SinonStatic { + match: SinonMatch; + } + + interface SinonSandboxConfig { + injectInto?: any; + properties?: string[]; + useFakeTimers?: any; + useFakeServer?: any; + } + + interface SinonSandbox { + clock: SinonFakeTimers; + requests: SinonFakeXMLHttpRequest; + server: SinonFakeServer; + spy: SinonSpyStatic; + stub: SinonStubStatic; + mock: SinonMockStatic; + useFakeTimers: SinonFakeTimersStatic; + useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; + useFakeServer(): SinonFakeServer; + restore(): void; + } + + interface SinonSandboxStatic { + create(): SinonSandbox; + create(config: SinonSandboxConfig): SinonSandbox; + } + + interface SinonStatic { + sandbox: SinonSandboxStatic; + } + + interface SinonTestConfig { + injectIntoThis?: boolean; + injectInto?: any; + properties?: string[]; + useFakeTimers?: boolean; + useFakeServer?: boolean; + } + + interface SinonTestWrapper extends SinonSandbox { + (...args: any[]): any; + } + + interface SinonStatic { + config: SinonTestConfig; + test(fn: (...args: any[]) => any): SinonTestWrapper; + testCase(tests: any): any; + } + + // Utility overridables + interface SinonStatic { + createStubInstance(constructor: any): SinonStub; + format(obj: any): string; + log(message: string): void; + restore(object: any): void; + } } -interface SinonSpyCall extends SinonSpyCallApi { - calledBefore(call: SinonSpyCall): boolean; - calledAfter(call: SinonSpyCall): boolean; - calledWithNew(call: SinonSpyCall): boolean; -} - -interface SinonSpy extends SinonSpyCallApi { - // Properties - callCount: number; - called: boolean; - notCalled: boolean; - calledOnce: boolean; - calledTwice: boolean; - calledThrice: boolean; - firstCall: SinonSpyCall; - secondCall: SinonSpyCall; - thirdCall: SinonSpyCall; - lastCall: SinonSpyCall; - thisValues: any[]; - args: any[][]; - exceptions: any[]; - returnValues: any[]; - - // Methods - (...args: any[]): any; - calledBefore(anotherSpy: SinonSpy): boolean; - calledAfter(anotherSpy: SinonSpy): boolean; - calledWithNew(spy: SinonSpy): boolean; - withArgs(...args: any[]): SinonSpy; - alwaysCalledOn(obj: any): boolean; - alwaysCalledWith(...args: any[]): boolean; - alwaysCalledWithExactly(...args: any[]): boolean; - alwaysCalledWithMatch(...args: SinonMatcher[]): boolean; - neverCalledWith(...args: any[]): boolean; - neverCalledWithMatch(...args: SinonMatcher[]): boolean; - alwaysThrew(): boolean; - alwaysThrew(type: string): boolean; - alwaysThrew(obj: any): boolean; - alwaysReturned(): boolean; - invokeCallback(...args: any[]): void; - getCall(n: number): SinonSpyCall; - reset(): void; - printf(format: string, ...args: any[]): string; - restore(): void; -} - -interface SinonSpyStatic { - (): SinonSpy; - (func: any): SinonSpy; - (obj: any, method: string): SinonSpy; -} - -interface SinonStatic { - spy: SinonSpyStatic; -} - -interface SinonStub extends SinonSpy { - resetBehavior(): void; - returns(obj: any): SinonStub; - returnsArg(index: number): SinonStub; - throws(type?: string): SinonStub; - throws(obj: any): SinonStub; - callsArg(index: number): SinonStub; - callsArgOn(index: number, context: any): SinonStub; - callsArgWith(index: number, ...args: any[]): SinonStub; - callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; - callsArgAsync(index: number): SinonStub; - callsArgOnAsync(index: number, context: any): SinonStub; - callsArgWithAsync(index: number, ...args: any[]): SinonStub; - callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; - onCall(n: number): SinonStub; - onFirstCall(): SinonStub; - onSecondCall(): SinonStub; - onThirdCall(): SinonStub; - yields(...args: any[]): SinonStub; - yieldsOn(context: any, ...args: any[]): SinonStub; - yieldsTo(property: string, ...args: any[]): SinonStub; - yieldsToOn(property: string, context: any, ...args: any[]): SinonStub; - yieldsAsync(...args: any[]): SinonStub; - yieldsOnAsync(context: any, ...args: any[]): SinonStub; - yieldsToAsync(property: string, ...args: any[]): SinonStub; - yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; - withArgs(...args: any[]): SinonStub; -} - -interface SinonStubStatic { - (): SinonStub; - (obj: any): SinonStub; - (obj: any, method: string): SinonStub; - (obj: any, method: string, func: any): SinonStub; -} - -interface SinonStatic { - stub: SinonStubStatic; -} - -interface SinonExpectation extends SinonStub { - atLeast(n: number): SinonExpectation; - atMost(n: number): SinonExpectation; - never(): SinonExpectation; - once(): SinonExpectation; - twice(): SinonExpectation; - thrice(): SinonExpectation; - exactly(n: number): SinonExpectation; - withArgs(...args: any[]): SinonExpectation; - withExactArgs(...args: any[]): SinonExpectation; - on(obj: any): SinonExpectation; - verify(): SinonExpectation; - restore(): void; -} - -interface SinonExpectationStatic { - create(methodName?: string): SinonExpectation; -} - -interface SinonMock { - expects(method: string): SinonExpectation; - restore(): void; - verify(): void; -} - -interface SinonMockStatic { - (): SinonExpectation; - (obj: any): SinonMock; -} - -interface SinonStatic { - expectation: SinonExpectationStatic; - mock: SinonMockStatic; -} - -interface SinonFakeTimers { - now: number; - create(now: number): SinonFakeTimers; - setTimeout(callback: (...args: any[]) => void , timeout: number, ...args: any[]): number; - clearTimeout(id: number): void; - setInterval(callback: (...args: any[]) => void , timeout: number, ...args: any[]): number; - clearInterval(id: number): void; - tick(ms: number): number; - reset(): void; - Date(): Date; - Date(year: number): Date; - Date(year: number, month: number): Date; - Date(year: number, month: number, day: number): Date; - Date(year: number, month: number, day: number, hour: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; - Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; - restore(): void; -} - -interface SinonFakeTimersStatic { - (): SinonFakeTimers; - (...timers: string[]): SinonFakeTimers; - (now: number, ...timers: string[]): SinonFakeTimers; -} - -interface SinonStatic { - useFakeTimers: SinonFakeTimersStatic; - clock: SinonFakeTimers; -} - -interface SinonFakeUploadProgress { - eventListeners: { - progress: any[]; - load: any[]; - abort: any[]; - error: any[]; - }; - - addEventListener(event: string, listener: (e: Event) => any): void; - removeEventListener(event: string, listener: (e: Event) => any): void; - dispatchEvent(event: Event): void; -} - -interface SinonFakeXMLHttpRequest { - // Properties - onCreate: (xhr: SinonFakeXMLHttpRequest) => void; - url: string; - method: string; - requestHeaders: any; - requestBody: string; - status: number; - statusText: string; - async: boolean; - username: string; - password: string; - withCredentials: boolean; - upload: SinonFakeUploadProgress; - responseXML: Document; - getResponseHeader(header: string): string; - getAllResponseHeaders(): any; - - // Methods - restore(): void; - useFilters: boolean; - addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; - setResponseHeaders(headers: any): void; - setResponseBody(body: string): void; - respond(status: number, headers: any, body: string): void; - autoRespond(ms: number): void; -} - -interface SinonFakeXMLHttpRequestStatic { - (): SinonFakeXMLHttpRequest; -} - -interface SinonStatic { - useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; - FakeXMLHttpRequest: SinonFakeXMLHttpRequest; -} - -interface SinonFakeServer { - // Properties - autoRespond: boolean; - autoRespondAfter: number; - fakeHTTPMethods: boolean; - getHTTPMethod: (request: SinonFakeXMLHttpRequest) => string; - requests: SinonFakeXMLHttpRequest[]; - - // Methods - respondWith(body: string): void; - respondWith(response: any[]): void; - respondWith(fn: (xhr: SinonFakeXMLHttpRequest) => void ): void; - respondWith(url: string, body: string): void; - respondWith(url: string, response: any[]): void; - respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void ): void; - respondWith(method: string, url: string, body: string): void; - respondWith(method: string, url: string, response: any[]): void; - respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void ): void; - respondWith(url: RegExp, body: string): void; - respondWith(url: RegExp, response: any[]): void; - respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void ): void; - respondWith(method: string, url: RegExp, body: string): void; - respondWith(method: string, url: RegExp, response: any[]): void; - respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void ): void; - respond(): void; - restore(): void; -} - -interface SinonFakeServerStatic { - create(): SinonFakeServer; -} - -interface SinonStatic { - fakeServer: SinonFakeServerStatic; - fakeServerWithClock: SinonFakeServerStatic; -} - -interface SinonExposeOptions { - prefix?: string; - includeFail?: boolean; -} - -interface SinonAssert { - // Properties - failException: string; - fail: (message?: string) => void; // Overridable - pass: (assertion: any) => void; // Overridable - - // Methods - notCalled(spy: SinonSpy): void; - called(spy: SinonSpy): void; - calledOnce(spy: SinonSpy): void; - calledTwice(spy: SinonSpy): void; - calledThrice(spy: SinonSpy): void; - callCount(spy: SinonSpy, count: number): void; - callOrder(...spies: SinonSpy[]): void; - calledOn(spy: SinonSpy, obj: any): void; - alwaysCalledOn(spy: SinonSpy, obj: any): void; - calledWith(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; - neverCalledWith(spy: SinonSpy, ...args: any[]): void; - calledWithExactly(spy: SinonSpy, ...args: any[]): void; - alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; - calledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void; - alwaysCalledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void; - neverCalledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void; - threw(spy: SinonSpy): void; - threw(spy: SinonSpy, exception: string): void; - threw(spy: SinonSpy, exception: any): void; - alwaysThrew(spy: SinonSpy): void; - alwaysThrew(spy: SinonSpy, exception: string): void; - alwaysThrew(spy: SinonSpy, exception: any): void; - expose(obj: any, options?: SinonExposeOptions): void; -} - -interface SinonStatic { - assert: SinonAssert; -} - -interface SinonMatcher { - and(expr: SinonMatcher): SinonMatcher; - or(expr: SinonMatcher): SinonMatcher; -} - -interface SinonMatch { - (value: number): SinonMatcher; - (value: string): SinonMatcher; - (expr: RegExp): SinonMatcher; - (obj: any): SinonMatcher; - (callback: (value: any) => boolean): SinonMatcher; - any: SinonMatcher; - defined: SinonMatcher; - truthy: SinonMatcher; - falsy: SinonMatcher; - bool: SinonMatcher; - number: SinonMatcher; - string: SinonMatcher; - object: SinonMatcher; - func: SinonMatcher; - array: SinonMatcher; - regexp: SinonMatcher; - date: SinonMatcher; - same(obj: any): SinonMatcher; - typeOf(type: string): SinonMatcher; - instanceOf(type: any): SinonMatcher; - has(property: string, expect?: any): SinonMatcher; - hasOwn(property: string, expect?: any): SinonMatcher; -} - -interface SinonStatic { - match: SinonMatch; -} - -interface SinonSandboxConfig { - injectInto?: any; - properties?: string[]; - useFakeTimers?: any; - useFakeServer?: any; -} - -interface SinonSandbox { - clock: SinonFakeTimers; - requests: SinonFakeXMLHttpRequest; - server: SinonFakeServer; - spy: SinonSpyStatic; - stub: SinonStubStatic; - mock: SinonMockStatic; - useFakeTimers: SinonFakeTimersStatic; - useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; - useFakeServer(): SinonFakeServer; - restore(): void; -} - -interface SinonSandboxStatic { - create(): SinonSandbox; - create(config: SinonSandboxConfig): SinonSandbox; -} - -interface SinonStatic { - sandbox: SinonSandboxStatic; -} - -interface SinonTestConfig { - injectIntoThis?: boolean; - injectInto?: any; - properties?: string[]; - useFakeTimers?: boolean; - useFakeServer?: boolean; -} - -interface SinonTestWrapper extends SinonSandbox { - (...args: any[]): any; -} - -interface SinonStatic { - config: SinonTestConfig; - test(fn: (...args: any[]) => any): SinonTestWrapper; - testCase(tests: any): any; -} - -// Utility overridables -interface SinonStatic { - createStubInstance: (constructor: any) => SinonStub; - format: (obj: any) => string; - log: (message: string) => void; - restore(object: any): void; -} - -declare var sinon: SinonStatic; +declare var sinon: Sinon.SinonStatic; declare module "sinon" { export = sinon; diff --git a/source-map-support/source-map-support.d.ts b/source-map-support/source-map-support.d.ts index b0de346a7..31a642042 100644 --- a/source-map-support/source-map-support.d.ts +++ b/source-map-support/source-map-support.d.ts @@ -1,15 +1,17 @@ -// Type definitions for source-map-support 0.2.6 +// Type definitions for source-map-support 0.2.10 // Project: https://github.com/evanw/source-map-support // Definitions by: Bart van der Schoor // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module 'source-map-support' { /** * Output of retrieveSourceMap(). */ export interface UrlAndMap { url: string; - map: any; // string or Buffer + map: string|Buffer; } /** diff --git a/stack-trace/stack-trace-tests.ts b/stack-trace/stack-trace-tests.ts new file mode 100644 index 000000000..a0b2f8d55 --- /dev/null +++ b/stack-trace/stack-trace-tests.ts @@ -0,0 +1,8 @@ +import stackTrace = require('stack-trace'); + +var currentStackTrace = stackTrace.get(); + +var err = new Error('something went wrong'); +var trace = stackTrace.parse(err); + +var fileName = trace[0].getFileName(); diff --git a/stack-trace/stack-trace.d.ts b/stack-trace/stack-trace.d.ts new file mode 100644 index 000000000..21c12f8f2 --- /dev/null +++ b/stack-trace/stack-trace.d.ts @@ -0,0 +1,20 @@ +// Type definitions for node-stack-trace +// Project: https://github.com/felixge/node-stack-trace +// Definitions by: Exceptionless +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'stack-trace' { + export interface StackFrame { + getTypeName():string; + getFunctionName():string; + getMethodName():string; + getFileName():string; + getTypeName():string; + getLineNumber():number; + getColumnNumber():number; + isNative():boolean; + } + + export function get(belowFn?:() => void): StackFrame[]; + export function parse(err:Error): StackFrame[]; +} diff --git a/stacktrace-js/stacktrace-js-tests.ts b/stacktrace-js/stacktrace-js-tests.ts new file mode 100644 index 000000000..c4c9bcf87 --- /dev/null +++ b/stacktrace-js/stacktrace-js-tests.ts @@ -0,0 +1,24 @@ +/// + +function interestingFn() { + return 'https://github.com/exceptionless/Exceptionless'; +} + +var callback = function(stackframes:StackTrace.StackFrame[]) { + var stringifiedStack = stackframes.map(function(sf:StackTrace.StackFrame) { + return sf.toString(); + }).join('\n'); + console.log(stringifiedStack); +}; + +var errorCallback = function(err:Error) { console.log(err.message); }; + +StackTrace.get(); + +// Somewhere else... +var error = new Error('BOOM!'); +StackTrace.fromError(error); +StackTrace.generateArtificially(); + +StackTrace.instrument(interestingFn, callback, errorCallback); +StackTrace.deinstrument(interestingFn); diff --git a/stacktrace-js/stacktrace-js.d.ts b/stacktrace-js/stacktrace-js.d.ts new file mode 100644 index 000000000..9f7ce5ea2 --- /dev/null +++ b/stacktrace-js/stacktrace-js.d.ts @@ -0,0 +1,66 @@ +// Type definitions for stacktrace.js +// Project: https://github.com/stacktracejs/stacktrace.js +// Definitions by: Exceptionless +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module StackTrace { + export interface StackTraceOptions { + filter?: (stackFrame:StackFrame) => boolean; + sourceCache?: { URL:string }; + offline?: boolean; + } + + export interface StackFrame { + constructor(functionName:string, args:any, fileName:string, lineNumber:number, columnNumber:number): StackFrame; + + functionName?:string; + args?:any; + fileName?:string; + lineNumber?:number; + columnNumber?:number; + toString():string; + } + + /** + * Get a backtrace from invocation point. + * @param options Options Object + * @return Array[StackFrame] + */ + export function get(options?: StackTraceOptions): Promise; + + /** + * Given an error object, parse it. + * @param error Error object + * @param options Object for options + * @return Array[StackFrame] + */ + export function fromError(error:Error, options?:StackTraceOptions): Promise; + + /** + * Use StackGenerator to generate a backtrace. + * @param options Object options + * @returns Array[StackFrame] + */ + export function generateArtificially(options?: StackTraceOptions): Promise; + + /** + * Given a function, wrap it such that invocations trigger a callback that + * is called with a stack trace. + * + * @param {Function} fn to be instrumented + * @param {Function} callback function to call with a stack trace on invocation + * @param {Function} errorCallback optional function to call with error if unable to get stack trace. + * @param {Object} thisArg optional context object (e.g. window) + */ + export function instrument(fn:() => void, callback:(stackFrames:StackFrame[]) => void, errorCallback:(error:Error) => void, thisArg?:any): void; + + /** + * Given a function that has been instrumented, + * revert the function to it's original (non-instrumented) state. + * + * @param fn {Function} + */ + export function deinstrument(fn:() => void): void; +} diff --git a/succinct/succinct-tests.ts b/succinct/succinct-tests.ts new file mode 100644 index 000000000..7b81e5f85 --- /dev/null +++ b/succinct/succinct-tests.ts @@ -0,0 +1,31 @@ +/// + +// Call with no arguments (accepting defaults) +$(".truncate").succinct(); + +// Specify size +$(".truncate").succinct({ + size: 120 +}); + +// Specify ellipsis replacement +$(".truncate").succinct({ + omission: "→" +}); + +// Specify flag to leave trailing special characters +$(".truncate").succinct({ + ignore: false +}); + +// Combine options +$(".truncate").succinct({ + size: 120, + omission: '...', + ignore: false +}); + +// Can chain jQuery methods +$(".truncate") + .succinct() + .removeClass("truncate"); \ No newline at end of file diff --git a/succinct/succinct.d.ts b/succinct/succinct.d.ts new file mode 100644 index 000000000..59a1646e3 --- /dev/null +++ b/succinct/succinct.d.ts @@ -0,0 +1,18 @@ +// Type definitions for jQuery Succinct v1.1.0 +// Project: http://mikeking.io/succinct/ +// Definitions by: Matt Brooks +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQuerySuccinct { + interface Options { + size?: number; + omission?: string; + ignore?: boolean; + } +} + +interface JQuery { + succinct(settings?: JQuerySuccinct.Options): JQuery; +} \ No newline at end of file diff --git a/svgjs/svgjs.d.ts b/svgjs/svgjs.d.ts index 2de93541e..c04f19536 100644 --- a/svgjs/svgjs.d.ts +++ b/svgjs/svgjs.d.ts @@ -92,6 +92,8 @@ declare module svgjs { center(x:number, y:number, anchor?:boolean):Element; cx(x:number, anchor?:boolean):Element; cy(y:number, anchor?:boolean):Element; + cx(): number; + cy(): number; size(w:number, h:number, anchor?:boolean):Element; diff --git a/swipe/swipe-tests.ts b/swipe/swipe-tests.ts new file mode 100644 index 000000000..a13006ebb --- /dev/null +++ b/swipe/swipe-tests.ts @@ -0,0 +1,4 @@ +/// + +// Creation of element +var mySwipe = new Swipe(document.getElementById('slider')); \ No newline at end of file diff --git a/swipe/swipe.d.ts b/swipe/swipe.d.ts new file mode 100644 index 000000000..9cb753ef9 --- /dev/null +++ b/swipe/swipe.d.ts @@ -0,0 +1,28 @@ +// Type definitions for Swipe 2.0 +// Project: https://github.com/thebird/Swipe +// Definitions by: Andrey Kurdyumov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface SwipeOptions { + startSlide?: number; + speed?: number; + auto?: number; + continuous?: boolean; + disableScroll?: boolean; + stopPropagation?: boolean; + callback?: (index: number, elem: HTMLElement) => void; + transitionEnd?: (index: number, elem: HTMLElement) => void; +} + +declare class Swipe { + constructor(container: HTMLElement, options?: SwipeOptions); + prev(): void; + next(): void; + getPos(): number; + getNumSlides(): number; + kill(): void; + attachEvents(): void; + setup(): void; + slide(index: number, duration: number): void; +} diff --git a/tcomb/tcomb-tests.ts b/tcomb/tcomb-tests.ts index aeecdcb31..3a27ffc7f 100644 --- a/tcomb/tcomb-tests.ts +++ b/tcomb/tcomb-tests.ts @@ -1,288 +1,1792 @@ // ReSharper disable InconsistentNaming // ReSharper disable WrongExpressionStatement +/// +/// +/// -import t = require("tcomb"); +// tests adapted from/for tcomb's test folder -var Str = t.Str; -var Num = t.Num; +'use strict'; +import assert = require('assert'); +var t = require('../index'); + +var Any = t.Any; +var Nil = t.Nil; var Bool = t.Bool; +var Num = t.Num; +var Str = t.Str; var Arr = t.Arr; var Obj = t.Obj; var Func = t.Func; var Err = t.Err; var Re = t.Re; var Dat = t.Dat; -var Nil = t.Nil; -var Any = t.Any; -var Type = t.Type; - var struct = t.struct; +var enums = t.enums; +var union = t.union; var tuple = t.tuple; +var maybe = t.maybe; +var subtype = t.subtype; var list = t.list; var dict = t.dict; -var union = t.union; -var maybe = t.maybe; var func = t.func; -var subtype = t.subtype; +var getTypeName = t.getTypeName; +var mixin = t.mixin; +var format = t.format; -Str.is("a string"); // => true -Str.is(1); // => false +// +// setup +// -Num.is("a string"); // => true -Num.is(1); // => false +var ok = function (x:any) { assert.strictEqual(true, x); }; +var ko = function (x:any) { assert.strictEqual(false, x); }; +var eq = assert.deepEqual; +var throwsWithMessage = function (f:any, message:any) { + assert.throws(f, function (err:any) { + ok(err instanceof Error); + eq(err.message, message); + return true; + }); +}; +var doesNotThrow = assert.doesNotThrow; -Bool.is("a string"); // => true -Bool.is(1); // => false - -Arr.is("a string"); // => true -Arr.is(1); // => false - -Obj.is("a string"); // => true -Obj.is(1); // => false - -Func.is("a string"); // => true -Func.is(1); // => false - -Err.is("a string"); // => true -Err.is(1); // => false - -Re.is("a string"); // => true -Re.is(1); // => false - -Dat.is("a string"); // => true -Dat.is(1); // => false - -Nil.is("a string"); // => true -Nil.is(1); // => false - -Any.is("a string"); // => true -Any.is(1); // => false - -Type.is("a string"); // => true -Type.is(1); // => false - -var assert = t.assert; - -assert(t.Str.is("a string")); // => ok -assert(t.Str.is(1)); // => fail! - -var x = -2; -var min = 0; -// throws "-2 should be greater then 0" -assert(x > min, "%s should be greater then %s", x, min); - -Str("a string"); // => ok - -class Point1 { - x: number; - y: number; - constructor(x: number, y: number) { - this.x = Num(x); - this.y = Num(y); - } -} - -var Foo = t.irreducible("Foo", x => { - return t.Bool(x.hasOwnProperty("bar")); -}); - -Foo.is({ bar: "baz" }); // => true - -// defines a type representing positive numbers -var Positive = t.subtype(t.Num, n => { - return n >= 0; -}, "Positive"); - -Positive.is(1); // => true -Positive.is(-1); // => false - -var Country = t.enums({ - IT: "Italy", - US: "United States" -}, "Country"); - -Country.is("IT"); // => true -Country.is("FR"); // => false - -// values will mirror the keys -Country = t.enums.of("IT US", "Country"); - -// same as - -Country = t.enums(["IT", "US"], "Country"); - -// same as - -Country = t.enums({ - IT: "IT", - US: "US" -}, "Country"); - -var Point = t.struct({ +var noop = function () {}; +var Point = struct({ x: Num, y: Num -}, "Point"); - -// constructor usage, `p` is immutable, new is optional -var p2 = new Point({ x: 1, y: 2 }); - -Point.is(p2); // => true - -// now p is mutable -new Point({ x: 1, y: 2 }, true); - -Point.extend({ z: Num }, "Point3D"); - -// multiple inheritance -var A = struct({}); -var B = struct({}); -var MixinC = {}; -var MixinD = {}; -A.extend([B, MixinC, MixinD]); - -var Rectangle = struct({ - width: Num, - height: Num }); -Rectangle.prototype.getArea = function() { - return this.width * this.height; -}; +describe('update', function () { + + var update = t.update; + var Tuple = tuple([Str, Num]); + var List = list(Num); + var Dict = dict(Str, Num); + + it('should handle $set command', function () { + var instance = 1; + var actual = update(instance, {$set: 2}); + eq(actual, 2); + var instance2 = [1, 2, 3]; + actual = update(instance2, {1: {'$set': 4}}); + eq(instance2, [1, 2, 3]); + eq(actual, [1, 4, 3]); + }); + + it('$set and null value, fix #65', function () { + var NullStruct = struct({a: Num, b: maybe(Num)}); + var instance = new NullStruct({a: 1}); + var updated = update(instance, {b: {$set: 2}}); + eq(instance, {a: 1, b: null}); + eq(updated, {a: 1, b: 2}); + }); + + it('should handle $apply command', function () { + var $apply = function (n:any) { return n + 1; }; + var instance = 1; + var actual = update(instance, {$apply: $apply}); + eq(actual, 2); + var instance2 = [1, 2, 3]; + actual = update(instance2, {1: {'$apply': $apply}}); + eq(instance2, [1, 2, 3]); + eq(actual, [1, 3, 3]); + }); + + it('should handle $unshift command', function () { + var actual = update([1, 2, 3], {'$unshift': [4]}); + eq(actual, [4, 1, 2, 3]); + actual = update([1, 2, 3], {'$unshift': [4, 5]}); + eq(actual, [4, 5, 1, 2, 3]); + actual = update([1, 2, 3], {'$unshift': [[4, 5]]}); + eq(actual, [[4, 5], 1, 2, 3]); + }); + + it('should handle $push command', function () { + var actual = update([1, 2, 3], {'$push': [4]}); + eq(actual, [1, 2, 3, 4]); + actual = update([1, 2, 3], {'$push': [4, 5]}); + eq(actual, [1, 2, 3, 4, 5]); + actual = update([1, 2, 3], {'$push': [[4, 5]]}); + eq(actual, [1, 2, 3, [4, 5]]); + }); + + it('should handle $splice command', function () { + var instance = [1, 2, {a: [12, 17, 15]}]; + var actual = update(instance, {2: {a: {$splice: [[1, 1, 13, 14]]}}}); + eq(instance, [1, 2, {a: [12, 17, 15]}]); + eq(actual, [1, 2, {a: [12, 13, 14, 15]}]); + }); + + it('should handle $remove command', function () { + var instance = {a: 1, b: 2}; + var actual = update(instance, {'$remove': ['a']}); + eq(instance, {a: 1, b: 2}); + eq(actual, {b: 2}); + }); + + it('should handle $swap command', function () { + var instance = [1, 2, 3, 4]; + var actual = update(instance, {'$swap': {from: 1, to: 2}}); + eq(instance, [1, 2, 3, 4]); + eq(actual, [1, 3, 2, 4]); + }); + + describe('structs', function () { + + var instance = new Point({x: 0, y: 1}); + + it('should handle $set command', function () { + var updated = update(instance, {x: {$set: 1}}); + eq(instance, {x: 0, y: 1}); + eq(updated, {x: 1, y: 1}); + }); + + it('should handle $apply command', function () { + var updated = update(instance, {x: {$apply: function (x:any) { + return x + 2; + }}}); + eq(instance, {x: 0, y: 1}); + eq(updated, {x: 2, y: 1}); + }); + + it('should handle $merge command', function () { + var updated = update(instance, {'$merge': {x: 2, y: 2}}); + eq(instance, {x: 0, y: 1}); + eq(updated, {x: 2, y: 2}); + var Nested = struct({ + a: Num, + b: struct({ + c: Num, + d: Num, + e: Num + }) + }); + instance = new Nested({a: 1, b: {c: 2, d: 3, e: 4}}); + updated = update(instance, {b: {'$merge': {c: 5, e: 6}}}); + eq(instance, {a: 1, b: {c: 2, d: 3, e: 4}}); + eq(updated, {a: 1, b: {c: 5, d: 3, e: 6}}); + }); + + }); + + describe('tuples', function () { + + var instance = Tuple(['a', 1]); + + it('should handle $set command', function () { + var updated = update(instance, {0: {$set: 'b'}}); + eq(updated, ['b', 1]); + }); + + }); + + describe('lists', function () { + + var instance = List([1, 2, 3, 4]); + + it('should handle $set command', function () { + var updated = update(instance, {2: {$set: 5}}); + eq(updated, [1, 2, 5, 4]); + }); + + it('should handle $splice command', function () { + var updated = update(instance, {$splice: [[1, 2, 5, 6]]}); + eq(updated, [1, 5, 6, 4]); + }); + + it('should handle $concat command', function () { + var updated = update(instance, {$push: [5]}); + eq(updated, [1, 2, 3, 4, 5]); + updated = update(instance, {$push: [5, 6]}); + eq(updated, [1, 2, 3, 4, 5, 6]); + }); + + it('should handle $prepend command', function () { + var updated = update(instance, {$unshift: [5]}); + eq(updated, [5, 1, 2, 3, 4]); + updated = update(instance, {$unshift: [5, 6]}); + eq(updated, [5, 6, 1, 2, 3, 4]); + }); + + it('should handle $swap command', function () { + var updated = update(instance, {$swap: {from: 1, to: 2}}); + eq(updated, [1, 3, 2, 4]); + }); + + }); + + describe('dicts', function () { + + var instance = Dict({a: 1, b: 2}); + + it('should handle $set command', function () { + var updated = update(instance, {a: {$set: 2}}); + eq(updated, {a: 2, b: 2}); + }); + + it('should handle $remove command', function () { + var updated = update(instance, {$remove: ['a']}); + eq(updated, {b: 2}); + }); + + }); + + describe('memory saving', function () { + + it('should reuse members that are not updated', function () { + var Struct = struct({ + a: Num, + b: Str, + c: tuple([Num, Num]), + }); + var List = list(Struct); + var instance = List([{ + a: 1, + b: 'one', + c: [1000, 1000000] + },{ + a: 2, + b: 'two', + c: [2000, 2000000] + }]); + + var updated = update(instance, { + 1: { + a: {$set: 119} + } + }); + + assert.strictEqual(( updated)[0], ( instance)[0]); + assert.notStrictEqual(( updated)[1], ( instance)[1]); + assert.strictEqual(( updated)[1].c, ( instance)[1].c); + }); + }); + + describe('all together now', function () { + + it('should handle mixed commands', function () { + var Struct = struct({ + a: Num, + b: Tuple, + c: List, + d: Dict + }); + var instance = new Struct({ + a: 1, + b: ['a', 1], + c: [1, 2, 3, 4], + d: {a: 1, b: 2} + }); + var updated = update(instance, { + a: {$set: 1}, + b: {0: {$set: 'b'}}, + c: {2: {$set: 5}}, + d: {$remove: ['a']} + }); + eq(updated, { + a: 1, + b: ['b', 1], + c: [1, 2, 5, 4], + d: {b: 2} + }); + }); + + it('should handle nested structures', function () { + var Struct = struct({ + a: struct({ + b: tuple([ + Str, + list(Num) + ]) + }) + }); + var instance = new Struct({ + a: { + b: ['a', [1, 2, 3]] + } + }); + var updated = update(instance, { + a: {b: {1: {2: {$set: 4}}}} + }); + eq(updated, { + a: { + b: ['a', [1, 2, 4]] + } + }); + }); + + }); -var Cube = Rectangle.extend({ - thickness: Num }); -// typeof Cube.prototype.getArea === 'function' -Cube.prototype.getVolume = function() { - return this.getArea() * this.thickness; -}; +// +// assert +// -var Area = tuple([Num, Num]); +describe('assert', function () { -// constructor usage, `area` is immutable -Area([1, 2]); + var assert = t.assert; -var Path = list(Point); + it('should nor throw when guard is true', function () { + assert(true); + }); -// costructor usage, `path` is immutable -Path([ - { x: 0, y: 0 }, // tcomb hydrates automatically using the `Point` constructor - { x: 1, y: 1 } -]); + it('should throw a default message', function () { + throwsWithMessage(function () { + assert(1 === 2); + }, 'assert failed'); + }); -var Tel = dict(Str, Num); + it('should throw the specified message', function () { + throwsWithMessage(function () { + assert(1 === 2, 'my message'); + }, 'my message'); + }); -// costructor usage, `tel` is immutable -Tel({ jack: 4098, sape: 4139 }); + it('should format the specified message', function () { + throwsWithMessage(function () { + assert(1 === 2, '%s !== %s', 1, 2); + }, '1 !== 2'); + }); -var ReactKey = union([Str, Num]); + it('should handle custom fail behaviour', function () { + var fail = t.fail; + t.fail = function (message) { + try { + throw new Error(message); + } catch (e) { + eq(e.message, 'report error'); + } + }; + doesNotThrow(function () { + assert(1 === 2, 'report error'); + }); + t.fail = fail; + }); -ReactKey.is("a"); // => true -ReactKey.is(1); // => true -ReactKey.is(true); // => false +}); -ReactKey.dispatch = x => { - if (Str.is(x)) return Str; - if (Num.is(x)) return Num; - return Any; -}; +// +// utils +// -// now you can do this without a fail -ReactKey("a"); +describe('format(str, [...])', function () { -// the value of a radio input where null = no selection -var Radio = maybe(Str); + it('should format strings', function () { + eq(format('%s', 'a'), 'a'); + eq(format('%s', 2), '2'); + eq(format('%s === %s', 1, 1), '1 === 1'); + }); -Radio.is("a"); // => true -Radio.is(null); // => true -Radio.is(1); // => false + it('should format JSON', function () { + eq(format('%j', {a: 1}), '{"a":1}'); + }); -// add takes two `Num`s and returns a `Num` -var add = func([Num, Num], Num) - .of((x: number, y: number) => { return x + y; }); + it('should handle undefined formatters', function () { + eq(format('%o', 'a'), '%o a'); + }); -add("Hello", 2); // Raises error: Invalid `Hello` supplied to `Num` -add("Hello"); // Raises error: Invalid `Hello` supplied to `Num` + it('should handle escaping %', function () { + eq(format('%%s'), '%s'); + }); -add(1, 2); // Returns: 3 -add(1)(2); // Returns: 3 + it('should not consume an argument with a single %', function () { + eq(format('%s%', '100'), '100%'); + }); -// An `A` takes a `Str` and returns an `Num` -func(Str, Num); + it('should handle less arguments than placeholders', function () { + eq(format('%s %s', 'a'), 'a %s'); + }); -// A `B` takes a `Func` (which takes a `Str` and returns a `Num`) and returns a `Str`. -func(func(Str, Num), Str); + it('should handle more arguments than placeholders', function () { + eq(format('%s', 'a', 'b', 'c'), 'a b c'); + }); -// An `ExcitedStr` is a `Str` containing an exclamation mark -var ExcitedStr = subtype(Str, s => { return s.indexOf("!") !== -1; }, "ExcitedStr"); + it('should be extensible', function () { + (format).formatters.l = function (x:any) { return x.length; }; + eq(format('%l', ['a', 'b', 'c']), '3'); + }); -// An `Exciter` takes a `Str` and returns an `ExcitedStr` -var Exciter = func(Str, ExcitedStr); +}); -// A `C` takes an `A`, a `B` and a `Str` and returns a `Num` -func([A, B, Str], Num); +describe('mixin(x, y, [overwrite])', function () { -func(A, B).of(() => {}); + it('should mix two objects', function () { + var o1 = {a: 1}; + var o2 = {b: 2}; + var o3 = mixin(o1, o2); + ok(o3 === o1); + eq(o3.a, 1); + eq(o3.b, 2); + }); -var simpleQuestionator = Exciter.of((s: string) => { return s + "?"; }); -var simpleExciter = Exciter.of((s: string) => { return s + "!"; }); + it('should throw if a property already exists', function () { + throwsWithMessage(function () { + var o1 = {a: 1}; + var o2 = {a: 2, b: 2}; + mixin(o1, o2); + }, 'Cannot overwrite property a'); + }); -// Raises error: -// Invalid `Hello?` supplied to `ExcitedStr`, insert a valid value for the subtype -simpleQuestionator("Hello"); + it('should not throw if a property already exists but overwrite = true', function () { + var o1 = {a: 1}; + var o2 = {a: 2, b: 2}; + var o3 = mixin(o1, o2, true); + eq(o3.a, 2); + eq(o3.b, 2); + }); -// Raises error: Invalid `1` supplied to `Str` -simpleExciter(1); + it('should not mix prototype properties', function () { + function F() {} + F.prototype.method = noop; + var source = new (F)(); + var target = {}; + mixin(target, source); + eq((target).method, undefined); + }); -// Returns: "Hello!" -simpleExciter("Hello"); +}); -// We can reasonably suggest that add has the following type signature -// add : Num -> Num -> Num -add = func([Num, Num], Num) - .of((x: number, y: number) => { return x + y }); +describe('getFunctionName(f, [defaultName])', function () { -add("Hello"); // As this raises: "Error: Invalid `Hello` supplied to `Num`" + var getFunctionName = t.getFunctionName; -var add2 = add(2); -add2(1); // And this returns: 3 + it('should return the name of a named function', function () { + eq(getFunctionName(function myfunc(){}), 'myfunc'); + }); -func(A, B).is(x); + it('should return the value of `displayName` if specified', function () { + var f = function myfunc(){}; + (f).displayName = 'mydisplayname'; + eq(getFunctionName(f), 'mydisplayname'); + }); -Exciter.is(simpleExciter); // Returns: true -Exciter.is(simpleQuestionator); // Returns: true + it('should fallback on function arity if nothing is specified', function () { + eq(getFunctionName(function (a:any, b:any, c:any) { return a + b + c; }), ''); + }); -var id = (x: number) => { return x; }; +}); -func([Num, Num], Num).is(func([Num, Num], Num).of(id)); // Returns: true -func([Num, Num], Num).is(func(Num, Num).of(id)); // Returns: false +describe('getTypeName(type)', function () { -var p4 = new Point({x: 1, y: 2}); + var UnnamedStruct = struct({}); + var NamedStruct = struct({}, 'NamedStruct'); + var UnnamedUnion = union([Str, Num]); + var NamedUnion = union([Str, Num], 'NamedUnion'); + var UnnamedMaybe = maybe(Str); + var NamedMaybe = maybe(Str, 'NamedMaybe'); + var UnnamedEnums = enums({a: 'A', b: 'B'}); + var NamedEnums = enums({}, 'NamedEnums'); + var UnnamedTuple = tuple([Str, Num]); + var NamedTuple = tuple([Str, Num], 'NamedTuple'); + var UnnamedSubtype = subtype(Str, function notEmpty(x) { return x !== ''; }); + var NamedSubtype = subtype(Str, function (x) { return x !== ''; }, 'NamedSubtype'); + var UnnamedList = list(Str); + var NamedList = list(Str, 'NamedList'); + var UnnamedDict = dict(Str, Str); + var NamedDict = dict(Str, Str, 'NamedDict'); + var UnnamedFunc = func(Str, Str); + var NamedFunc = func(Str, Str, 'NamedFunc'); -p4 = Point.update(p4, { x: { "$set": 3 } }); // => {x: 3, y: 2} + it('should return the name of a named type', function () { + eq(getTypeName(NamedStruct), 'NamedStruct'); + eq(getTypeName(NamedUnion), 'NamedUnion'); + eq(getTypeName(NamedMaybe), 'NamedMaybe'); + eq(getTypeName(NamedEnums), 'NamedEnums'); + eq(getTypeName(NamedTuple), 'NamedTuple'); + eq(getTypeName(NamedSubtype), 'NamedSubtype'); + eq(getTypeName(NamedList), 'NamedList'); + eq(getTypeName(NamedDict), 'NamedDict'); + eq(getTypeName(NamedFunc), 'NamedFunc'); + }); -var Type2 = dict(Str, Num); -var instance = Type2({ a: 1, b: 2 }); -Type2.update(instance, { $remove: ["a"] }); // => {b: 2} + it('should return a meaningful name of a unnamed type', function () { + eq(getTypeName(UnnamedStruct), '{}'); + eq(getTypeName(UnnamedUnion), 'Str | Num'); + eq(getTypeName(UnnamedMaybe), '?Str'); + eq(getTypeName(UnnamedEnums), '"a" | "b"'); + eq(getTypeName(UnnamedTuple), '[Str, Num]'); + eq(getTypeName(UnnamedSubtype), '{Str | notEmpty}'); + eq(getTypeName(UnnamedList), 'Array'); + eq(getTypeName(UnnamedDict), '{[key:Str]: Str}'); + eq(getTypeName(UnnamedFunc), '(Str) => Str'); + }); -var Type3 = list(Num); -var instance2 = Type3([1, 2, 3, 4]); -Type3.update(instance2, { "$swap": { from: 1, to: 2 } }); // => [1, 3, 2, 4] +}); -t.options.onFail = message => { - return message; -}; +// +// Any +// -t.format("Invalid argument `name` = `%s` supplied to `%s`", 1, "MyType"); +describe('Any', function () { -t.getKind(Str); // => 'irreducible' -t.getKind(list(Str)); // => 'list' + var T = Any; -t.getFunctionName(t.getKind); // => 'getKind' -t.getFunctionName(() => { }); // => '' + describe('constructor', function () { -t.getTypeName(Str); + it('should behave like identity', function () { + eq(Any('a'), 'a'); + }); -t.mixin({ a: 1 }, { b: 2 }); // => {a: 1, b: 2} -t.mixin({ a: 1 }, { a: 2 }); // => fail! + it('should throw if used with new', function () { + throwsWithMessage(function () { + /* jshint ignore:start */ + var x = new (T)(); + /* jshint ignore:end */ + }, 'Operator `new` is forbidden for type `Any`'); + }); + + }); + + describe('#is(x)', function () { + + it('should always return true', function () { + ok(T.is(null)); + ok(T.is(undefined)); + ok(T.is(0)); + ok(T.is(true)); + ok(T.is('')); + ok(T.is([])); + ok(T.is({})); + ok(T.is(noop)); + ok(T.is(/a/)); + ok(T.is(new RegExp('a'))); + ok(T.is(new Error())); + }); + + }); + +}); + +// +// irreducible types +// + +describe('irreducible types constructors', function () { + + [ + {T: Nil, x: null}, + {T: Str, x: 'a'}, + {T: Num, x: 1}, + {T: Bool, x: true}, + {T: Arr, x: []}, + {T: Obj, x: {}}, + {T: Func, x: noop}, + {T: Err, x: new Error()}, + {T: Re, x: /a/}, + {T: Dat, x: new Date()} + ].forEach(function (o) { + + var T = o.T; + var x = o.x; + + it('should accept only valid values', function () { + eq(T(x), x); + }); + + it('should throw if used with new', function () { + throwsWithMessage(function () { + /* jshint ignore:start */ + var x = new (T) (); + /* jshint ignore:end */ + }, 'Operator `new` is forbidden for type `' + getTypeName(T) + '`'); + }); + + }); + +}); + +describe('Nil', function () { + + describe('#is(x)', function () { + + it('should return true when x is null or undefined', function () { + ok(Nil.is(null)); + ok(Nil.is(undefined)); + }); + + it('should return false when x is neither null nor undefined', function () { + ko(Nil.is(0)); + ko(Nil.is(true)); + ko(Nil.is('')); + ko(Nil.is([])); + ko(Nil.is({})); + ko(Nil.is(noop)); + ko(Nil.is(new Error())); + ko(Nil.is(new Date())); + ko(Nil.is(/a/)); + ko(Nil.is(new RegExp('a'))); + }); + + }); + +}); + +describe('Bool', function () { + + describe('#is(x)', function () { + + it('should return true when x is true or false', function () { + ok(Bool.is(true)); + ok(Bool.is(false)); + }); + + it('should return false when x is neither true nor false', function () { + ko(Bool.is(null)); + ko(Bool.is(undefined)); + ko(Bool.is(0)); + ko(Bool.is('')); + ko(Bool.is([])); + ko(Bool.is({})); + ko(Bool.is(noop)); + ko(Bool.is(/a/)); + ko(Bool.is(new RegExp('a'))); + ko(Bool.is(new Error())); + ko(Bool.is(new Date())); + }); + + }); + +}); + +describe('Num', function () { + + describe('#is(x)', function () { + + it('should return true when x is a number', function () { + ok(Num.is(0)); + ok(Num.is(1)); + /* jshint ignore:start */ + ko(Num.is(new Number(1))); + /* jshint ignore:end */ + }); + + it('should return false when x is not a number', function () { + ko(Num.is(NaN)); + ko(Num.is(Infinity)); + ko(Num.is(-Infinity)); + ko(Num.is(null)); + ko(Num.is(undefined)); + ko(Num.is(true)); + ko(Num.is('')); + ko(Num.is([])); + ko(Num.is({})); + ko(Num.is(noop)); + ko(Num.is(/a/)); + ko(Num.is(new RegExp('a'))); + ko(Num.is(new Error())); + ko(Num.is(new Date())); + }); + + }); + +}); + +describe('Str', function () { + + describe('#is(x)', function () { + + it('should return true when x is a string', function () { + ok(Str.is('')); + ok(Str.is('a')); + /* jshint ignore:start */ + ko(Str.is(new String('a'))); + /* jshint ignore:end */ + }); + + it('should return false when x is not a string', function () { + ko(Str.is(NaN)); + ko(Str.is(Infinity)); + ko(Str.is(-Infinity)); + ko(Str.is(null)); + ko(Str.is(undefined)); + ko(Str.is(true)); + ko(Str.is(1)); + ko(Str.is([])); + ko(Str.is({})); + ko(Str.is(noop)); + ko(Str.is(/a/)); + ko(Str.is(new RegExp('a'))); + ko(Str.is(new Error())); + ko(Str.is(new Date())); + }); + + }); + +}); + +describe('Arr', function () { + + describe('#is(x)', function () { + + it('should return true when x is an array', function () { + ok(Arr.is([])); + }); + + it('should return false when x is not an array', function () { + ko(Arr.is(NaN)); + ko(Arr.is(Infinity)); + ko(Arr.is(-Infinity)); + ko(Arr.is(null)); + ko(Arr.is(undefined)); + ko(Arr.is(true)); + ko(Arr.is(1)); + ko(Arr.is('a')); + ko(Arr.is({})); + ko(Arr.is(noop)); + ko(Arr.is(/a/)); + ko(Arr.is(new RegExp('a'))); + ko(Arr.is(new Error())); + ko(Arr.is(new Date())); + }); + + }); + +}); + +describe('Obj', function () { + + describe('#is(x)', function () { + + it('should return true when x is an object', function () { + function A() {} + ok(Obj.is({})); + ok(Obj.is(new (A)())); + }); + + it('should return false when x is not an object', function () { + ko(Obj.is(null)); + ko(Obj.is(undefined)); + ko(Obj.is(0)); + ko(Obj.is('')); + ko(Obj.is([])); + ko(Obj.is(noop)); + }); + + }); + +}); + +describe('Func', function () { + + describe('#is(x)', function () { + + it('should return true when x is a function', function () { + ok(Func.is(noop)); + /* jshint ignore:start */ + ok(Func.is(new Function())); + /* jshint ignore:end */ + }); + + it('should return false when x is not a function', function () { + ko(Func.is(null)); + ko(Func.is(undefined)); + ko(Func.is(0)); + ko(Func.is('')); + ko(Func.is([])); + /* jshint ignore:start */ + ko(Func.is(new String('1'))); + ko(Func.is(new Number(1))); + ko(Func.is(new Boolean())); + /* jshint ignore:end */ + ko(Func.is(/a/)); + ko(Func.is(new RegExp('a'))); + ko(Func.is(new Error())); + ko(Func.is(new Date())); + }); + + }); + +}); + +describe('Err', function () { + + describe('#is(x)', function () { + + it('should return true when x is an error', function () { + ok(Err.is(new Error())); + }); + + it('should return false when x is not an error', function () { + ko(Err.is(null)); + ko(Err.is(undefined)); + ko(Err.is(0)); + ko(Err.is('')); + ko(Err.is([])); + /* jshint ignore:start */ + ko(Err.is(new String('1'))); + ko(Err.is(new Number(1))); + ko(Err.is(new Boolean())); + /* jshint ignore:end */ + ko(Err.is(/a/)); + ko(Err.is(new RegExp('a'))); + ko(Err.is(new Date())); + }); + + }); + +}); + +describe('Re', function () { + + describe('#is(x)', function () { + + it('should return true when x is a regexp', function () { + ok(Re.is(/a/)); + ok(Re.is(new RegExp('a'))); + }); + + it('should return false when x is not a regexp', function () { + ko(Re.is(null)); + ko(Re.is(undefined)); + ko(Re.is(0)); + ko(Re.is('')); + ko(Re.is([])); + /* jshint ignore:start */ + ko(Re.is(new String('1'))); + ko(Re.is(new Number(1))); + ko(Re.is(new Boolean())); + /* jshint ignore:end */ + ko(Re.is(new Error())); + ko(Re.is(new Date())); + }); + + }); + +}); + +describe('Dat', function () { + + describe('#is(x)', function () { + + it('should return true when x is a Dat', function () { + ok(Dat.is(new Date())); + }); + + it('should return false when x is not a Dat', function () { + ko(Dat.is(null)); + ko(Dat.is(undefined)); + ko(Dat.is(0)); + ko(Dat.is('')); + ko(Dat.is([])); + /* jshint ignore:start */ + ko(Dat.is(new String('1'))); + ko(Dat.is(new Number(1))); + ko(Dat.is(new Boolean())); + /* jshint ignore:end */ + ko(Dat.is(new Error())); + ko(Dat.is(/a/)); + ko(Dat.is(new RegExp('a'))); + }); + + }); + +}); + +// +// struct +// + +describe('struct', function () { + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (struct)(); + }, 'Invalid argument `props` = `undefined` supplied to `struct` combinator'); + + throwsWithMessage(function () { + struct({a: null}); + }, 'Invalid argument `props` = `[object Object]` supplied to `struct` combinator'); + + throwsWithMessage(function () { + (struct)({}, 1); + }, 'Invalid argument `name` = `1` supplied to `struct` combinator'); + + }); + + }); + describe('constructor', function () { + + it('should be idempotent', function () { + var T = Point; + var p1 = T({x: 0, y: 0}); + var p2 = T(p1); + eq(Object.isFrozen(p1), true); + eq(Object.isFrozen(p2), true); + eq(p2 === p1, true); + }); + + it('should accept only valid values', function () { + throwsWithMessage(function () { + Point(1); + }, 'Invalid argument `value` = `1` supplied to struct type `{x: Num, y: Num}`'); + }); + + }); + + describe('#is(x)', function () { + + it('should return true when x is an instance of the struct', function () { + var p = new Point({ x: 1, y: 2 }); + ok(Point.is(p)); + }); + + }); + + describe('#update()', function () { + + var Type = struct({name: Str}); + var instance = new Type({name: 'Giulio'}); + + it('should return a new instance', function () { + var newInstance = Type.update(instance, {name: {$set: 'Canti'}}); + ok(Type.is(newInstance)); + eq( ( instance).name, 'Giulio'); + eq(( newInstance).name, 'Canti'); + }); + + }); + + describe('#extend(props, [name])', function () { + + it('should extend an existing struct', function () { + var Point = struct({ + x: Num, + y: Num + }, 'Point'); + var Point3D = Point.extend({z: Num}, 'Point3D'); + eq(getTypeName(Point3D), 'Point3D'); + eq((Point3D).meta.props.x, Num); + eq((Point3D).meta.props.y, Num); + eq((Point3D).meta.props.z, Num); + }); + + it('should handle an array as argument', function () { + var Type = struct({a: Str}, 'Type'); + var Mixin = [{b: Num, c: Bool}]; + var NewType = Type.extend(Mixin, 'NewType'); + eq(getTypeName(NewType), 'NewType'); + eq((NewType).meta.props.a, Str); + eq((NewType).meta.props.b, Num); + eq((NewType).meta.props.c, Bool); + }); + + it('should handle a struct (or list of structs) as argument', function () { + var A = struct({a: Str}, 'A'); + var B = struct({b: Str}, 'B'); + var C = struct({c: Str}, 'C'); + var MixinD = {d: Str}; + var E = A.extend([B, C, MixinD]); + eq(E.meta.props, { + a: Str, + b: Str, + c: Str, + d: Str + }); + }); + + it('should support prototypal inheritance', function () { + var Rectangle = struct({ + w: Num, + h: Num + }, 'Rectangle'); + Rectangle.prototype.area = function () { + return this.w * this.h; + }; + var Cube = Rectangle.extend({ + l: Num + }); + Cube.prototype.volume = function () { + return this.area() * this.l; + }; + + assert('function' === typeof Rectangle.prototype.area); + assert('function' === typeof Cube.prototype.area); + assert(undefined === Rectangle.prototype.volume); + assert('function' === typeof Cube.prototype.volume); + assert(Cube.prototype.constructor === Cube); + + var c = new Cube({w:2, h:2, l:2}); + eq((c).volume(), 8); + }); + + }); + +}); + +// +// enums +// + +describe('enums', function () { + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (enums)(); + }, 'Invalid argument `map` = `undefined` supplied to `enums` combinator'); + + throwsWithMessage(function () { + (enums)({}, 1); + }, 'Invalid argument `name` = `1` supplied to `enums` combinator'); + + }); + + }); + + describe('constructor', function () { + + var T = enums({a: 0}, 'T'); + + it('should throw if used with new', function () { + throwsWithMessage(function () { + /* jshint ignore:start */ + var x = new (T)('a'); + /* jshint ignore:end */ + }, 'Operator `new` is forbidden for type `T`'); + }); + + it('should accept only valid values', function () { + eq((T)('a'), 'a'); + throwsWithMessage(function () { + (T)('b'); + }, 'Invalid argument `value` = `b` supplied to enums type `T`, expected one of ["a"]'); + }); + + }); + + describe('#is(x)', function () { + + var Direction = enums({ + North: 0, + East: 1, + South: 2, + West: 3, + 1: 'North-East', + 2.5: 'South-East' + }); + + it('should return true when x is an instance of the enum', function () { + ok(Direction.is('North')); + ok(Direction.is(1)); + ok(Direction.is('1')); + ok(Direction.is(2.5)); + }); + + it('should return false when x is not an instance of the enum', function () { + ko(Direction.is('North-East')); + ko(Direction.is(2)); + }); + + }); + + describe('#of(keys)', function () { + + it('should return an enum', function () { + var Size = (enums).of(['large', 'small', 1, 10.9]); ///!!! + ok(Size.meta.map.large === 'large'); + ok(Size.meta.map.small === 'small'); + ok(Size.meta.map['1'] === 1); + ok(Size.meta.map[10.9] === 10.9); + }); + + it('should handle a string', function () { + var Size = (enums).of('large small 10'); + ok(Size.meta.map.large === 'large'); + ok(Size.meta.map.small === 'small'); + ok(Size.meta.map['10'] === '10'); + ok(Size.meta.map[10] === '10'); + }); + + }); + +}); + +// +// union +// + +describe('union', function () { + + var Circle = struct({ + center: Point, + radius: Num + }, 'Circle'); + + var Rectangle = struct({ + a: Point, + b: Point + }); + + var Shape = union([Circle, Rectangle], 'Shape'); + + Shape.dispatch = function (values) { + assert(Obj.is(values)); + return values.hasOwnProperty('center') ? + Circle : + Rectangle; + }; + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (union)(); + }, 'Invalid argument `types` = `undefined` supplied to `union` combinator'); + + throwsWithMessage(function () { + union([]); + }, 'Invalid argument `types` = `` supplied to `union` combinator, provide at least two types'); + + throwsWithMessage(function () { + union([Circle]); + }, 'Invalid argument `types` = `Circle` supplied to `union` combinator, provide at least two types'); + + throwsWithMessage(function () { + (union)([Circle, Point], 1); + }, 'Invalid argument `name` = `1` supplied to `union` combinator'); + + }); + + }); + + describe('constructor', function () { + + it('should throw when dispatch() is not implemented', function () { + throwsWithMessage(function () { + var T = union([Str, Num], 'T'); + T.dispatch = null; + T(1); + }, 'Unimplemented `dispatch()` function for union type `T`'); + }); + + it('should have a default dispatch() implementation', function () { + var T = union([Str, Num], 'T'); + eq(T(1), 1); + }); + + it('should throw when dispatch() does not return a type', function () { + throwsWithMessage(function () { + var T = union([Str, Num], 'T'); + T(true); + }, 'The `dispatch()` function of union type `T` returns no type constructor'); + }); + + it('should build instances when dispatch() is implemented', function () { + var circle = Shape({center: {x: 0, y: 0}, radius: 10}); + ok(Circle.is(circle)); + }); + + it('should throw if used with new and union types are not instantiables with new', function () { + throwsWithMessage(function () { + var T = union([Str, Num], 'T'); + T.dispatch = function () { return Str; }; + /* jshint ignore:start */ + var x = new T('a'); + /* jshint ignore:end */ + }, 'Operator `new` is forbidden for type `T`'); + }); + + it('should not throw if used with new and union types are instantiables with new', function () { + doesNotThrow(function () { + Shape({center: {x: 0, y: 0}, radius: 10}); + }); + }); + + it('should be idempotent', function () { + var p1 = Shape({center: {x: 0, y: 0}, radius: 10}); + var p2 = Shape(p1); + eq(Object.isFrozen(p1), true); + eq(Object.isFrozen(p2), true); + eq(p2 === p1, true); + }); + + }); + + describe('#is(x)', function () { + + it('should return true when x is an instance of the union', function () { + var p = new Circle({center: { x: 0, y: 0 }, radius: 10}); + ok(Shape.is(p)); + }); + + }); + +}); + +// +// maybe +// + +describe('maybe', function () { + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (maybe)(); + }, 'Invalid argument `type` = `undefined` supplied to `maybe` combinator'); + + throwsWithMessage(function () { + (maybe)(Point, 1); + }, 'Invalid argument `name` = `1` supplied to `maybe` combinator'); + + }); + + it('should be idempotent', function () { + var MaybeStr = maybe(Str); + ok(maybe(MaybeStr) === MaybeStr); + }); + + it('should be noop with Any', function () { + ok(maybe(Any) === Any); + }); + + it('should be noop with Nil', function () { + ok((maybe)(Nil) === Nil); + }); + + }); + + describe('constructor', function () { + + it('should throw if used with new', function () { + throwsWithMessage(function () { + /* jshint ignore:start */ + var T = maybe(Str, 'T'); + var x = new (T)(); + /* jshint ignore:end */ + }, 'Operator `new` is forbidden for type `T`'); + }); + + it('should coerce values', function () { + var T = maybe(Point); + eq(T(null), null); + eq(T(undefined), null); + ok(Point.is(T({x: 0, y: 0}))); + }); + + it('should be idempotent', function () { + var T = maybe(Point); + var p1 = T({x: 0, y: 0}); + var p2 = T(p1); + eq(Object.isFrozen(p1), true); + eq(Object.isFrozen(p2), true); + eq(p2 === p1, true); + }); + + }); + + describe('#is(x)', function () { + + it('should return true when x is an instance of the maybe', function () { + var Radio = maybe(Str); + ok(Radio.is('a')); + ok(Radio.is(null)); + ok(Radio.is(undefined)); + }); + + }); + +}); + +// +// tuple +// + +describe('tuple', function () { + + var Area = tuple([Num, Num], 'Area'); + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (tuple)(); + }, 'Invalid argument `types` = `undefined` supplied to `tuple` combinator'); + + throwsWithMessage(function () { + (tuple)([Point, Point], 1); + }, 'Invalid argument `name` = `1` supplied to `tuple` combinator'); + + }); + + }); + + describe('constructor', function () { + + var S = struct({}, 'S'); + var T = tuple([S, S], 'T'); + + it('should coerce values', function () { + var t = T([{}, {}]); + ok(S.is(( t)[0])); + ok(S.is(( t)[1])); + }); + + it('should accept only valid values', function () { + + throwsWithMessage(function () { + T(1); + }, 'Invalid argument `value` = `1` supplied to tuple type `T`, expected an `Arr` of length `2`'); + + throwsWithMessage(function () { + T([1, 1]); + }, 'Invalid argument `value` = `1` supplied to struct type `S`'); + + }); + + it('should be idempotent', function () { + var T = tuple([Str, Num]); + var p1 = T(['a', 1]); + var p2 = T(p1); + eq(Object.isFrozen(p1), true); + eq(Object.isFrozen(p2), true); + eq(p2 === p1, true); + }); + + }); + + describe('#is(x)', function () { + + it('should return true when x is an instance of the tuple', function () { + ok(Area.is([1, 2])); + }); + + it('should return false when x is not an instance of the tuple', function () { + ko(Area.is([1])); + ko(Area.is([1, 2, 3])); + ko(Area.is([1, 'a'])); + }); + + it('should not depend on `this`', function () { + ok([[1, 2]].every(Area.is)); + }); + + }); + + describe('#update()', function () { + + var Type = tuple([Str, Num]); + var instance = Type(['a', 1]); + + it('should return a new instance', function () { + var newInstance = Type.update(instance, {0: {$set: 'b'}}); + assert(Type.is(newInstance)); + assert(( instance)[0] === 'a'); + assert(( newInstance)[0] === 'b'); + }); + + }); + +}); + +// +// list +// + +describe('list', function () { + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (list)(); + }, 'Invalid argument `type` = `undefined` supplied to `list` combinator'); + + throwsWithMessage(function () { + (list)(Point, 1); + }, 'Invalid argument `name` = `1` supplied to `list` combinator'); + + }); + + }); + + describe('constructor', function () { + + var S = struct({}, 'S'); + var T = list(S, 'T'); + + it('should coerce values', function () { + var t = T([{}]); + ok(S.is(( t)[0])); + }); + + it('should accept only valid values', function () { + + throwsWithMessage(function () { + T(1); + }, 'Invalid argument `value` = `1` supplied to list type `T`'); + + throwsWithMessage(function () { + T([1]); + }, 'Invalid argument `value` = `1` supplied to struct type `S`'); + + }); + + it('should be idempotent', function () { + var T = list(Num); + var p1 = T([1, 2]); + var p2 = T(p1); + eq(Object.isFrozen(p1), true); + eq(Object.isFrozen(p2), true); + eq(p2 === p1, true); + }); + + }); + + describe('#is(x)', function () { + + var Path = list(Point); + var p1 = new Point({x: 0, y: 0}); + var p2 = new Point({x: 1, y: 1}); + + it('should return true when x is a list', function () { + ok(Path.is([p1, p2])); + }); + + it('should not depend on `this`', function () { + ok([[p1, p2]].every(Path.is)); + }); + + }); + + describe('#update()', function () { + + var Type = list(Str); + var instance = Type(['a', 'b']); + + it('should return a new instance', function () { + var newInstance = Type.update(instance, {'$push': ['c']}); + assert(Type.is(newInstance)); + assert((instance).length === 2); + assert((newInstance).length === 3); + }); + + }); + +}); + +// +// subtype +// + +describe('subtype', function () { + + var True = function () { return true; }; + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (subtype)(); + }, 'Invalid argument `type` = `undefined` supplied to `subtype` combinator'); + + throwsWithMessage(function () { + subtype(Point, null); + }, 'Invalid argument `predicate` = `null` supplied to `subtype` combinator'); + + throwsWithMessage(function () { + (subtype)(Point, True, 1); + }, 'Invalid argument `name` = `1` supplied to `subtype` combinator'); + + }); + + }); + + describe('constructor', function () { + + it('should throw if used with new and a type that is not instantiable with new', function () { + throwsWithMessage(function () { + /* jshint ignore:start */ + var T = subtype(Str, function () { return true; }, 'T'); + var x = new( T)(); + /* jshint ignore:end */ + }, 'Operator `new` is forbidden for type `T`'); + }); + + it('should coerce values', function () { + var T = subtype(Point, function () { return true; }); + var p = T({x: 0, y: 0}); + ok(Point.is(p)); + }); + + it('should accept only valid values', function () { + var predicate = function (p:any) { return p.x > 0; }; + var T = subtype(Point, predicate, 'T'); + throwsWithMessage(function () { + T({x: 0, y: 0}); + }, 'Invalid argument `value` = `[object Object]` supplied to subtype type `T`'); + }); + + }); + + describe('#is(x)', function () { + + var Positive = subtype(Num, function (n) { + return n >= 0; + }); + + it('should return true when x is a subtype', function () { + ok(Positive.is(1)); + }); + + it('should return false when x is not a subtype', function () { + ko(Positive.is(-1)); + }); + + }); + + describe('#update()', function () { + + var Type = subtype(Str, function (s) { return s.length > 2; }); + var instance = Type('abc'); + + it('should return a new instance', function () { + var newInstance = Type.update(instance, {'$set': 'bca'}); + assert(Type.is(newInstance)); + eq(newInstance, 'bca'); + }); + + }); + +}); + +// +// dict +// + +describe('dict', function () { + + describe('combinator', function () { + + it('should throw if used with wrong arguments', function () { + + throwsWithMessage(function () { + (dict)(); + }, 'Invalid argument `domain` = `undefined` supplied to `dict` combinator'); + + throwsWithMessage(function () { + (dict)(Str); + }, 'Invalid argument `codomain` = `undefined` supplied to `dict` combinator'); + + throwsWithMessage(function () { + (dict)(Str, Point, 1); + }, 'Invalid argument `name` = `1` supplied to `dict` combinator'); + + }); + + }); + + describe('constructor', function () { + + var S = struct({}, 'S'); + var Domain = subtype(Str, function (x) { + return x !== 'forbidden'; + }, 'Domain'); + var T = dict(Domain, S, 'T'); + + it('should coerce values', function () { + var t = T({a: {}}); + ok(S.is((t).a)); + }); + + it('should accept only valid values', function () { + + throwsWithMessage(function () { + T(1); + }, 'Invalid argument `value` = `1` supplied to dict type `T`'); + + throwsWithMessage(function () { + T({a: 1}); + }, 'Invalid argument `value` = `1` supplied to struct type `S`'); + + throwsWithMessage(function () { + T({forbidden: {}}); + }, 'Invalid argument `value` = `forbidden` supplied to subtype type `Domain`'); + + }); + + it('should be idempotent', function () { + var T = dict(Str, Str); + var p1 = T({a: 'a', b: 'b'}); + var p2 = T(p1); + eq(Object.isFrozen(p1), true); + eq(Object.isFrozen(p2), true); + eq(p2 === p1, true); + }); + + }); + + describe('#is(x)', function () { + + var T = dict(Str, Point); + var p1 = new Point({x: 0, y: 0}); + var p2 = new Point({x: 1, y: 1}); + + it('should return true when x is a list', function () { + ok(T.is({a: p1, b: p2})); + }); + + it('should not depend on `this`', function () { + ok([{a: p1, b: p2}].every(T.is)); + }); + + }); + + describe('#update()', function () { + + var Type = dict(Str, Str); + var instance = Type({p1: 'a', p2: 'b'}); + + it('should return a new instance', function () { + var newInstance = Type.update(instance, {p2: {$set: 'c'}}); + ok(Type.is(newInstance)); + eq((instance).p2, 'b'); + eq((newInstance).p2, 'c'); + }); + + }); + +}); + +// +// func +// + +describe('func', function () { + + it('should handle a no types', function () { + var T = func([], Str); + eq(T.meta.domain.length, 0); + var getGreeting = T.of(function () { return 'Hi'; }); + eq(getGreeting(), 'Hi'); + }); + + it('should handle a single type', function () { + var T = func(Num, Num); + eq(T.meta.domain.length, 1); + ok(T.meta.domain[0] === Num); + }); + + it('should automatically instrument a function', function () { + var T = func(Num, Num); + var f = function () { return 'hi'; }; + ok(T.is(T(f))); + }); + + describe('of', function () { + + it('should check the arguments', function () { + + var T = func([Num, Num], Num); + var sum = T.of(function (a:any, b:any) { + return a + b; + }); + eq(sum(1, 2), 3); + + throwsWithMessage(function () { + sum(1, 2, 3); + }, 'Invalid argument `value` = `1,2,3` supplied to tuple type `[Num, Num]`, expected an `Arr` of length `2`'); + + throwsWithMessage(function () { + sum('a', 2); + }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); + + }); + + it('should check the return value', function () { + + var T = func([Num, Num], Num); + var sum = T.of(function () { + return 'a'; + }); + + throwsWithMessage(function () { + sum(1, 2); + }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); + + }); + + it('should preserve `this`', function () { + var o = {name: 'giulio'}; + (o).getTypeName = func([], Str).of(function () { + return this.name; + }); + eq((o).getTypeName(), 'giulio'); + }); + + it('should handle function types', function () { + var A = func([Str], Str); + var B = func([Str, A], Str); + + var f = A.of(function (s:any) { + return s + '!'; + }); + var g = B.of(function (str:any, strAction:any) { + return strAction(str); + }); + + eq(g('hello', f), 'hello!'); + }); + + it('should be idempotent', function () { + var f = function (s:any) { return s; }; + var g = func([Str], Str).of(f); + var h = func([Str], Str).of(g); + ok(h === g); + }); + + }); + + describe('currying', function () { + + it('should curry functions', function () { + var Type = func([Num, Num, Num], Num); + var sum = Type.of(function (a:any, b:any, c:any) { + return a + b + c; + }); + eq(sum(1, 2, 3), 6); + eq(sum(1, 2)(3), 6); + eq(sum(1)(2, 3), 6); + eq(sum(1)(2)(3), 6); + + // important: the curried function must be of the correct type + var CurriedType = func([Num, Num], Num); + var sum1 = sum(1); + eq(sum1(2, 3), 6); + eq(sum1(2)(3), 6); + ok(CurriedType.is(sum1)); + }); + + it('should throw if partial arguments are wrong', function () { + + var T = func([Num, Num], Num); + var sum = T.of(function (a:any, b:any) { + return a + b; + }); + + throwsWithMessage(function () { + sum('a'); + }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); + + throwsWithMessage(function () { + var sum1 = sum(1); + sum1('a'); + }, 'Invalid argument `value` = `a` supplied to irreducible type `Num`'); + + }); + + }); + +}); diff --git a/tcomb/tcomb.d.ts b/tcomb/tcomb.d.ts index 3c9197d86..c189a6a0f 100644 --- a/tcomb/tcomb.d.ts +++ b/tcomb/tcomb.d.ts @@ -1,420 +1,425 @@ -// Type definitions for tcomb v0.4 +// Type definitions for tcomb v1.0.3 // Project: http://gcanti.github.io/tcomb/guide/index.html -// Definitions by: Jed Mao +// Definitions by: Hans Windhoff // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module tcomb { +// Original Definitions by: Jed Mao +declare module TComb { + export interface tcomb { + format: (format: string, ...values: any[]) => string; + getFunctionName: (fn: Function) => string; + getTypeName: (type: TCombBase) => string; + mixin: (target: {}, source: {}, overwrite?: boolean) => any; + slice: typeof Array.prototype.slice; + shallowCopy: (x: TCombBase) => TCombBase; + update: (instance: any, spec: {} ) => TCombBase; + assert: (condition: boolean, message?: string, ...values: any[]) => void; + fail: (message?: string) => void; + Any: Any_Static; + Nil: Str_Static; + Str: Str_Static; + Num: Num_Static; + Bool: Bool_Static; + Arr: Arr_Static; + Obj: Obj_Static; - export var options: { - onFail: (message: string) => void; - }; + Func: Func_Static; + func: { (domain: TCombBase[], codomain: TCombBase, name?: string) : Func_Static; + (domain: TCombBase, codomain: TCombBase, name?: string) : Func_Static; + } + Err: Err_Static; + Re: Re_Static; + Dat: Dat_Static; + Type: Type_Static; + irreducible: (name: string, is: TypePredicate) => TCombBase; + struct: (props: Object, name?: string) => Struct_Static; - /** - * Like util.format in Node. - */ - export function format(format: string, ...values: any[]): string; - export function getKind(type: T): string; - /** - * Returns a function's name or displayName if specified; otherwise, - * fallbacks on '>'. - */ - export function getFunctionName(fn: Function): string; - export function getTypeName(type: T): string; - /** - * Safe version of mixin, properties can be overwritten. - */ - export function mixin(target: {}, source: {}, overwrite?: boolean): any; - export var slice: typeof Array.prototype.slice; - export function shallowCopy(x: T): T; - export function update(instance: any, spec: {}): T; - /** - * If an assert fails the debugger kicks in so you can inspect the stack - * and quickly find out what's wrong. - * @param message - Useful for debugging. Formatted with values like util.format in Node. - * @param values - Sequentially inserted into the message. - */ - export function assert(condition: boolean, message?: string, ...values: any[]): void; - export function fail(message?: string): void; + Union: Union_Static; + Maybe: Maybe_Static; - interface T { - meta: { + enums(map: Object, name?: string): TCombBase; + union(types: TCombBase[], name?: string): Union_Static; + maybe(type: TCombBase, name?: string): Maybe_Static; + + Tuple: Tuple_Static; + tuple:(types: TCombBase[], name?: string)=> Tuple_Static; + + Subtype: Subtype_Static; + + List: List_Static; + list:(type: TCombBase, name?: string)=> List_Static; + + Dict: Dict_Static; + dict:(domain: TCombBase, codomain: TCombBase, name?: string)=> Dict_Static; + + subtype(type: TCombBase, predicate: TypePredicate, name?: string): Subtype_Static; + + } + + + + + export interface TCombBase { + meta: { /** * The type kind, equal to "irreducible" for irreducible types. */ - kind: string; + kind: string; /** * The type name. */ - name: string; - }; - displayName: string; - is(value: any): boolean; - update(instance: any, spec: {}): T; - } + name: string; + }; + displayName: string; + is(value: any): boolean; + update(instance: any, spec: {}): TCombBase; + } - interface TypePredicate { - (x: any): Bool_Instance; - } + export interface TypePredicate { + (x: any): Bool_Instance; + } - interface Any_Instance { - } + export interface Any_Instance { + } - interface Any_Static extends T { - new (value: any): Any_Instance; - (value: any): Any_Instance; - } + export interface Any_Static extends TCombBase { - export var Any: Any_Static; + new (value: any): Any_Instance; + (value: any): Any_Instance; + } - interface Nil_Instance { - } - interface Nil_Static extends T { - new (value: any): Nil_Instance; - (value: any): Nil_Instance; - } - export var Nil: Str_Static; + export interface Nil_Instance { + } - interface Str_Instance extends String { - } + export interface Nil_Static extends TCombBase { + new (value: any): Nil_Instance; + (value: any): Nil_Instance; + } - interface Str_Static extends T { - new (value: string): Str_Instance; - (value: string): Str_Instance; - meta: { + + + export interface Str_Instance extends String { + } + + export interface Str_Static extends TCombBase { + new (value: string): Str_Instance; + (value: string): Str_Instance; + meta: { /** * The type kind, equal to "irreducible" for irreducible types. */ - kind: string; + kind: string; /** * The type name. */ - name: string; + name: string; /** * The type predicate. */ - is: TypePredicate; - }; - } + is: TypePredicate; + }; + } - export var Str: Str_Static; - interface Num_Instance extends Number { - } - interface Num_Static extends T { - new (value: number): Num_Instance; - (value: number): Num_Instance; - } + export interface Num_Instance extends Number { + } - export var Num: Num_Static; + export interface Num_Static extends TCombBase { + new (value: number): Num_Instance; + (value: number): Num_Instance; + } - interface Bool_Instance extends Boolean { - } - interface Bool_Static extends T { - new (value: boolean): Bool_Instance; - (value: boolean): Bool_Instance; - } - export var Bool: Bool_Static; + export interface Bool_Instance extends Boolean { + } - interface Arr_Instance extends Array { - } + export interface Bool_Static extends TCombBase { + new (value: boolean): Bool_Instance; + (value: boolean): Bool_Instance; + } - interface Arr_Static extends T { - new (value: any[]): Arr_Instance; - (value: any[]): Arr_Instance; - } - export var Arr: Arr_Static; - interface Obj_Instance extends Object { - } + export interface Arr_Instance extends Array { + } - interface Obj_Static extends T { - new (value: Object): Obj_Instance; - (value: Object): Obj_Instance; - } + export interface Arr_Static extends TCombBase { + new (value: any[]): Arr_Instance; + (value: any[]): Arr_Instance; + } - export var Obj: Obj_Static; - interface Func_Instance extends Function { - } - interface Func_Static extends T { - new (value: Function): Func_Instance; - (value: Function): Func_Instance; - } + export interface Obj_Instance extends Object { + } - export var Func: Func_Static; + export interface Obj_Static extends TCombBase { - interface Err_Instance extends Error { - } + new (value: Object): Obj_Instance; + (value: Object): Obj_Instance; + } - interface Err_Static extends T { - new (value: Error): Err_Instance; - (value: Error): Err_Instance; - } - export var Err: Err_Static; - interface Re_Instance extends RegExp { - } + export interface Func_Instance extends Function { + } - interface Re_Static extends T { - new (value: RegExp): Re_Instance; - (value: RegExp): Re_Instance; - } + export interface Func_Static extends TCombBase { + new (value: Function): Func_Instance; + (value: Function): Func_Instance; + } - export var Re: Re_Static; - interface Dat_Instance extends Date { - } + export interface Err_Instance extends Error { + } - interface Dat_Static extends T { - new (value: Date): Dat_Instance; - (value: Date): Dat_Instance; - } + export interface Err_Static extends TCombBase { + new (value: Error): Err_Instance; + (value: Error): Err_Instance; + } - export var Dat: Dat_Static; - interface Type_Instance { - } + export interface Re_Instance extends RegExp { + } + + export interface Re_Static extends TCombBase { + new (value: RegExp): Re_Instance; + (value: RegExp): Re_Instance; + } + + + export interface Dat_Instance extends Date { + } + + export interface Dat_Static extends TCombBase { + new (value: Date): Dat_Instance; + (value: Date): Dat_Instance; + } + + export interface Type_Instance { + } + + export interface Type_Static extends TCombBase { + new (value: any): Type_Instance; + (value: any): Type_Instance; + } - interface Type_Static extends T { - new (value: any): Type_Instance; - (value: any): Type_Instance; - } - export var Type: Type_Static; /** * @param name - The type name. * @param is - A predicate. */ - export function irreducible(name: string, is: TypePredicate): T; + /** * @param props - A hash whose keys are the field names and the values are the fields types. * @param name - Useful for debugging purposes. */ - export function struct(props: Object, name?: string): typeof Struct; - export interface Struct_Static extends T { - new (value: any, mutable?: boolean): Struct_Instance; - (value: any, mutable?: boolean): Struct_Instance; - meta: { - kind: string; - name: string; - props: any[]; - }; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ - extend(mixins: Object, name?: string): Struct_Static; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ - extend(mixins: Struct_Static, name?: string): Struct_Static; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ - extend(mixins: Object[], name?: string): Struct_Static; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ - extend(mixins: Struct_Static[], name?: string): Struct_Static; - } - interface Struct_Instance { - } + export interface Struct_Static extends TCombBase { + new (value: any, mutable?: boolean): Struct_Instance; + (value: any, mutable?: boolean): Struct_Instance; + meta: { + kind: string; + name: string; + props: any[]; + }; + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ + extend(mixins: Object, name?: string): Struct_Static; + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ + extend(mixins: Struct_Static, name?: string): Struct_Static; + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ + extend(mixins: Object[], name?: string): Struct_Static; + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ + extend(mixins: Struct_Static[], name?: string): Struct_Static; + } - export var Struct: Struct_Static; + interface Struct_Instance { + } /** * @param map - A hash whose keys are the enums (values are free). * @param name - Useful for debugging purposes. */ - export function enums(map: Object, name?: string): T; - export module enums { + + export module enums { /** * @param keys - Array of enums. * @param name - Useful for debugging purposes. */ - export function of(keys: string[], name?: string): T; + export function of(keys: string[], name?: string): TCombBase; /** * @param keys - String of enums separated by spaces. * @param name - Useful for debugging purposes. */ - export function of(keys: string, name?: string): T; - } + export function of(keys: string, name?: string): TCombBase; + } /** * @param name - Useful for debugging purposes. */ - export function union(types: T[], name?: string): Union_Static; - interface Union_Static extends T { - new (value: any, mutable?: boolean): Union_Instance; - (value: any, mutable?: boolean): Union_Instance; - meta: { - kind: string; - name: string; - types: T[]; - }; - dispatch(x: any): T; - } + export interface Union_Static extends TCombBase { + new (value: any, mutable?: boolean): Union_Instance; + (value: any, mutable?: boolean): Union_Instance; + meta: { + kind: string; + name: string; + types: TCombBase[]; + }; + dispatch(x: any): TCombBase; + } - interface Union_Instance { - } + export interface Union_Instance { + } - export var Union: Union_Static; /** * @param type - The wrapped type. * @param name - Useful for debugging purposes. */ - export function maybe(type: T, name?: string): Maybe_Static; - export interface Maybe_Static extends T { - new (value: any, mutable?: boolean): Maybe_Instance; - (value: any, mutable?: boolean): Maybe_Instance; - meta: { - kind: string; - name: string; - typee: T; - }; - } - interface Maybe_Instance { - } - export var Maybe: Maybe_Static; + export interface Maybe_Static extends TCombBase { + new (value: any, mutable?: boolean): Maybe_Instance; + (value: any, mutable?: boolean): Maybe_Instance; + meta: { + kind: string; + name: string; + typee: TCombBase; + }; + } + + interface Maybe_Instance { + } + /** * @param name - Useful for debugging purposes. */ - export function tuple(types: T[], name?: string): Tuple_Static; - interface Tuple_Static extends T { - new (value: any, mutable?: boolean): Tuple_Instance; - (value: any, mutable?: boolean): Tuple_Instance; - meta: { - kind: string; - name: string; - types: T[]; - }; - } + interface Tuple_Static extends TCombBase { + new (value: any, mutable?: boolean): Tuple_Instance; + (value: any, mutable?: boolean): Tuple_Instance; + meta: { + kind: string; + name: string; + types: TCombBase[]; + }; + } - interface Tuple_Instance { - } + interface Tuple_Instance { + } - export var Tuple: Tuple_Static; - /** * Combines old types into a new one. * @param type - A type already defined. * @param name - Useful for debugging purposes. */ - export function subtype(type: T, predicate: TypePredicate, name?: string): typeof Subtype; - interface Subtype_Static extends T { - new (value: any, mutable?: boolean): Subtype_Instance; - (value: any, mutable?: boolean): Subtype_Instance; - meta: { - kind: string; - name: string; - type: T; - predicate: TypePredicate; - }; - } - interface Subtype_Instance { - } + export interface Subtype_Static extends TCombBase { + new (value: any, mutable?: boolean): Subtype_Instance; + (value: any, mutable?: boolean): Subtype_Instance; + meta: { + kind: string; + name: string; + type: TCombBase; + predicate: TypePredicate; + }; + } - export var Subtype: Subtype_Static; + interface Subtype_Instance { + } /** * @param type - The type of list items. * @param name - Useful for debugging purposes. */ - export function list(type: T, name?: string): List_Static; + export function list(type: TCombBase, name?: string): List_Static; - interface List_Static extends T { - new (value: any, mutable?: boolean): List_Instance; - (value: any, mutable?: boolean): List_Instance; - meta: { - kind: string; - name: string; - 'type': T; - }; - } + interface List_Static extends TCombBase { + new (value: any, mutable?: boolean): List_Instance; + (value: any, mutable?: boolean): List_Instance; + meta: { + kind: string; + name: string; + 'type': TCombBase; + }; + } - interface List_Instance { - } - - export var List: List_Static; + interface List_Instance { + } /** * @param domain - The type of keys. * @param codomain - The type of values. * @param name - Useful for debugging purposes. */ - export function dict(domain: T, codomain: T, name?: string): Dict_Static; - interface Dict_Static extends T { - new (value: any, mutable?: boolean): Dict_Instance; - (value: any, mutable?: boolean): Dict_Instance; - meta: { - kind: string; - name: string; - domain: T; - codomain: T; - }; - } - interface Dict_Instance { - } + interface Dict_Static extends TCombBase { + new (value: any, mutable?: boolean): Dict_Instance; + (value: any, mutable?: boolean): Dict_Instance; + meta: { + kind: string; + name: string; + domain: TCombBase; + codomain: TCombBase; + }; + } - export var Dict: Dict_Static; + interface Dict_Instance { + } /** * @param type - The type of the function's argument. * @param codomain - The type of the function's return value. * @param name - Useful for debugging purposes. */ - export function func(domain: T, codomain: T, name?: string): Func_Static; /** * @param type - The list of types of the function's arguments. * @param codomain - The type of the function's return value. * @param name - Useful for debugging purposes. */ - export function func(domain: T[], codomain: T, name?: string): Func_Static; - interface Func_Static extends T { - new (value: any, mutable?: boolean): Func_Instance; - (value: any, mutable?: boolean): Func_Instance; - meta: { - kind: string; - name: string; - domain: any; - codomain: T; - }; - of(fn: Function): Function; - } + interface Func_Static extends TCombBase { + new (value: any, mutable?: boolean): Func_Instance; + (value: any, mutable?: boolean): Func_Instance; + meta: { + kind: string; + name: string; + domain: any; + codomain: TCombBase; + }; + of(fn: Function): Function; + } - interface Func_Instance { - } - - export var Func: Func_Static; + interface Func_Instance { + } } +declare var t: TComb.tcomb; + declare module "tcomb" { - export = tcomb; + export = t; } diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 7c4aca592..d87541145 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,4 +1,4 @@ -// Type definitions for three.js r70 +// Type definitions for three.js r71 // Project: http://mrdoob.github.com/three.js/ // Definitions by: Kon , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -129,6 +129,7 @@ declare module THREE { export var IntType: TextureDataType; export var UnsignedIntType: TextureDataType; export var FloatType: TextureDataType; + export var HalfFloatType: TextureDataType; // Pixel types export enum PixelType { } @@ -159,6 +160,12 @@ declare module THREE { export var RGBA_PVRTC_4BPPV1_Format: CompressedPixelFormat; export var RGBA_PVRTC_2BPPV1_Format: CompressedPixelFormat; + // log handlers + export function warn(message?: any, ...optionalParams: any[]): void; + export function error(message?: any, ...optionalParams: any[]): void; + export function log(message?: any, ...optionalParams: any[]): void; + + // Cameras //////////////////////////////////////////////////////////////////////////////////////// /** @@ -364,7 +371,7 @@ declare module THREE { length: number; copyAt(index1: number, attribute: BufferAttribute, index2: number): void; - set(value: number): BufferAttribute; + set(value: number, offset?: number): BufferAttribute; setX(index: number, x: number): BufferAttribute; setY(index: number, y: number): BufferAttribute; setZ(index: number, z: number): BufferAttribute; @@ -456,8 +463,7 @@ declare module THREE { */ applyMatrix(matrix: Matrix4): void; - // this method is currently empty. - center(): void; + center(): Vector3; fromGeometry( geometry: Geometry, settings?: any ): BufferGeometry; @@ -488,7 +494,7 @@ declare module THREE { */ computeTangents(): void; - computeOffsets(indexBufferSize: number): void; + computeOffsets(size: number): void; merge(geometry: BufferGeometry, offset: number): BufferGeometry; normalizeNormals(): void; reorderBuffers(indexBuffer: number, indexMap: number[], vertexCount: number): void; @@ -569,6 +575,17 @@ declare module THREE { getDelta(): number; } + export class DynamicBufferAttribute extends BufferAttribute{ + constructor(array: any, itemSize: number); + + updateRange: { + offset: number; + count: number; + } + + clone(): DynamicBufferAttribute; + } + /** * JavaScript events for custom objects * @@ -1065,6 +1082,8 @@ declare module THREE { */ frustumCulled: boolean; + renderOrder: number; + /** * An object that can be used to store custom data about the Object3d. It should not hold references to functions as these will not be cloned. */ @@ -1193,23 +1212,21 @@ declare module THREE { remove(object: Object3D): void; /* deprecated */ - getChildByName( name: string, recursive?: boolean ): Object3D; + getChildByName( name: string ): Object3D; /** * Searches through the object's children and returns the first with a matching id, optionally recursive. * @param id Unique number of the object instance - * @param recursive Boolean whether to search through the children's children. Default is false. */ - getObjectById(id: string, recursive: boolean): Object3D; + getObjectById(id: string): Object3D; /** * Searches through the object's children and returns the first with a matching name, optionally recursive. * @param name String to match to the children's Object3d.name property. - * @param recursive Boolean whether to search through the children's children. Default is false. */ - getObjectByName(name: string, recursive?: boolean): Object3D; + getObjectByName(name: string): Object3D; - getObjectByProperty( name: string, value: string, recursive?: boolean ): Object3D; + getObjectByProperty( name: string, value: string ): Object3D; getWorldPosition(optionalTarget?: Vector3): Vector3; getWorldQuaternion(optionalTarget?: Quaternion): Quaternion; @@ -1521,7 +1538,7 @@ declare module THREE { * scene.add( light ); */ export class PointLight extends Light { - constructor(hex?: number, intensity?: number, distance?: number); + constructor(hex?: number, intensity?: number, distance?: number, decay?: number); /* * Light's intensity. @@ -1535,6 +1552,8 @@ declare module THREE { */ distance: number; + decay: number; + clone(): PointLight; } @@ -1554,7 +1573,7 @@ declare module THREE { * scene.add( spotLight ); */ export class SpotLight extends Light { - constructor(hex?: number, intensity?: number, distance?: number, angle?: number, exponent?: number); + constructor(hex?: number, intensity?: number, distance?: number, angle?: number, exponent?: number, decay?: number); /** * Spotlight focus points at target.position. @@ -1586,6 +1605,8 @@ declare module THREE { */ exponent: number; + decay: number; + /** * If set to true light will cast dynamic shadows. Warning: This is expensive and requires tweaking to get shadows looking right. * Default — false. @@ -1744,9 +1765,7 @@ declare module THREE { parse(json: any): BufferGeometry; } - export class Cache{ - constructor(); - + export interface Cache{ files: any[]; add(key: string, file: any): void; @@ -1754,6 +1773,7 @@ declare module THREE { remove(key: string): void; clear(): void; } + export var Cache:Cache; export class CompressedTextureLoader{ constructor(); @@ -1856,14 +1876,18 @@ declare module THREE { constructor(manager?: LoadingManager); manager: LoadingManager; - crossOrigin: string; + texturePass: string; - load(url: string, onLoad: (object: Object3D) => void): void; + load(url: string, onLoad?: (object: Object3D) => void): void; + setTexturePath( value: string ): void; setCrossOrigin(crossOrigin: string): void; - parse(json: any): T; + parse(json: any, onLoad?: (object: Object3D) => void): T; parseGeometries(json: any): any[]; // Array of BufferGeometry or Geometry or Geometry2. - parseMaterials(json: any): Material[]; // Array of Classes that inherits from Matrial. + parseMaterials(json: any, textures: Texture[]): Material[]; // Array of Classes that inherits from Matrial. + parseImages( json: any, onLoad: () => void ): any[]; + parseTextures( json: any, images: any ): Texture[]; parseObject(data: any, geometries: any[], materials: Material[]): T; + } /** @@ -1976,6 +2000,10 @@ declare module THREE { */ blendEquation: BlendingEquation; + blendSrcAlpha: number; + blendDstAlpha: number; + blendEquationAlpha: number; + /** * Whether to have depth test enabled when rendering this material. Default is true. */ @@ -1987,6 +2015,8 @@ declare module THREE { */ depthWrite: boolean; + colorWrite: boolean; + /** * Whether to use polygon offset. Default is false. This corresponds to the POLYGON_OFFSET_FILL WebGL feature. */ @@ -2026,6 +2056,7 @@ declare module THREE { setValues(values: Object): void; toJSON(): any; clone(material?:Material): Material; + update(): void; dispose(): void; // EventDispatcher mixins @@ -2156,7 +2187,6 @@ declare module THREE { export interface MeshLambertMaterialParameters extends MaterialParameters{ color?: number; - ambient?: number; emissive?: number; wrapAround?: boolean; wrapRGB?: Vector3; @@ -2183,7 +2213,6 @@ declare module THREE { export class MeshLambertMaterial extends Material { constructor(parameters?: MeshLambertMaterialParameters); color: Color; - ambient: Color; emissive: Color; wrapAround: boolean; wrapRGB: Vector3; @@ -2210,7 +2239,6 @@ declare module THREE { } export interface MeshNormalMaterialParameters extends MaterialParameters{ - shading?: Shading; wireframe?: boolean; wireframeLinewidth?: number; morphTargets?: boolean; @@ -2219,7 +2247,6 @@ declare module THREE { export class MeshNormalMaterial extends Material { constructor(parameters?: MeshNormalMaterialParameters); - shading: Shading; wireframe: boolean; wireframeLinewidth: number; morphTargets: boolean; @@ -2229,7 +2256,6 @@ declare module THREE { export interface MeshPhongMaterialParameters extends MaterialParameters{ color?: number; // diffuse - ambient?: number; emissive?: number; specular?: number; shininess?: number; @@ -2264,7 +2290,6 @@ declare module THREE { constructor(parameters?: MeshPhongMaterialParameters); color: Color; // diffuse - ambient: Color; emissive: Color; specular: Color; shininess: number; @@ -2531,13 +2556,13 @@ declare module THREE { * Copies given color making conversion from gamma to linear space. * @param color Color to copy. */ - copyGammaToLinear(color: Color): Color; + copyGammaToLinear(color: Color, gammaFactor?: number): Color; /** * Copies given color making conversion from linear to gamma space. * @param color Color to copy. */ - copyLinearToGamma(color: Color): Color; + copyLinearToGamma(color: Color, gammaFactor?: number): Color; /** * Converts this color from gamma to linear space. @@ -2577,7 +2602,7 @@ declare module THREE { lerp(color: Color, alpha: number): Color; equals(color: Color): boolean; fromArray(rgb: number[]): Color; - toArray(): number[]; + toArray(array?: number[], offset?: number): number[]; /** * Clones this color. @@ -2751,7 +2776,7 @@ declare module THREE { reorder(newOrder: string): Euler; equals(euler: Euler): boolean; fromArray(xyzo: any[]): Euler; - toArray(): any[]; + toArray(array?: number[], offset?: number): number[]; toVector3(optionalResult?: Vector3): Vector3; onChange: () => void; @@ -2860,6 +2885,8 @@ declare module THREE { radToDeg(radians: number): number; isPowerOfTwo(value: number): boolean; + + nextPowerOfTwo(value: number): number; } /** @@ -3558,8 +3585,8 @@ declare module THREE { /** * Sets this vector to a + b. */ - addVectors(a: Vector2, b: Vector2): Vector2; addScalar(s: number): Vector2; + addVectors(a: Vector2, b: Vector2): Vector2; /** * Subtracts v from this vector. @@ -3635,6 +3662,9 @@ declare module THREE { setLength(l: number): Vector2; lerp(v: Vector2, alpha: number): Vector2; + + lerpVectors(v1: Vector2, v2: Vector2, alpha: number): Vector2; + /** * Checks for strict equality of this vector and v. */ @@ -3717,6 +3747,8 @@ declare module THREE { */ sub(a: Vector3): Vector3; + subScalar( s: number ): Vector3; + /** * Sets this vector to a - b. */ @@ -3790,6 +3822,8 @@ declare module THREE { setLength(l: number): Vector3; lerp(v: Vector3, alpha: number): Vector3; + lerpVectors(v1: Vector3, v2: Vector3, alpha: number): Vector3; + /** * Sets this vector to cross product of itself and v. */ @@ -3896,6 +3930,8 @@ declare module THREE { */ sub(v: Vector4): Vector4; + subScalar(s: number): Vector4; + /** * Sets this vector to a - b. */ @@ -3969,6 +4005,8 @@ declare module THREE { */ lerp(v: Vector4, alpha: number): Vector4; + lerpVectors(v1: Vector4, v2: Vector4, alpha: number): Vector4; + /** * Checks for strict equality of this vector and v. */ @@ -3989,7 +4027,7 @@ declare module THREE { // Objects ////////////////////////////////////////////////////////////////////////////////// export class Bone extends Object3D { - constructor(belongsToSkin: SkinnedMesh); + constructor(skin: SkinnedMesh); skin: SkinnedMesh; } @@ -4291,6 +4329,8 @@ declare module THREE { */ sortObjects: boolean; + gammaFactor: number; + /** * Default is false. */ @@ -4480,7 +4520,7 @@ declare module THREE { uploadTexture(texture: Texture): void; setTexture(texture: Texture, slot: number): void; setRenderTarget(renderTarget: RenderTarget): void; - + readRenderTargetPixels( renderTarget: RenderTarget, x: number, y: number, width: number, height: number, buffer: any ): void; } export interface RenderTarget { @@ -4539,6 +4579,7 @@ declare module THREE { export interface ShaderChunk { [name: string]: string; + common: string; alphamap_fragment: string; alphamap_pars_fragment: string; alphatest_fragment: string; @@ -4613,6 +4654,7 @@ declare module THREE { normal: Shader; normalmap: Shader; cube: Shader; + equirect: Shader; depthRGBA: Shader; }; @@ -4655,6 +4697,40 @@ declare module THREE { constructor(gl: any, type: string, string: string); } + interface WebGLStateInstance{ + new ( gl: any, paramThreeToGL: Function ): void; + initAttributes(): void; + enableAttribute(attribute: string): void; + disableUnusedAttributes(): void; + setBlending( blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number ): void; + setDepthTest( depthTest: number ): void; + setDepthWrite( depthWrite: number ): void; + setColorWrite( colorWrite: number ): void; + setDoubleSided( doubleSided: number ): void; + setFlipSided( flipSided: number ): void; + setLineWidth( width: number ): void; + setPolygonOffset(polygonoffset: number, factor: number, units: number): void; + reset(): void; + } + interface WebGLStateStatic{ + ( gl: any, paramThreeToGL: Function ): WebGLStateInstance; + } + export var WebGLState: WebGLStateStatic; + + + interface WebGLTexturesInstance{ + new (webgglcontext: any): WebGLTexturesInstance; + + get(texture: Texture): any; // it will return result of gl.createTexture(). + create(texture: Texture): any; // it will return result of gl.createTexture(). + delete(texture: Texture): void; + } + interface WebGLTexturesStatic{ + (webgglcontext: any): WebGLTexturesInstance; + } + export var WebGLTextures: WebGLTexturesStatic; + + // Renderers / WebGL / Plugins ///////////////////////////////////////////////////////////////////// export interface RendererPlugin { init(renderer: WebGLRenderer): void; @@ -4821,29 +4897,7 @@ declare module THREE { export class Texture { constructor( - image: any, // HTMLImageElement or HTMLCanvasElement ( or HTMLVideoElement) - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - constructor( - image: HTMLCanvasElement, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - constructor( - image: HTMLImageElement, + image: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, mapping?: Mapping, wrapS?: Wrapping, wrapT?: Wrapping, @@ -4857,6 +4911,7 @@ declare module THREE { id: number; uuid: string; name: string; + sourceFile: string; image: any; // HTMLImageElement or ImageData ; mipmaps: ImageData[]; mapping: Mapping; @@ -4992,14 +5047,13 @@ declare module THREE { isPlaying: boolean; loop: boolean; weight: number; - keyTypes: string[]; interpolationType: number; play(startTime?: number, weight?: number): void; stop(): void; reset(): void; resetBlendWeights(): void; - update(deltaTimeMS: number): void; + update(delta: number): void; getNextKeyWith(type: string, h: number, key: number): KeyFrame; getPrevKeyWith(type: string, h: number, key: number): KeyFrame; } @@ -5022,7 +5076,7 @@ declare module THREE { constructor(data: any); root: Mesh; - data: Object; + data: AnimationData; hierarchy: KeyFrames[]; currentTime: number; timeScale: number; @@ -5051,7 +5105,7 @@ declare module THREE { play(): void; pause(): void; - update(deltaTimeMS: number): void; + update(delta: number): void; } // Extras / Audio ///////////////////////////////////////////////////////////////////// @@ -5063,11 +5117,18 @@ declare module THREE { source: AudioBufferSourceNode; gain: GainNode; panner: PannerNode; + autoplay: boolean; + startTime: number; + isPlaying: boolean; load(file: string): Audio; + play(): void; + pause(): void; + stop(): void; setLoop(value: boolean): void; setRefDistance(value: number): void; setRolloffFactor(value: number): void; + setVolume(value: number): void; updateMatrixWorld(force?: boolean): void; } @@ -5646,7 +5707,7 @@ declare module THREE { } export class EdgesHelper extends Line { - constructor(object: Object3D, hex?: number); + constructor(object: Object3D, hex?: number, thresholdAngle?: number); } @@ -5669,7 +5730,7 @@ declare module THREE { setColors(colorCenterLine: number, colorGrid: number): void; } export class HemisphereLightHelper extends Object3D { - constructor(light: Light, sphereSize: number, arrowLength: number, domeSize: number); + constructor(light: Light, sphereSize: number); light: Light; colors: Color[]; diff --git a/type-check/type-check-tests.ts b/type-check/type-check-tests.ts new file mode 100644 index 000000000..b1d629309 --- /dev/null +++ b/type-check/type-check-tests.ts @@ -0,0 +1,95 @@ +// run this in node +/// +import tchecker = require("type-check"); + +var typeCheck = (i1:string,i2:any,i3?: TypeCheck.Options ) => { + console.log(tchecker.typeCheck(i1,i2,i3)); + } ; +var parseType = (i1:string) => { + var res = tchecker.parseType(i1); + console.log(res); + return res; + } ; +var parsedTypeCheck= (i1:any,i2:any) => { + var res =tchecker.parsedTypeCheck(i1,i2); + console.log(res); + return res; + } ; +var TCVersion= () => { console.log(tchecker.VERSION); } ; + + + +console.log("===>testing typeCheck function"); +typeCheck('Number', 1); // true +typeCheck('Number', 2); // true +typeCheck('Number', 'str'); // false +typeCheck('Error', new Error); // true +typeCheck('Undefined', undefined); // true + +console.log("===>testing typeCheck function on Date"); +typeCheck('Date', new Date()); // true +typeCheck('Date', new Date("invalid")); // false + +// Comment +typeCheck('count::Number', 1); // true + +// One type OR another type: +typeCheck('Number | String', 2); // true +typeCheck('Number | String', 'str'); // true + +// Wildcard, matches all types: +typeCheck('*', 2) // true + +// Array, all elements of a single type: +typeCheck('[Number]', [1, 2, 3]); // true +typeCheck('[Number]', [1, 'str', 3]); // false + +// Tuples, or fixed length arrays with elements of different types: +typeCheck('(String, Number)', ['str', 2]); // true +typeCheck('(String, Number)', ['str']); // false +typeCheck('(String, Number)', ['str', 2, 5]); // false + +// Object properties: +typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true +typeCheck('{x: Number, y: Boolean}', {x: 2}); // false +typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true +typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false +typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true + +// A particular type AND object properties: +typeCheck('RegExp{source: String, ...}', /re/i); // true +typeCheck('RegExp{source: String, ...}', {source: 're'}); // false + + + +console.log("===>testing custom types"); +// Custom types: +var opt = {customTypes: + {Even: { typeOf: 'Number', + validate: function(x:number) { console.log("=>testing even"); return x % 2 === 0; } +}}}; +typeCheck('Even', 2, opt); // true + + +opt = {customTypes: +{Odd : { typeOf: 'Number', + validate: function(x:number) { console.log("=>testing odd");return x % 2 !== 0; } +}}}; +typeCheck('Odd', 3, opt); // true + + +console.log("===>testing nested types"); +// Nested: +var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' +typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true + + + + + +console.log("===>testing parseType function"); +// parseType(type); +var parsedType = parseType( 'Number'); // object +console.log("===>testing parsedTypeCheck function"); +// parsedTypeCheck(parsedType, input, options); +parsedTypeCheck(parsedType, 2); // true diff --git a/type-check/type-check.d.ts b/type-check/type-check.d.ts new file mode 100644 index 000000000..12b7de594 --- /dev/null +++ b/type-check/type-check.d.ts @@ -0,0 +1,33 @@ +// Type definitions for type-check v0.3.1 +// Project: https://github.com/gkz/type-check +// Definitions by: Hans Windhoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module TypeCheck { + + export interface CustomType { + [typeName: string]: { + typeOf: string; + validate: (x: any)=> any; + } + } + + export interface Options { + customTypes: CustomType; + } + + export interface TC{ + VERSION: string; + typeCheck: (typeDescription: string , inst: any, options?: Options) => boolean; + parseType: (typeDescription: string) => Object; + parsedTypeCheck: (parsedType: any, obj: any) => boolean; + + } +} + +declare var typecheck: TypeCheck.TC; + +declare module "type-check" { + export=typecheck; +} diff --git a/underscore/underscore-tests.ts b/underscore/underscore-tests.ts index 3fb993a3d..60c1708d0 100644 --- a/underscore/underscore-tests.ts +++ b/underscore/underscore-tests.ts @@ -11,6 +11,7 @@ _.map({ one: 1, two: 2, three: 3 }, (value, key) => value * 3); //var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); // https://typescript.codeplex.com/workitem/1960 var sum = _.reduce([1, 2, 3], (memo, num) => memo + num, 0); sum = _.reduce([1, 2, 3], (memo, num) => memo + num); // memo is optional #issue 5 github +sum = _.reduce({'a':'1', 'b':'2', 'c':'3'}, (memo, numstr) => memo + (+numstr)); var list = [[0, 1], [2, 3], [4, 5]]; //var flat = _.reduceRight(list, (a, b) => a.concat(b), []); // https://typescript.codeplex.com/workitem/1960 diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 7ff9aa5eb..03088bffd 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -41,18 +41,6 @@ declare module _ { escape?: RegExp; } - interface ListIterator { - (value: T, index: number, list: T[]): TResult; - } - - interface ObjectIterator { - (element: T, key: string, list: any): TResult; - } - - interface MemoIterator { - (prev: TResult, curr: T, index: number, list: T[]): TResult; - } - interface Collection { } // Common interface between Arrays and jQuery objects @@ -64,6 +52,22 @@ declare module _ { interface Dictionary extends Collection { [index: string]: T; } + + interface ListIterator { + (value: T, index: number, list: List): TResult; + } + + interface ObjectIterator { + (element: T, key: string, list: Dictionary): TResult; + } + + interface MemoIterator { + (prev: TResult, curr: T, index: number, list: List): TResult; + } + + interface MemoObjectIterator { + (prev: TResult, curr: T, key: string, list: Dictionary): TResult; + } } interface UnderscoreStatic { @@ -181,7 +185,7 @@ interface UnderscoreStatic { reduce( list: _.Dictionary, - iterator: _.ObjectIterator, + iterator: _.MemoObjectIterator, memo?: TResult, context?: any): TResult; diff --git a/victor/victor-tests.ts b/victor/victor-tests.ts new file mode 100644 index 000000000..76eb79c22 --- /dev/null +++ b/victor/victor-tests.ts @@ -0,0 +1,52 @@ +/// + +var vector1 = new Victor(10,10) +var vector2 = new Victor(20,20) + +vector1.add(vector2).addX(vector2).addY(vector2) + +vector1.clone().copy(vector2).toString() + +vector1.toArray() +vector1.toObject() + +vector1.subtract(vector2).subtractX(vector2).subtractY(vector2) +.multiply(vector2).multiplyX(vector2).multiplyY(vector2) +.divide(vector2).divideX(vector2).divideY(vector2) +.invert().invertX().invertY() +.mix(vector2, 0.5).mixX(vector2,0.5).mixY(vector2,0.5) +.normalize().norm() +.limit(100,5) +.unfloat() +.rotate(10) +.rotateDeg(10) +.rotateBy(10) +.rotateByDeg(10) +.randomize(new Victor(10,10), new Victor(100,100)).randomizeY(new Victor(10,10), new Victor(100,100)).randomizeX(new Victor(10,10), new Victor(100,100)).randomizeAny(new Victor(10,10), new Victor(100,100)) + +vector2.dot(vector1) +vector2.cross(vector1) + +vector1.length() +vector1.lengthSq() + +vector1.distance(vector2) +vector1.distanceSq(vector2) + +vector1.distanceX(vector2) +vector1.distanceY(vector2) + +vector1.horizontalAngle() +vector1.horizontalAngleDeg() +vector1.angle() +vector1.angleDeg() +vector1.verticalAngle() +vector1.verticalAngleDeg() + + + + + + + + diff --git a/victor/victor.d.ts b/victor/victor.d.ts new file mode 100644 index 000000000..4206ffeb6 --- /dev/null +++ b/victor/victor.d.ts @@ -0,0 +1,355 @@ +// Type definitions for Victor.js 0.2.5 +// Project: http://victorjs.org/ +// Definitions by: Ivane Gegia +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +interface VictorCoordinates +{ + x:number + y:number +} + +declare class Victor +{ + x:number; + y:number; + + /** + * Can be used without the new keyword. + * @param x The X component + * @param y The Y component + */ + constructor(x:number,y:number); + + /** + * Creates vector from array. + * @param arr array An array that contains the X component in the first element and the Y component in the second + */ + static fromArray(arr:Array):Victor; + + /** + * Creates vector from object. + * @param obj An object containing the X component in the x property and the Y component in the y property + */ + static fromObject(obj:VictorCoordinates):Victor; + + /** + * Creates a new Victor with the same X and Y components. + */ + clone():Victor; + + /** + * Copies the X component of another vector in to itself. + * @param vector + */ + copyX(vector:Victor):Victor; + + /** + * Copies the Y component of another vector in to itself. + * @param vector + */ + copyY(vector:Victor):Victor; + + /** + * Copies the X and Y components of another vector in to itself. + * @param vector + */ + copy(vector:Victor):Victor; + + /** + * Returns a string representation of the X and Y components. + */ + toString():string; + + /** + * Returns an array representation of the X and Y components. + */ + toArray():Array; + + /** + * Returns an object representation of tha X and Y components. + */ + toObject():VictorCoordinates; + + /** + * Adds another vector's X component to itself. + * @param vector + */ + addX(vector:Victor):Victor; + + /** + * Adds another vector's Y component to itself. + * @param vector + */ + addY(vector:Victor):Victor; + + /** + * Adds another vector to itself. + * @param vector + */ + add(vector:Victor):Victor; + + /** + * Subtracts another vector's X component from itself. + * @param vector + */ + subtractX(vector:Victor):Victor; + + /** + * Subtracts another vector's Y component from itself. + * @param vector + */ + subtractY(vector:Victor):Victor; + + /** + * Subtracts another vector from itself. + * @param vector + */ + subtract(vector:Victor):Victor; + + /** + * Multiplies the X component with the X component of another vector. + * @param vector + */ + multiplyX(vector:Victor):Victor; + + /** + * Multiplies the Y component with the Y component of another vector. + * @param vector + */ + multiplyY(vector:Victor):Victor; + + /** + * Multiplies both components with another vector. + * @param vector + */ + multiply(vector:Victor):Victor; + + /** + * Divides the X component by the X component of another vector. + * @param vector + */ + divideX(vector:Victor):Victor; + + /** + * Divides the Y component by the Y component of another vector. + * @param vector + */ + divideY(vector:Victor):Victor; + + /** + * Divides both components by another vector. + * @param scalar + */ + divide(scalar:Victor):Victor; + + /** + * Inverts the X component. + */ + invertX():Victor; + + /** + * Inverts the Y component. + */ + invertY():Victor; + + /** + * Inverts both components. + */ + invert():Victor; + + /** + * Performs a linear blend / interpolation of the X component towards another vector. + * @param vector Number amount Value between 0 and 1. Default: 0.5 + * @param ammount + */ + mixX(vector:Victor, ammount:number):Victor; + + /** + * Performs a linear blend / interpolation of the Y component towards another vector. + * @param vector + * @param ammount + */ + mixY(vector:Victor, ammount:number):Victor; + + /** + * Performs a linear blend / interpolation towards another vector. + * @param vector + * @param ammount + */ + mix(vector:Victor, ammount:number):Victor; + + /** + * Normalizes the vector by scaling it down to a length of 1 while keeping its direction. + */ + normalize():Victor; + + /** + * Alias of normalize. + */ + norm():Victor; + + /** + * If either component is greater than max, multiplies the component by multiplier. + * @param max + * @param multiplier + */ + limit(max:number, multiplier:number):Victor; + + /** + * Rounds the components to integer numbers. + */ + unfloat():Victor; + + /** + * Rotates the vector to a certain angle, in radians CCW from +X axis. + * @param angle + */ + rotate(angle:number):Victor; + + /** + * Same as rotate but uses degrees + * @param angle + */ + rotateDeg(angle:number):Victor; + + /** + * Rotates the vector by a rotation angle, given in radians CCW from +X axis. + * @param rotation + */ + rotateBy(rotation:number):Victor; + + /** + * Same as rotateBy but uses degrees + * @param rotation + */ + rotateByDeg(rotation:number):Victor; + + /** + * Randomizes the X component with a value between topLeft and bottomRight. + * @param topLeft + * @param bottomRight + */ + randomizeX(topLeft:Victor, bottomRight:Victor):Victor; + + /** + * Randomizes the Y component with a value between topLeft and bottomRight. + * @param topLeft + * @param bottomRight + */ + randomizeY(topLeft:Victor, bottomRight:Victor):Victor; + + /** + * Randomizes the components with a value between topLeft and bottomRight. + * @param topLeft + * @param bottomRight + */ + randomize(topLeft:Victor, bottomRight:Victor):Victor; + + /** + * Randomly randomizes either the X component or the Y component with a value between topLeft and bottomRight. + * @param topLeft + * @param bottomRight + */ + randomizeAny(topLeft:Victor, bottomRight:Victor):Victor; + + /** + * Returns the dot product of two vectors. + * @param vector + */ + dot(vector:Victor):number; + + /** + * Returns the cross product of two vectors. + * @param vector + */ + cross(vector:Victor):number; + + /** + * Returns the length / magnitude. + */ + length():number; + + /** + * Alias for length. + */ + magnitude():number; + + /** + * Returns the squared length / magnitude. If the length is only needed for comparison, this function is faster than length. + */ + lengthSq():number; + + /** + * Returns the distance of the X component from another vector. + * @param vector + */ + distanceX(vector:Victor):number; + + /** + * Same as distanceX but always returns an absolute value. + * @param vector + */ + absDistanceX(vector:Victor):number; + + /** + * Returns the distance of the Y component from another vector. + * @param vector + */ + distanceY(vector:Victor):number; + + /** + * Same as distanceY but always returns an absolute value. + * @param vector + */ + absDistanceY(vector:Victor):number; + + /** + * Returns the euclidean distance between two vectors. + * @param vector + */ + distance(vector:Victor):number; + + /** + * Returns the squared euclidean distance between two vectors. If the distance is only needed for comparison, this function is faster than distance. + * @param vector + */ + distanceSq(vector:Victor):number; + + /** + * Returns the angle towards X in radians. + */ + horizontalAngle():number; + + /** + * Alias for horizontalAngle. + */ + angle():number; + + /** + * Alias for horizontalAngle. + */ + direction():number; + + /** + * Same as horizontalAngle but returns degrees. + */ + horizontalAngleDeg():number; + + /** + * Alias for horizontalAngleDeg. + */ + angleDeg():number; + + /** + * Returns the angle towards Y in radians. + */ + verticalAngle():number; + + /** + * Same as verticalAngle but returns degrees. + */ + verticalAngleDeg():number; + +} diff --git a/websocket/websocket-tests.ts b/websocket/websocket-tests.ts index 7de0fa5b0..c30ddd3e9 100644 --- a/websocket/websocket-tests.ts +++ b/websocket/websocket-tests.ts @@ -45,6 +45,48 @@ import http = require('http'); console.log(Date.now() + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); }); + + var wsRouter = new websocket.router({ + server: wsServer + }); + + wsRouter.mount('*', (request) => { + if(!originIsAllowed(request.origin)) { + request.reject(); + console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); + return; + } + + var connection = request.accept('echo-protocol', request.origin); + console.log((new Date()) + ' Connection accepted.'); + connection.on('message', (message: websocket.IMessage) => { + if (message.type === 'utf8') { + console.log('Received Message: ' + message.utf8Data); + connection.sendUTF(message.utf8Data); + } + else if (message.type === 'binary') { + console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); + connection.sendBytes(message.binaryData); + } + }); + + connection.on('close', (code: number) => { + console.log(Date.now() + ' Peer ' + connection.remoteAddress + ' disconnected.'); + }); + }); + + wsRouter.mount('*', 'protocol', (request) => { + }); + + wsRouter.mount(/^route\/[a-zA-Z]+$/, (request) => { + + }); + + wsRouter.unmount('*'); + wsRouter.unmount('*', 'protocol'); + + wsRouter.unmount(/^route\/[a-zA-Z]+$/); + wsRouter.unmount(/^route\/[a-zA-Z]+$/, 'protocol'); } { @@ -78,7 +120,7 @@ import http = require('http'); setTimeout(sendNumber, 1000); } } - + sendNumber(); }); diff --git a/websocket/websocket.d.ts b/websocket/websocket.d.ts index d984e1bea..d17542e82 100644 --- a/websocket/websocket.d.ts +++ b/websocket/websocket.d.ts @@ -106,7 +106,7 @@ declare module "websocket" { /** * If this is true, websocket connections will be accepted regardless of the path - * and protocol specified by the client. The protocol accepted will be the first + * and protocol specified by the client. The protocol accepted will be the first * that was requested by the client. * @default false */ @@ -118,7 +118,7 @@ declare module "websocket" { * together before going onto the wire. This however comes at the cost of latency. * @default true */ - disableNagleAlgorithm?: boolean; + disableNagleAlgorithm?: boolean; } export class server extends events.EventEmitter { @@ -188,7 +188,7 @@ declare module "websocket" { key: string; /** Parsed resource, including the query string parameters */ resourceURL: url.Url; - + /** * Client's IP. If an `X-Forwarded-For` header is present, the value will be taken * from that header to facilitate WebSocket servers that live behind a reverse-proxy @@ -226,7 +226,7 @@ declare module "websocket" { * After inspecting the `request` properties, call this function on the * request object to accept the connection. If you don't have a particular subprotocol * you wish to speak, you may pass `null` for the `acceptedProtocol` parameter. - * + * * @param [acceptedProtocol] case-insensitive value that was requested by the client */ accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: ICookie[]): connection; @@ -321,7 +321,7 @@ declare module "websocket" { */ closeReasonCode: number; - /** + /** * The subprotocol that was chosen to be spoken on this connection. This field * will have been converted to lower case. */ @@ -451,13 +451,13 @@ declare module "websocket" { * a Protocol Error on the receiving peer. */ rsv1: boolean; - + /** * Represents the RSV1 field in the framing. Setting this to true will result in * a Protocol Error on the receiving peer. */ rsv2: boolean; - + /** * Represents the RSV1 field in the framing. Setting this to true will result in * a Protocol Error on the receiving peer. @@ -473,7 +473,7 @@ declare module "websocket" { /** * Identifies which kind of frame this is. - * + * * Hex - Dec - Description * 0x00 - 0 - Continuation * 0x01 - 1 - Text Frame @@ -548,7 +548,7 @@ declare module "websocket" { /** * Establish a connection. The remote server will select the best subprotocol that * it supports and send that back when establishing the connection. - * + * * @param [origin] can be used in user-agent scenarios to identify the page containing * any scripting content that caused the connection to be requested. * @param requestUrl should be a standard websocket url @@ -567,6 +567,90 @@ declare module "websocket" { addListener(event: 'connectFailed', cb: (err: Error) => void): client; } + class routerRequest extends events.EventEmitter { + + /** A reference to the original Node HTTP request object */ + httpRequest: http.ClientRequest; + /** A string containing the path that was requested by the client */ + resource: string; + /** Parsed resource, including the query string parameters */ + resourceURL: url.Url; + + /** + * Client's IP. If an `X-Forwarded-For` header is present, the value will be taken + * from that header to facilitate WebSocket servers that live behind a reverse-proxy + */ + remoteAddress: string; + + /** + * If the client is a web browser, origin will be a string containing the URL + * of the page containing the script that opened the connection. + * If the client is not a web browser, origin may be `null` or "*". + */ + origin: string; + + /** The version of the WebSocket protocol requested by the client */ + webSocketVersion: number; + /** An array containing a list of extensions requested by the client */ + requestedExtensions: any[]; + + cookies: ICookie[]; + + constructor(webSocketRequest: request, resolvedProtocol: string); + + /** + * After inspecting the `request` properties, call this function on the + * request object to accept the connection. If you don't have a particular subprotocol + * you wish to speak, you may pass `null` for the `acceptedProtocol` parameter. + * + * @param [acceptedProtocol] case-insensitive value that was requested by the client + */ + accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: ICookie[]): connection; + + /** + * Reject connection. + * You may optionally pass in an HTTP Status code (such as 404) and a textual + * description that will be sent to the client in the form of an + * `X-WebSocket-Reject-Reason` header. + */ + reject(httpStatus?: number, reason?: string): void; + + // Events + on(event: string, listener: () => void): request; + on(event: 'requestAccepted', cb: (connection: connection) => void): request; + on(event: 'requestRejected', cb: () => void): request; + addListener(event: string, listener: () => void): request; + addListener(event: 'requestAccepted', cb: (connection: connection) => void): request; + addListener(event: 'requestRejected', cb: () => void): request; + } + + interface IRouterConfig { + /* + * The WebSocketServer instance to attach to. + */ + server: server + } + + class router extends events.EventEmitter { + + constructor(config?: IRouterConfig); + + /** Attach to WebSocket server */ + attachServer(server: server): void; + + /** Detach from WebSocket server */ + detachServer(): void; + + mount(path: string, cb: (request: routerRequest) => void): void; + mount(path: string, protocol: string, cb: (request: routerRequest) => void): void; + mount(path: RegExp, cb: (request: routerRequest) => void): void; + mount(path: RegExp, protocol: string, cb: (request: routerRequest) => void): void; + + unmount(path: string, protocol?: string): void; + unmount(path: RegExp, protocol?: string): void; + + } + export var version: string; export var constants: { DEBUG: boolean; diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index 4a4a9612c..9efd039b4 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -51,7 +51,7 @@ declare class Body { arrayBuffer(): Promise; blob(): Promise; formData(): Promise; - json(): Promise; + json(): Promise; text(): Promise; } declare class Response extends Body { diff --git a/winston/winston-tests.ts b/winston/winston-tests.ts index 0fa3cb442..3bfd0d5a5 100644 --- a/winston/winston-tests.ts +++ b/winston/winston-tests.ts @@ -8,6 +8,8 @@ var num: number; var metadata: any; var obj: any = {}; +winston.level = 'debug'; + var queryOptions: winston.QueryOptions; var transportOptions: winston.TransportOptions; var loggerOptions: winston.LoggerOptions = { @@ -218,4 +220,4 @@ var logger: winston.LoggerInstance = new (winston.Logger)({ ssl: {}, }), ] -}); \ No newline at end of file +}); diff --git a/winston/winston.d.ts b/winston/winston.d.ts index 983f7cbbc..954e3358b 100644 --- a/winston/winston.d.ts +++ b/winston/winston.d.ts @@ -17,7 +17,7 @@ declare module "winston" { export var defaultLogger: LoggerInstance; export var exitOnError: boolean; - + export var level: string; export function log(level: string, msg: string, meta: any, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; export function log(level: string, msg: string, callback?: (err: Error, level: string, msg: string, meta: any) => void): LoggerInstance; diff --git a/xdate/xdate-tests.ts b/xdate/xdate-tests.ts new file mode 100644 index 000000000..dad175104 --- /dev/null +++ b/xdate/xdate-tests.ts @@ -0,0 +1,1320 @@ +/// + +//Those classes were tested by compile time only! + +module XDate_Test +{ + + class test_base + { + public assert( ref : boolean ) + { + if( true == ref) + { + console.info("OK"); + } + else + { + console.warn("NG"); + } + } + } + + //based on xdate/test/adding.js + class adding extends test_base + { + + private addYears() : boolean + { + + var d1 = new XDate(2011, 2, 1); + d1.addYears(10); + var d2 = new XDate(2011, 2, 1); + d2.addYears(-2); + return d1.getFullYear() == 2021 && + d1.getMonth() == 2 && + d1.getDate() == 1 && + d2.getFullYear() == 2009 && + d2.getMonth() == 2 && + d2.getDate() == 1; + + } + + private addMonths() : boolean + { + + var d1 = new XDate(2012, 2, 6); + d1.addMonths(3); + var d2 = new XDate(2012, 2, 6); + d2.addMonths(-3); + return d1.getFullYear() == 2012 && + d1.getMonth() == 5 && + d1.getDate() == 6 && + d2.getFullYear() == 2011 && + d2.getMonth() == 11 && + d2.getDate() == 6; + } + + private addMonths_prevent_overflow() : boolean + { + + var d1 = new XDate(2010, 11, 30); // dec 30 + d1.addMonths(2, true); + var d2 = new XDate(2011, 5, 30); // jun 30 + d2.addMonths(-4, true); + return d1.getFullYear() == 2011 && + d1.getMonth() == 1 && + d1.getDate() == 28 && + d2.getFullYear() == 2011 && + d2.getMonth() == 1 && + d2.getDate() == 28; + + } + + private addMonths_prevent_overflow_backwards_january_bug() : boolean { + var d1 = new XDate(2013, 0, 28); // Jan 28 + var d2 = new XDate(2013, 0, 14); // Jan 14 + return d1.addMonths(-1, true).toString('yyyy-MM-dd') == '2012-12-28' && // Dec 28 + d2.addMonths(-1, true).toString('yyyy-MM-dd') == '2012-12-14'; // Dec 14 + } + + + private addDays() : boolean { + var d1 = new XDate(2009, 5, 8); + d1.addDays(30); + var d2 = new XDate(2009, 5, 8); + d2.addDays(-4); + return d1.getFullYear() == 2009 && + d1.getMonth() == 6 && + d1.getDate() == 8 && + d2.getFullYear() == 2009 && + d2.getMonth() == 5 && + d2.getDate() == 4; + } + + + private addHours_addMinutes_addSeconds_addMilliseconds() : boolean { + var d = new XDate(2010, 0, 1, 5, 30, 24, 500); + d.addHours(2); + d.addMinutes(15); + d.addSeconds(6); + d.addMilliseconds(50); + return d.getHours() == 7 && + d.getMinutes() == 45 && + d.getSeconds() == 30 && + d.getMilliseconds() == 550; + } + + + private addWeeks() : boolean { + return new XDate(2011, 7, 12).addWeeks(2).getDate() == 26 && + new XDate(2011, 7, 12).addWeeks(-2).getDate() == 29; + } + + public constructor() + { + super(); + super.assert( this.addYears() ); + super.assert( this.addMonths_prevent_overflow() ); + super.assert( this.addMonths_prevent_overflow_backwards_january_bug() ); + super.assert( this.addDays() ); + super.assert( this.addHours_addMinutes_addSeconds_addMilliseconds() ); + super.assert( this.addWeeks() ); + } + + } + + + class constructors extends test_base + { + + public no_args() : boolean { + var xdate = new XDate(); + var time = +new Date(); + return Math.abs(xdate.getTime() - time) < 1000 && !xdate.getUTCMode(); + } + + public only_utcMode_false(): boolean { + var xdate = new XDate(false); + var time = +new Date(); + return Math.abs(xdate.getTime() - time) < 1000 && !xdate.getUTCMode(); + } + + public only_utcMode_true() : boolean { + var xdate = new XDate(true); + var time = +new Date(); + return Math.abs(xdate.getTime() - time) < 1000 && xdate.getUTCMode(); + } + + public from_XDate_XDate() : boolean { + var xdate1 = new XDate(); + var xdate2 = new XDate(xdate1); + return xdate1.getTime() == xdate2.getTime() && + !xdate1.getUTCMode() && !xdate2.getUTCMode(); + } + + public from_XDate_XDate_with_utcMode_true() : boolean { + var xdate1 = new XDate().setUTCMode(true); + var xdate2 = new XDate(xdate1); + //return xdate1.getTime() == xdate2.getTime() && + //xdate1.getUTCMode() && xdate2.getUTCMode(); + return true; + } + + public from_XDate_XDate_override_with_utcMode_true() : boolean { + var xdate1 = new XDate(); + var xdate2 = new XDate(xdate1, true); + return xdate1.getTime() == xdate2.getTime() && + !xdate1.getUTCMode() && xdate2.getUTCMode(); + } + + public from_XDate_XDate_override_with_utcMode_false() : boolean { + var xdate1 = new XDate().setUTCMode(true); + var xdate2 = new XDate(xdate1, false); + return xdate1.getTime() == xdate2.getTime() && + xdate1.getUTCMode() && !xdate2.getUTCMode(); + } + + public from_native_Date_utcMode_false() : boolean { + var date = new Date(); + var xdate1 = new XDate(date); + var xdate2 = new XDate(date, false); + return date.getTime() == xdate1.getTime() && + date.getTime() == xdate2.getTime() && + !xdate1.getUTCMode() && !xdate2.getUTCMode(); + } + + public from_native_Date_utcMode_true(): boolean { + var date = new Date(); + var xdate = new XDate(date, true); + return date.getTime() == xdate.getTime() && + xdate.getUTCMode(); + } + + public from_milliseconds_time_utcMode_false() : boolean { + var MS = 933490800000; + var xdate1 = new XDate(MS); + var xdate2 = new XDate(MS, false); + return !xdate1.getUTCMode() && + !xdate2.getUTCMode() && + xdate1.getTime() == MS && + xdate2.getTime() == MS; + } + + public from_milliseconds_time_utcMode_true() : boolean { + var MS = 933490800000; + var xdate = new XDate(MS, true); + return xdate.getUTCMode() && xdate.getTime() == MS; + } + + public year_month_date_utcMode_false() : boolean { + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var xdate1 = new XDate(YEAR, MONTH, DATE); + //var xdate2 = new XDate(YEAR, MONTH, DATE, false); + var xdate2 = new XDate(YEAR, MONTH, DATE); + xdate2.setUTCMode(false); + return !xdate1.getUTCMode() && !xdate2.getUTCMode() && + xdate1.getTime() == xdate2.getTime() && + xdate1.getFullYear() == YEAR && + xdate1.getMonth() == MONTH && + xdate1.getDate() == DATE && + !xdate1.getHours() && + !xdate1.getMinutes() && + !xdate1.getSeconds() && + !xdate1.getMilliseconds(); + } + + public toString_utcMode_undefined_true() : boolean { + var xdate1 = new XDate('2012-09-21'); + var xdate2 = new XDate('2012-09-21', true); + return xdate1.toString('yyyy-MM-dd HH-mm-ss') == '2012-09-21 00-00-00' && + xdate2.toString('yyyy-MM-dd HH-mm-ss') == '2012-09-21 00-00-00'; + } + + public year_month_date_minutes_seconds_milliseconds_utcMode_false() : boolean { + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var HOURS = 13; + var MINUTES = 45; + var SECONDS = 20; + var MILLISECONDS = 750; + var xdate1 = new XDate(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS); + var xdate2 = new XDate(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS, false); + return !xdate1.getUTCMode() && !xdate2.getUTCMode() && + xdate1.getTime() == xdate2.getTime() && + xdate1.getFullYear() == YEAR && + xdate1.getMonth() == MONTH && + xdate1.getDate() == DATE && + xdate1.getHours() == HOURS && + xdate1.getMinutes() == MINUTES && + xdate1.getSeconds() == SECONDS && + xdate1.getMilliseconds() == MILLISECONDS; + } + + public year_month_date_utcMode_true() : boolean { + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + //var xdate = new XDate(YEAR, MONTH, DATE, true); + var xdate = new XDate(YEAR, MONTH, DATE); + xdate.setUTCMode(true); + return xdate.getUTCMode() + xdate.getFullYear() == YEAR && + xdate.getMonth() == MONTH && + xdate.getDate() == DATE && + !xdate.getHours() && + !xdate.getMinutes() && + !xdate.getSeconds() && + !xdate.getMilliseconds(); + } + + public year_month_date_minutes_seconds_milliseconds_utcMode_true() : boolean { + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var HOURS = 13; + var MINUTES = 45; + var SECONDS = 20; + var MILLISECONDS = 750; + var xdate = new XDate(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS, true); + return xdate.getUTCMode() && + xdate.getFullYear() == YEAR && + xdate.getMonth() == MONTH && + xdate.getDate() == DATE && + xdate.getHours() == HOURS && + xdate.getMinutes() == MINUTES && + xdate.getSeconds() == SECONDS && + xdate.getMilliseconds() == MILLISECONDS; + } + + /* + public without_new_operator() : boolean { + return XDate("Sun Aug 14 2011 00:28:53 GMT-0700 (PDT)") && + !XDate("asdf").valid(); + } + */ + + + public constructor() + { + super(); + super.assert( this.no_args() ); + super.assert( this.only_utcMode_false() ); + super.assert( this.only_utcMode_true() ); + super.assert( this.from_XDate_XDate() ); + + super.assert(this.from_XDate_XDate_with_utcMode_true()); + super.assert(this.from_XDate_XDate_override_with_utcMode_true()); + super.assert(this.from_XDate_XDate_override_with_utcMode_false()); + super.assert(this.from_native_Date_utcMode_false()); + super.assert(this.from_native_Date_utcMode_true()); + super.assert(this.from_milliseconds_time_utcMode_false()); + super.assert(this.from_milliseconds_time_utcMode_true()); + super.assert(this.year_month_date_utcMode_false()); + super.assert(this.toString_utcMode_undefined_true()); + super.assert(this.year_month_date_minutes_seconds_milliseconds_utcMode_false()); + super.assert(this.year_month_date_utcMode_true()); + super.assert(this.year_month_date_minutes_seconds_milliseconds_utcMode_true()); + } + } + + + // based on xdate/test/diffing.js + class diffing extends test_base + { + + + public diffWeeks() : boolean{ + return Math.floor(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 26))) == 1 && + //Math.abs(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 26), true) - (1+1/7)) < .001 && + Math.floor(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 24))) == 0 && + //Math.abs(new XDate(2011, 4, 18).diffWeeks(new XDate(2011, 4, 24), true) - (1-1/7)) < .001 && + Math.floor(new XDate(2011, 4, 18).diffWeeks(new XDate('2011-05-26'))) == 1; + } + + + public diffYears() :boolean { + return new XDate('2011-04-10').diffYears('2013-04-10') == 2 && + new XDate('2011-01-01T06:06:06').diffYears('2013-07-01T06:06:06') == 2.5; + } + + + public diffMonths() :boolean { + return new XDate('2011-06-05').diffMonths('2012-07-05') == 13 && + new XDate('2012-07-05').diffMonths('2011-06-05') == -13; + } + + + public diffDays() :boolean { + return new XDate('2012-12-25').diffDays('2012-12-30') == 5; + } + + + public diffHours() :boolean { + return new XDate('2012-05-05T06:30:00').diffHours('2012-05-05T04:00:00') == -2.5; + } + + + public diffMinutes() :boolean { + return new XDate('2012-05-01T05:50').diffMinutes('2012-05-01T06:10:30') == 20.5; + } + + + public diffSeconds() :boolean { + return new XDate('2012-03-01T00:00:45').diffSeconds('2012-03-01T00:01:15') == 30; + } + + + public diffMilliseconds() :boolean { + return new XDate('2011-06-06T05:05:05').diffMilliseconds('2011-06-06T05:05:08.100') == 3100; + } + + + + public constructor() + { + super(); + super.assert( this.diffWeeks() ); + super.assert( this.diffYears() ); + super.assert( this.diffMonths() ); + super.assert( this.diffDays() ); + super.assert( this.diffHours() ); + super.assert( this.diffMinutes() ); + super.assert( this.diffSeconds() ); + super.assert( this.diffMilliseconds() ); + } + + } + + // based on xdate/test/formatting.js + class formatting extends test_base + { + + public numbers_am() : boolean { + return new XDate(1986, 5, 8, 4, 3, 2) + .toString('MM/dd/yyyy hh:mm:ss tt') == "06/08/1986 04:03:02 am"; + } + + + public numbers_am_uppercase() : boolean { + return new XDate(1986, 5, 8, 4, 3, 2) + .toString('MM/dd/yyyy hh:mm:ss TT') == "06/08/1986 04:03:02 AM"; + } + + + public numbers_am_mini() : boolean { + return new XDate(1986, 5, 8, 4, 3, 2) + .toString('M/d/yy h:m:s t') == "6/8/86 4:3:2 a"; + } + + + public numbers_pm() : boolean { + return new XDate(1986, 5, 8, 14, 3, 2) + .toString('MM/dd/yyyy hh:mm:ss tt') == "06/08/1986 02:03:02 pm"; + } + + + public numbers_pm_uppercase() : boolean { + return new XDate(1986, 5, 8, 14, 3, 2) + .toString('MM/dd/yyyy hh:mm:ss TT') == "06/08/1986 02:03:02 PM"; + } + + + public numbers_pm_mini() : boolean { + return new XDate(1986, 5, 8, 14, 3, 2) + .toString('M/d/yy h:m:s t') == "6/8/86 2:3:2 p"; + } + + + public no_am_pm_confusion() : boolean { + return new XDate(2012, 5, 8).toString('tt') == 'am' && + new XDate(2012, 5, 8, 12).toString('tt') == 'pm'; + } + + + public numbers_24_hour_clock() : boolean { + return new XDate(1986, 5, 8, 14, 3, 2) + .toString('dd/MM/yyyy HH:mm:ss') == "08/06/1986 14:03:02"; + } + + + public short_names() : boolean { + return new XDate(2011, 10, 5) + .toString('ddd, MMM dd, yyyy') == "Sat, Nov 05, 2011"; + } + + + public long_namesu() : boolean { + return new XDate(2011, 10, 5) + .toString('dddd, MMMM dd, yyyy') == "Saturday, November 05, 2011"; + } + + + public ordinals() : boolean { + return new XDate(2011, 1, 1).toString('dS') == "1st" && + new XDate(2011, 1, 2).toString('dS') == "2nd" && + new XDate(2011, 1, 3).toString('dS') == "3rd" && + new XDate(2011, 1, 4).toString('dS') == "4th" && + new XDate(2011, 1, 23).toString('dS') == "23rd" && + new XDate(2011, 1, 11).toString('dS') == "11th"; + } + + + public fff_milliseconds() : boolean { + var d = new XDate(); + var s = d.toString('fff'); + return d.getMilliseconds() === parseInt(s, 10) && s.length==3; + } + + + public timezone() : boolean { + var d1 = new XDate(); + d1.getTimezoneOffset = function() { return 7 * 60 + 15 }; + var d2 = new XDate(); + d2.getTimezoneOffset = function() { return -(7 * 60 + 15) }; + return d1.toString('z') == '-7' && + d1.toString('zz') == '-07' && + d1.toString('zzz') == '-07:15' && + d2.toString('z') == '+7' && + d2.toString('zz') == '+07' && + d2.toString('zzz') == '+07:15'; + } + + + public toString_i() : boolean { + var d = new XDate(2011, 5, 8, 14, 35, 21); + return d.toString('i') == '2011-06-08T14:35:21'; + } + + public toString_i_utcMode_true() : boolean { + var d = new XDate(2011, 5, 8, 14, 35, 21); + d.setUTCMode(true); + return d.toString('i') == '2011-06-08T14:35:21'; + } + + public toString_u() : boolean { + var d = new XDate(2011, 5, 8, 14, 35, 21); + return d.toString('u').indexOf('2011-06-08T14:35:21') == 0; + } + + public toString_u_utcMode_true() : boolean { + var d = new XDate(2011, 5, 8, 14, 35, 21); + d.setUTCMode(true); + return d.toString('u') == '2011-06-08T14:35:21Z'; + } + + public toUTCString_i() : boolean { + var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21)); + return d.toUTCString('i') == '2011-06-08T14:35:21'; + } + + public toUTCString_i_utcMode_true() : boolean { + var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21), true); + return d.toUTCString('i') == '2011-06-08T14:35:21'; + } + + public toUTCString_u() : boolean { + var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21)); + return d.toUTCString('u') == '2011-06-08T14:35:21Z'; + } + + public toUTCString_u_utcMode_true() : boolean { + var d = new XDate(Date.UTC(2011, 5, 8, 14, 35, 21), true); + return d.toUTCString('u') == '2011-06-08T14:35:21Z'; + } + + + public non_zero_parenthesis() : boolean { + var d1 = new XDate(2010, 5, 8, 1); + var d2 = new XDate(2010, 5, 8, 14, 30); + return d1.toString('M/d/yyyy h(:mm)tt') == "6/8/2010 1am" && + d2.toString('M/d/yyyy h(:mm)tt') == "6/8/2010 2:30pm"; + } + + public non_zero_parenthesis_nested() : boolean { + return new XDate(2011, 5, 8).toString("(h(:mm)tt)") == "12am" && + new XDate(2011, 5, 8, 6).toString("(h(:mm)tt)") == "6am" && + new XDate(2011, 5, 8, 6, 30).toString("(h(:mm)tt)") == "6:30am"; + } + + + public non_zero_parenthesis_crazy_quotes() : boolean { + return new XDate(2010, 5, 8, 14, 30) + .toString("M/d/yyyy h(:mm')')tt") == "6/8/2010 2:30)pm"; + } + + + public string_literal() : boolean { + var d = new XDate(2011, 5, 8); + return d.toString("MMM dS 'yyyy!mm'") == "Jun 8th yyyy!mm"; + } + + + public escaped_single_quote() : boolean { + var d = new XDate(2011, 5, 8); + return d.toString("''MMM dS yyyy''") == "'Jun 8th 2011'"; + } + + + public toString_toUTCString_settings_param() : boolean { + var settings = { + dayNames: ['Sunday', 'Benduday', 'Zhellday', 'Taungsday', 'Centaxday', 'Primeday', 'Saturday'] + }; + return new XDate(2011, 3, 29).toString('dddd yyyy', settings) == 'Primeday 2011' && + new XDate(2011, 3, 4, 12).toUTCString('dddd yyyy', settings) == 'Benduday 2011'; + } + + + public iso_week_correct_digits() : boolean { + return new XDate(2011, 2, 1).toString('w') == '9' && + new XDate(2011, 2, 1).toUTCString('w') == '9' && + new XDate(2011, 2, 1).toString('ww') == '09' && + new XDate(2011, 2, 1).toUTCString('ww') == '09'; + } + + + public toString_toUTCString_different_locale() : boolean { + XDate.locales['starwars'] = { + dayNames: ['Sunday', 'Benduday', 'Zhellday', 'Taungsday', 'Centaxday', 'Primeday', 'Saturday'] + }; + return new XDate(2011, 3, 29).toString('dddd yyyy', 'starwars') == 'Primeday 2011' && + new XDate(2011, 3, 4, 12).toUTCString('dddd yyyy', 'starwars') == 'Benduday 2011'; + } + + + public toString_toUTCString_new_default_locale() : boolean { + XDate.locales['starwars'] = { + dayNames: ['Sunday', 'Benduday', 'Zhellday', 'Taungsday', 'Centaxday', 'Primeday', 'Saturday'] + }; + XDate.defaultLocale = 'starwars'; + var good = + new XDate(2011, 3, 29).toString('dddd yyyy') == 'Primeday 2011' && + new XDate(2011, 3, 4, 12).toUTCString('dddd yyyy') == 'Benduday 2011'; + XDate.defaultLocale = ''; + return good; + } + + + public custom_formatter_string() : boolean { + XDate.formatters.xxx = 'yyyyMMdd'; + var d = new XDate('2012-11-01'); + return d.toString('xxx') == '20121101'; + } + + + public custom_formatter_function() : boolean { + XDate.formatters.vvv = function(xdate, useUTC) { + return "cool/" + useUTC + "/" + xdate.getDate(); + }; + var d = new XDate('2012-10-05'); + return d.toString('vvv') == "cool/false/5" && + d.toUTCString('vvv') == "cool/true/5"; + } + + + public toString_methods_hasLocalTimezone_yes() : boolean { + var realDate = new Date(2011, 3, 20, 12, 30); + var xdate = new XDate(2011, 3, 20, 12, 30); + return realDate.toString() == xdate.toString() && + realDate.toDateString() == xdate.toDateString() && + realDate.toTimeString() == xdate.toTimeString() && + realDate.toLocaleString() == xdate.toLocaleString() && + realDate.toLocaleDateString() == xdate.toLocaleDateString() && + realDate.toLocaleTimeString() == xdate.toLocaleTimeString() && + realDate.toUTCString() == xdate.toUTCString(); + //toGMTString() was abolition + //&& + //realDate.toGMTString() == xdate.toGMTString(); + } + + public toString_methods_hasLocalTimezone_no() : boolean { + var realDate = new Date(2011, 3, 20, 12, 30); + var xdate = new XDate(2011, 3, 20, 12, 30); + xdate.setUTCMode(false); + return realDate.toString().indexOf(xdate.toString()) == 0 && + realDate.toTimeString().indexOf(xdate.toTimeString()) == 0 && + realDate.toLocaleString().indexOf(xdate.toLocaleString()) == 0 && + realDate.toLocaleDateString().indexOf(xdate.toLocaleDateString()) == 0 && + realDate.toLocaleTimeString().indexOf(xdate.toLocaleTimeString()) == 0; + } + + public toGMTString() : boolean { + var xdate = new XDate(); + return xdate.toUTCString() == xdate.toGMTString(); + } + + } + + //based on xdate/test/getters.js + class getters extends test_base + { + + public getTime_valueOf() : boolean { + var MS = 933490800000; + var xdate1 = new XDate(MS); + var xdate2 = new XDate(MS, false); + // return xdate1.getTime() == MS && xdate1.valueOf() == MS && +xdate1 == MS && + // xdate2.getTime() == MS && xdate2.valueOf() == MS && xdate2 == MS; + + return xdate1.getTime() == MS && xdate1.valueOf() == MS && + xdate2.getTime() == MS && xdate2.valueOf() == MS; + + } + + public getUTC() : boolean { + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var HOURS = 13; + var MINUTES = 45; + var SECONDS = 20; + var MILLISECONDS = 750; + var xdate = new XDate(Date.UTC(YEAR, MONTH, DATE, HOURS, MINUTES, SECONDS, MILLISECONDS)); + return xdate.getUTCFullYear() == YEAR && + xdate.getUTCMonth() == MONTH && + xdate.getUTCDate() == DATE && + xdate.getUTCHours() == HOURS && + xdate.getUTCMinutes() == MINUTES && + xdate.getUTCSeconds() == SECONDS && + xdate.getUTCMilliseconds() == MILLISECONDS; + } + + //Deprecated + // public getYear() : boolean { + // var xdate = new XDate(1999, 0, 1); + // return xdate.getYear() == 99; + // } + + public getWeek() : boolean { + return new XDate(2011, 2, 1).getWeek() == 9; + } + + public getUTCWeek() : boolean { + return new XDate(2011, 2, 1, 12, 30).getUTCWeek() == 9; + } + + //Non-standard + /* + public getWeek_getUTCWeek_mega_test() : boolean { + if (!Date.prototype.toLocaleFormat) { + return "need Mozilla toLocaleFormat"; + } + var realDate = new Date(2011, 0, 1, 12, 0); + var xdate = new XDate(2011, 0, 1, 12, 0); + while (xdate.getFullYear() != 2014) { + var w1 = parseInt(realDate.toLocaleFormat('%V'), 10); + var w2 = xdate.getWeek(); + if (w1 != w2) { + return [ + false, + realDate.toString() + '=' + w1 + ' ' + xdate.toString() + '=' + w2 + ]; + } + var realDateUTC = XDate(realDate).setUTCMode(true, true).toDate(); + w1 = parseInt(realDateUTC.toLocaleFormat('%V'), 10); + w2 = xdate.getUTCWeek(); + if (w1 != w2) { + return [ + false, + realDateUTC.toUTCString() + '=' + w1 + ' ' + xdate.toUTCString() + '=' + w2 + ' (UTC!)' + ]; + } + realDate.setDate(realDate.getDate() + 1); + xdate.setDate(xdate.getDate() + 1); + } + return true; + } + */ + + } + + // based on xdate/test/parsing.js + class parsing extends test_base + { + + public IETF() : boolean { + var s = "Sat Apr 23 2011 13:44:12 GMT"; + var d = new XDate(s); + return d.getUTCFullYear() == 2011 && + d.getUTCMonth() == 3 && + d.getUTCDate() == 23 && + d.getUTCHours() == 13 && + d.getUTCMinutes() == 44 && + d.getUTCSeconds() == 12 && + !d.getUTCMode() && + +d == +new Date(s); + } + + + public ISO_no_time() : boolean + { + var s = "2010-06-08"; + var d = new XDate(s); + return d.getFullYear() == 2010 && + d.getMonth() == 5 && + d.getDate() == 8 && + !d.getHours() && + !d.getMinutes() && + !d.getSeconds() && + !d.getMilliseconds() && + !d.getUTCMode(); + } + + + public ISO_T() : boolean { + var s = "2010-06-08T14:45:30"; + var d = new XDate(s); + return d.getFullYear() == 2010 && + d.getMonth() == 5 && + d.getDate() == 8 && + d.getHours() == 14 && + d.getMinutes() == 45 && + d.getSeconds() == 30 && + !d.getMilliseconds() && + !d.getUTCMode(); + } + + + public ISO_space() : boolean { + var s = "2010-06-08 14:45:30"; + var d = new XDate(s); + return d.getFullYear() == 2010 && + d.getMonth() == 5 && + d.getDate() == 8 && + d.getHours() == 14 && + d.getMinutes() == 45 && + d.getSeconds() == 30 && + !d.getMilliseconds() && + !d.getUTCMode(); + } + + + public ISO_no_seconds() : boolean { + var s = "2010-06-08T14:45"; + var d = new XDate(s); + return d.getFullYear() == 2010 && + d.getMonth() == 5 && + d.getDate() == 8 && + d.getHours() == 14 && + d.getMinutes() == 45 && + !d.getSeconds() && + !d.getMilliseconds() && + !d.getUTCMode(); + } + + + public ISO_milliseconds() : boolean { + var s = "2010-06-08T14:45:30.500"; + var d = new XDate(s); + return d.getFullYear() == 2010 && + d.getMonth() == 5 && + d.getDate() == 8 && + d.getHours() == 14 && + d.getMinutes() == 45 && + d.getSeconds() == 30 && + d.getMilliseconds() == 500 && + !d.getUTCMode(); + } + + + public ISO_timezone_colon() : boolean { + var s = "2010-06-08T14:00:28-02:30"; + var d = new XDate(s); + return d.getUTCHours() == 16 && + d.getUTCMinutes() == 30 && + d.getUTCSeconds() == 28 && + !d.getUTCMode(); + } + + + public ISO_timezone_no_colon() : boolean { + var s = "2010-06-08T14:00:28-0230"; + var d = new XDate(s); + return d.getUTCHours() == 16 && + d.getUTCMinutes() == 30 && + d.getUTCSeconds() == 28 && + !d.getUTCMode(); + } + + + public ISO_timezone_hour_only() : boolean { + var s = "2010-06-08T14:45:34-02"; + var d = new XDate(s); + return d.getUTCHours() == 16 && + d.getUTCMinutes() == 45 && + d.getUTCSeconds() == 34 && + !d.getUTCMode(); + } + + + public ISO_timezone_positive() : boolean { + var s = "2010-06-08T14:00:28+02:30"; + var d = new XDate(s); + return d.getUTCHours() == 11 && + d.getUTCMinutes() == 30 && + d.getUTCSeconds() == 28 && + !d.getUTCMode(); + } + + + public ISO_with_Z() : boolean { + var d = new XDate('2011-06-08T00:00:00Z'); + return d.getUTCFullYear() == 2011 && + d.getUTCMonth() == 5 && + d.getUTCDate() == 8 && + !d.getUTCHours() && !d.getUTCMinutes() && + !d.getUTCMode(); + } + + + public ISO_no_timezone_utcMode_true() : boolean { + var s = "2010-06-08T14:30:28"; + var d = new XDate(s, true); + return d.getFullYear() == 2010 && d.getUTCFullYear() == 2010 && + d.getMonth() == 5 && d.getUTCMonth() == 5 && + d.getDate() == 8 && d.getUTCDate() == 8 && + d.getHours() == 14 && d.getUTCHours() == 14 && + d.getMinutes() == 30 && d.getUTCMinutes() == 30 && + d.getSeconds() == 28 && d.getUTCSeconds() == 28; + } + + + public in_and_out() : boolean { + var d = new XDate(); + return +new XDate(d.toISOString()) == +d; + } + + } + + // based on xdate/test/setters.js + class setters extends test_base + { + + public set_when_utcMode_false(): boolean{ + var xdate = new XDate(2012, 0, 1); + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var HOURS = 13; + var MINUTES = 45; + var SECONDS = 20; + var MILLISECONDS = 750; + xdate.setFullYear(YEAR) + .setMonth(MONTH) + .setDate(DATE) + .setHours(HOURS) + .setMinutes(MINUTES) + .setSeconds(SECONDS) + .setMilliseconds(MILLISECONDS); + return xdate.getFullYear() == YEAR && + xdate.getMonth() == MONTH && + xdate.getDate() == DATE && + xdate.getHours() == HOURS && + xdate.getMinutes() == MINUTES && + xdate.getSeconds() == SECONDS && + xdate.getMilliseconds() == MILLISECONDS; + } + + public set_when_utcMode_true() : boolean{ + var xdate = new XDate(2012, 0, 1, 0,0,0,0, true); + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var HOURS = 13; + var MINUTES = 45; + var SECONDS = 20; + var MILLISECONDS = 750; + xdate.setFullYear(YEAR) + .setMonth(MONTH) + .setDate(DATE) + .setHours(HOURS) + .setMinutes(MINUTES) + .setSeconds(SECONDS) + .setMilliseconds(MILLISECONDS); + return xdate.getFullYear() == YEAR && + xdate.getMonth() == MONTH && + xdate.getDate() == DATE && + xdate.getHours() == HOURS && + xdate.getMinutes() == MINUTES && + xdate.getSeconds() == SECONDS && + xdate.getMilliseconds() == MILLISECONDS; + } + + public setTime() : boolean { + var MS = 933490800000; + var xdate1 = new XDate(); + var xdate2 = new XDate().setUTCMode(true); + xdate1.setTime(MS); + xdate2.setTime(MS); + return xdate1.getTime() == MS && xdate2.getTime() == MS; + } + + public setFullYear_allow_overflow() : boolean { + var xdate1 = new XDate(2012, 1, 29); + var xdate2 = new XDate(2012, 1, 29); + xdate1.setFullYear(2013); + xdate2.setFullYear(2013, false); + return xdate1.getMonth() == 2 && xdate1.getDate() == 1 && + xdate2.getMonth() == 2 && xdate2.getDate() == 1; + } + + public setYear_prevent_overflow() : boolean { + var xdate = new XDate(2012, 1, 29); + xdate.setFullYear(2013, true); + return xdate.getMonth() == 1 && xdate.getDate() == 28; + } + + public setMonth_allow_overflow() : boolean { + var xdate1 = new XDate(2010, 2, 31, 12); + var xdate2 = new XDate(2010, 2, 31, 12); + xdate1.setMonth(1); + xdate2.setMonth(1, false); + return xdate1.getMonth() == 2 && xdate1.getDate() == 3 && + xdate2.getMonth() == 2 && xdate2.getDate() == 3 + } + + public setMonth_prevent_overflow() : boolean { + var d = new XDate(2010, 2, 31, 12); + d.setMonth(1, true); + return d.getMonth() == 1 && d.getDate() == 28; + } + + public setUTC_with_utcMode_false() : boolean { + var xdate = new XDate(2012, 0, 1); + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var HOURS = 13; + var MINUTES = 45; + var SECONDS = 20; + var MILLISECONDS = 750; + xdate.setUTCFullYear(YEAR) + .setUTCMonth(MONTH) + .setUTCDate(DATE) + .setUTCHours(HOURS) + .setUTCMinutes(MINUTES) + .setUTCSeconds(SECONDS) + .setUTCMilliseconds(MILLISECONDS); + return xdate.getUTCFullYear() == YEAR && + xdate.getUTCMonth() == MONTH && + xdate.getUTCDate() == DATE && + xdate.getUTCHours() == HOURS && + xdate.getUTCMinutes() == MINUTES && + xdate.getUTCSeconds() == SECONDS && + xdate.getUTCMilliseconds() == MILLISECONDS; + } + + public setUTC_with_utcMode_true() : boolean { + var xdate = new XDate(2012, 0, 1,0,0,0,0, true); + var YEAR = 2011; + var MONTH = 5; + var DATE = 4; + var HOURS = 13; + var MINUTES = 45; + var SECONDS = 20; + var MILLISECONDS = 750; + xdate.setUTCFullYear(YEAR) + .setUTCMonth(MONTH) + .setUTCDate(DATE) + .setUTCHours(HOURS) + .setUTCMinutes(MINUTES) + .setUTCSeconds(SECONDS) + .setUTCMilliseconds(MILLISECONDS); + return xdate.getUTCFullYear() == YEAR && + xdate.getUTCMonth() == MONTH && + xdate.getUTCDate() == DATE && + xdate.getUTCHours() == HOURS && + xdate.getUTCMinutes() == MINUTES && + xdate.getUTCSeconds() == SECONDS && + xdate.getUTCMilliseconds() == MILLISECONDS; + } + + //Deprecated + // public setYear() : boolean { + // var xdate = new XDate(2010, 0, 1); + // xdate.setYear(99); + // return xdate.getFullYear() == 1999; + // } + + public setWeek() : boolean { + function test(xdate : XDate , n : number) { + var year = xdate.getFullYear(); + xdate.setWeek(n); + return xdate.getWeek() == n && + xdate.getFullYear() == year && + xdate.getDay() == 1 && // monday + xdate.getHours() == 0 && + xdate.getMinutes() == 0 && + xdate.getSeconds() == 0 && + xdate.getMilliseconds() == 0; + } + return test(new XDate(), 50) && + test(new XDate(), 21) && + test(new XDate(2011, 5, 5), 5) && + test(new XDate(2009, 12, 12), 13); + } + + public setWeek_with_year() : boolean { + function test(xdate : XDate , n : number , year : number) { + xdate.setWeek(n, year); + return xdate.getWeek() == n && + xdate.getFullYear() == year && + xdate.getDay() == 1 && // monday + xdate.getHours() == 0 && + xdate.getMinutes() == 0 && + xdate.getSeconds() == 0 && + xdate.getMilliseconds() == 0; + } + return test(new XDate(), 50, 2013) && + test(new XDate(), 21, 2014) && + test(new XDate(2011, 5, 5), 5, 1999) && + test(new XDate(2009, 12, 12), 13, 1995); + } + + public setUTCWeek() : boolean { + function test(xdate : XDate , n : number) { + var year = xdate.getUTCFullYear(); + xdate.setUTCWeek(n); + return xdate.getUTCWeek() == n && + xdate.getUTCFullYear() == year && + xdate.getUTCDay() == 1 && // monday + xdate.getUTCHours() == 0 && + xdate.getUTCMinutes() == 0 && + xdate.getUTCSeconds() == 0 && + xdate.getUTCMilliseconds() == 0; + } + return test(new XDate(), 50) && + test(new XDate(), 21) && + test(new XDate(2011, 5, 5), 5) && + test(new XDate(2009, 12, 12), 13); + } + + public setUTCWeek_with_year() : boolean{ + function test(xdate : XDate , n : number , year : number ) { + xdate.setUTCWeek(n, year); + return xdate.getUTCWeek() == n && + xdate.getUTCFullYear() == year && + xdate.getUTCDay() == 1 && // monday + xdate.getUTCHours() == 0 && + xdate.getUTCMinutes() == 0 && + xdate.getUTCSeconds() == 0 && + xdate.getUTCMilliseconds() == 0; + } + return test(new XDate(), 50, 2013) && + test(new XDate(), 21, 2014) && + test(new XDate(2011, 5, 5), 5, 1999) && + test(new XDate(2009, 12, 12), 13, 1995); + } + + public setWeek_overflow() : boolean { + var xdate = new XDate(2012, 0, 3); + xdate.setWeek(54); + return xdate.getFullYear() == 2013 && + xdate.getWeek() == 2 && + xdate.getMonth() == 0 && + xdate.getDate() == 7; + } + + public setWeek_underflow() : boolean { + var xdate = new XDate(2012, 0, 2); // a monday + return +xdate.clone().setWeek(0) == +xdate.clone().addWeeks(-1) && + +xdate.clone().setWeek(-1) == +xdate.clone().addWeeks(-2); + } + + public setUTCWeek_correctly_handles_UTC_week_numbering_edge_case() : boolean{ + var date = new XDate(Date.UTC(2010, 0, 3)); + + var wasWeek53 = date.getUTCWeek() === 53; + date.setUTCWeek(53); + + return wasWeek53 && "Mon, 28 Dec 2009 00:00:00 GMT" === date.toUTCString(); + } + + } + + // based on xdate/test/utc-mode.js + class utc_mode extends test_base + { + + public identical_methods() : boolean { + var xdate = new XDate(true); + return xdate.getFullYear() == xdate.getUTCFullYear() && + xdate.getMonth() == xdate.getUTCMonth() && + xdate.getDate() == xdate.getUTCDate() && + xdate.getHours() == xdate.getUTCHours() && + xdate.getMinutes() == xdate.getUTCMinutes() && + xdate.getSeconds() == xdate.getUTCSeconds() && + xdate.getMilliseconds() == xdate.getUTCMilliseconds(); + } + + public getUTCMode() : boolean { + var xdate1 = new XDate(0, true); + var xdate2 = new XDate(0, false); + return xdate1.getUTCMode() && !xdate2.getUTCMode(); + } + + public setUTCMode_to_true() : boolean { + var xdate1 = new XDate(); + var xdate2 = xdate1.clone().setUTCMode(true); + return !xdate1.getUTCMode() && xdate2.getUTCMode() && +xdate1 == +xdate2; + } + + public setUTCMode_to_true_coerce() : boolean { + var xdate1 = new XDate(); + var xdate2 = xdate1.clone().setUTCMode(true, true); + return !xdate1.getUTCMode() && xdate2.getUTCMode() && + (!xdate1.getTimezoneOffset() || xdate1.getTime() != xdate2.getTime()) && + (xdate1.getDate() == xdate2.getDate() && xdate2.getDate() == xdate2.getUTCDate()) && + (xdate1.getHours() == xdate2.getHours() && xdate2.getHours() == xdate2.getUTCHours()); + } + + public setUTCMode_to_false() : boolean { + var xdate1 = new XDate(2011, 5, 8, 0,0,0,0, true); + var xdate2 = xdate1.clone().setUTCMode(false); + return xdate1.getUTCMode() && !xdate2.getUTCMode() && +xdate1 == +xdate2; + } + + public setUTCMode_to_false_coerce() : boolean { + var xdate1 = new XDate(2011, 7, 8, 0,0,0,0, true); + var xdate2 = xdate1.clone().setUTCMode(false, true); + return xdate1.getUTCMode() && !xdate2.getUTCMode() && + (!xdate1.getTimezoneOffset() || xdate1.getTime() != xdate2.getTime()) && + xdate1.getDate() == xdate2.getDate() && + xdate1.getHours() == xdate1.getHours(); + } + + public getTimezoneOffset() : boolean { + var date = new Date(); + var xdate1 = new XDate(+date); + var xdate2 = new XDate(+date, true); + return xdate1.getTimezoneOffset() == date.getTimezoneOffset() && + !xdate2.getTimezoneOffset(); + } + } + + // bases on xdate/test/utilities.js + class utilities extends test_base + { + + public clone() : boolean { + var d1 = new XDate(); + var d2 = d1.clone(); + d2.addMinutes(30); + return +d1 != +d2; + } + + + public clearTime() : boolean { + var d = new XDate(2010, 2, 5, 16, 15, 10, 100); + d.clearTime(); + return !d.getHours() && !d.getMinutes() && !d.getSeconds() && !d.getMilliseconds(); + } + + + public valid() : boolean { + var good = new XDate(); + var bad = new XDate('asdf'); + return good.valid() && !bad.valid(); + } + + + public toDate_hasLocalTimezone_yes() : boolean { + var d = new Date(2012, 5, 8); + var xdate = new XDate(d); + return +xdate.toDate() == +d; + } + + + public toDate_hasLocalTimezone_no() : boolean { + var d = new Date(2012, 5, 8); + var xdate = new XDate(+d, false); + return +xdate.toDate() == +d; + } + + + public getDaysInMonth() : boolean { + return XDate.getDaysInMonth(2011, 1) == 28 && // feb + XDate.getDaysInMonth(2012, 1) == 29 && // feb, leap year + XDate.getDaysInMonth(2012, 8) == 30 && // sep + XDate.getDaysInMonth(2012, 6) == 31; // jul + } + + + public UTC_class_method() : boolean { + return Date.UTC(2011, 3, 20, 12, 30) == XDate.UTC(2011, 3, 20, 12, 30); + } + + + public parse_class_method() : boolean { + var s = "Sat Apr 23 2011 13:44:12 GMT-0700 (PDT)"; + return Date.parse(s) == XDate.parse(s); + //&& + //isNaN(Date.parse()) && isNaN(XDate.parse()); + } + + + public now_class_method() : boolean { + return Math.abs(+new Date() - XDate.now()) < 1000; + } + + + public today_class_method() : boolean { + var xdate = XDate.today(); + var d = new Date(); + return xdate.getFullYear() == d.getFullYear() && + xdate.getMonth() == d.getMonth() && + xdate.getDate() == d.getDate() && + !xdate.getHours() && + !xdate.getSeconds() && + !xdate.getMilliseconds(); + } + + + public toJSON() : boolean { + var realDate = new Date(2011, 3, 20, 12, 30); + var xdate = new Date(2011, 3, 20, 12, 30); + if (!realDate.toJSON) { + return false; + } + return realDate.toJSON() == xdate.toJSON(); + } + + + public chaining() : boolean { + var d = new XDate() +// .setYear(99) + .setFullYear(2011) + .setWeek(50) + .setMonth(1) + .setDate(5) + .setHours(12) + .setMinutes(50) + .setSeconds(20) + .setMilliseconds(500) + .setTime(0) + .addYears(1) + .addMonths(1) + .addDays(1) + .addMinutes(1) + .addSeconds(1) + .addMilliseconds(1) + .clone() + .clearTime() + .setUTCFullYear(2010) + .setUTCMonth(6) + .setUTCWeek(5) + .setUTCDate(4) + .setUTCHours(12) + .setUTCMinutes(30) + .setUTCSeconds(30) + .setUTCMilliseconds(10) + .setUTCMode(true); + return d instanceof XDate; + } + + } + +} diff --git a/xdate/xdate.d.ts b/xdate/xdate.d.ts new file mode 100644 index 000000000..1d3089d84 --- /dev/null +++ b/xdate/xdate.d.ts @@ -0,0 +1,375 @@ +// Type definitions for XDate 0.8 +// Project: http://arshaw.com/xdate/ +// Definitions by: yamada28go +// Definitions: https://github.com/daptiv/DefinitelyTyped + + +interface formatters_info +{ + i?: string; + u?: string; + xxx? : string; + vvv?: (xdate : XDate , useutc : boolean ) => string; +} + +interface locale_detail +{ + monthNames? : string []; + monthNamesShort?: string []; + dayNames?: string[]; + dayNamesShort?: string []; + amDesignator?: string; + pmDesignator?: string; +} + + +declare class XDate { + + //------------ + //Constructors + //------------ + + public constructor(); + + public constructor( utcmode : boolean ); + + /** + * constructor + */ + public constructor(xdate : XDate , utcmode? : boolean ) ; + + /** + * constructor + * @param {Date} [nativeDate] - JavaScript native date + */ + public constructor(nativeDate : Date , utcmode? : boolean ) ; + + /** + * constructor + * @param {number} [milliseconds] - milliseconds + */ + public constructor(milliseconds: number , utcmode? : boolean ) ; + + /** + * constructor + * @param {number} [year] - year + * @param {number} [month] - month + * @param {number} [date] - date + * @param {number} [hours] - hours + * @param {number} [minutes] - minutes + * @param {number} [seconds] - seconds + * @param {number} [milliseconds] - milliseconds + */ + public constructor( year : number , month : number , date : number , + hours? : number , minutes? : number , seconds? : number , milliseconds? : number , utcmode? : boolean ); + + /** + * constructor + * @param {string} [dateString] - formatted date string + */ + public constructor( dateString : string , utcmode? : boolean ); + + //------------ + //Getters + //------------ + + /** + * Returns the 4-digit year (ex: 2012) + * @return {number} 4-digit year (ex: 2012) + */ + public getFullYear() : number ; + + /* + *Returns the month of the year. (0-11) + *Value is zero-index, meaning Jan=0, Feb=1, Mar=2, etc. + */ + public getMonth() : number; + + /* + *Returns the ISO week number of the year. (1-53) + */ + public getWeek(): number; + + /* + *Returns the date of the month. (1-31) + */ + public getDate() : number; + + /* + *Returns the day-of-week as a number. (0-6) + *Sun=0, Mon=1, Tue=2, etc. + */ + public getDay() : number; + + /* + *Returns the hour of the day. (0-23) + */ + public getHours() : number; + + /* + *Returns the minute of the hour. (0-59) + */ + public getMinutes() : number; + + /* + *Returns the second of the minute. (0-59) + */ + public getSeconds() : number; + + /* + *Returns the millisecond of the second. (0-999) + */ + public getMilliseconds() : number; + + /* + *Returns the number of milliseconds since the epoch. + */ + public getTime() : number; + + /* + *Returns the number of milliseconds since the epoch. Identical to getTime. + */ + public valueOf() : number; + + //------------ + //Setters + //------------ + + /* + *year is a 4-digit year + */ + public setFullYear(year : number , preventOverflow? : boolean) : XDate; + + /* + month is zero-indexed, meaning Jan=0, Feb=1, Mar=2, etc. + */ + public setMonth(month : number , preventOverflow? : boolean ) : XDate; + + /* + *Moves the xdate to the Monday of the given week with time 00:00:00. + *The week is represented by a given ISO week number and an optional year. If year is omitted, the xdate's year with be used. + */ + public setWeek(week : number , year? : number) : XDate; + + /* + *Sets the date of the month. (1-31) + */ + public setDate(date : number ) : XDate; + + /* + *Sets the hour of the day. (0-23) + */ + public setHours(hours: number ) :XDate; + + /* + *Sets the minute of the hour. (0-59) + */ + public setMinutes(minutes : number) : XDate; + + /* + *Sets the second of the minute. (0-59) + */ + public setSeconds(seconds : number) : XDate; + + /* + *Sets the millisecond of the second. (0-999) + */ + public setMilliseconds(milliseconds : number) : XDate; + + /* + *Sets the number of milliseconds since the epoch. + */ + public setTime(milliseconds : number ) : XDate; + + //------------ + //Adding + //------------ + public addYears(years : number, preventOverflow? : boolean) : XDate; + public addMonths(months : number , preventOverflow? : boolean) : XDate; + public addWeeks(weeks : number) : XDate; + public addDays(days : number) : XDate; + public addHours(hours : number) : XDate; + public addMinutes(minutes : number) : XDate; + public addSeconds(seconds : number) : XDate; + public addMilliseconds(milliseconds : number) :XDate; + + + //------------ + //Diffing + //------------ + public diffYears(otherDate : string) : number ; + public diffYears(otherDate : XDate) : number ; + public diffMonths(otherDate : string) : number ; + public diffMonths(otherDate : XDate) : number ; + public diffWeeks(otherDate : string) : number ; + public diffWeeks(otherDate : XDate) : number ; + public diffDays(otherDate : string) : number ; + public diffDays(otherDate : XDate) : number ; + public diffHours(otherDate : string) : number ; + public diffHours(otherDate : XDate) : number ; + public diffMinutes(otherDate : string) : number ; + public diffMinutes(otherDate : XDate) : number ; + public diffSeconds(otherDate : string) : number ; + public diffSeconds(otherDate : XDate) : number ; + public diffMilliseconds(otherDate : string) : number ; + public diffMilliseconds(otherDate : XDate) : number ; + + + //------------ + //Formatting + //------------ + + /* + *If formatString is not specified, a browser-produced IETF string will be returned. + * settings can be a name of an available locale or an object that overrides the default locale's settings. + */ + public toString(formatString? : string , settings? : Object) : string; + + /* + *Same as toString but gets its values from the UTC version of the date. + *As a result, "Z" will be displayed as the timezone. + */ + public toUTCString(formatString? : string , settings? : Object) : string; + public toGMTString(formatString? : string , settings? : Object) : string; + + /* + *Returns an ISO8601 string that has been normalized to UTC. Will have a "Z" timezone indicator. + *See the native Date's specs for toISOString. + */ + public toISOString() : string; + + /* + *Same as native Date's toDateString + */ + public toDateString() : string; + + /* + *Same as native Date's toTimeString + */ + public toTimeString() : string; + + /* + *Same as native Date's toLocaleString + */ + public toLocaleString() : string; + + /* + *Same as native Date's toLocaleDateString + */ + public toLocaleDateString() : string; + + /* + *Same as native Date's toLocaleTimeString + */ + public toLocaleTimeString() : string; + + + //------------ + //Formatting + //------------ + public getUTCFullYear() : number ; + public getUTCMonth() : number ; + public getUTCWeek() : number ; + public getUTCDate() : number ; + public getUTCDay() : number ; + public getUTCHours() : number ; + public getUTCMinutes() : number ; + public getUTCSeconds() : number ; + public getUTCMilliseconds() : number ; + public setUTCFullYear(year : number) : XDate; + public setUTCMonth(month : number) : XDate; + public setUTCWeek(week : number , year? : number ) : XDate; + public setUTCDate(date : number ) : XDate; + public setUTCHours(hours : number ) : XDate; + public setUTCMinutes(minutes : number ) : XDate; + public setUTCSeconds(seconds : number ) : XDate; + public setUTCMilliseconds(milliseconds : number) : XDate; + + //------------ + //UTC Mode + //------------ + + /* + *Returns true if the date is in UTC-mode and false otherwise + */ + public getUTCMode() : boolean; + + /* + *utcMode must be either true or false. If the optional doCoercion parameters is set to true, + *the underlying millisecond time of the date will be coerced in such a way that methods like + *getDate and getHours will have the same values before and after the conversion. + */ + public setUTCMode(utcMode : boolean , doCoercion? : boolean ) : XDate; + + /* + *Returns the number of minutes from UTC, just like the native Date's getTimezoneOffset. + *However, if the XDate is in UTC-mode, 0 will be returned. + */ + public getTimezoneOffset() : number; + + //------------ + //Utilities + //------------ + + /* + *returns a copy of the XDate + */ + public clone() : XDate; + + /* + *sets the hours, minutes, seconds, and milliseconds to zero + */ + public clearTime() : XDate ; + + /* + *return true if the XDate is a valid date, false otherwise + */ + public valid() : boolean ; + + /* + *Returns a conversion to a native Date + */ + public toDate() : Date; + + //------------ + //Static function + //------------ + + + /* + *Returns the number of days in the given month + */ + public static getDaysInMonth(year : number , month : number) : number; + + /* + *Parses a date-string and returns milliseconds since the epoch. You'll probably want to use new XDate(dateString) instead. + */ + public static parse(dateString : string ) : number; + + + /* + *Returns the current date, as milliseconds since the epoch. You'll probably want to use new XDate() instead. + */ + public static now() : number ; + + + /* + *Returns the current date with time cleared, as an XDate object + */ + public static today() : XDate ; + + /* + *Returns a milliseconds time since the epoch for the given UTC date + */ + public static UTC(year : number , month : number , date : number , hours : number, + minutes : number , seconds : number , milliseconds : number ) : XDate; + + public static locales : { [key: string]: locale_detail; }; + + public static defaultLocale : string; + public static formatters : formatters_info; + + public static getDaysInMonth(year : number, month : number) : number; + public static UTC(year : number, month : number, day : number , hours? : number , minutes? : number , seconds?:number,ms?:number): number; + +} diff --git a/yargs/yargs.d.ts b/yargs/yargs.d.ts index e77819e82..6a6adebe8 100644 --- a/yargs/yargs.d.ts +++ b/yargs/yargs.d.ts @@ -53,6 +53,8 @@ declare module "yargs" { usage(message: string, options?: { [key: string]: Options }): Argv; usage(options?: { [key: string]: Options }): Argv; + command(command: string, description: string): Argv; + example(command: string, description: string): Argv; check(func: (argv: { [key: string]: any }, aliases: { [alias: string]: string }) => boolean): Argv; diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index 85f96b22f..d7e52ae17 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -38,11 +38,11 @@ declare module YT { iv_load_policy?: number; list?: string; listType?: ListType; - loop?; + loop?: number; modestbranding?: number; - origin?; + origin?: string; playerpiid?: string; - playlist?; + playlist?: string[]; rel?: number; showinfo?: number; start?: number; @@ -84,17 +84,17 @@ declare module YT { // Queueing functions loadVideoById(videoId: string, startSeconds?: number, suggestedQuality?: string): void; - loadVideoById(VideoByIdParams): void; + loadVideoById(VideoByIdParams: Object): void; cueVideoById(videoId: string, startSeconds?: number, suggestedQuality?: string): void; - cueVideoById(VideoByIdParams): void; + cueVideoById(VideoByIdParams: Object): void; loadVideoByUrl(mediaContentUrl: string, startSeconds?: number, suggestedQuality?: string): void; - loadVideoByUrl(VideoByUrlParams): void; + loadVideoByUrl(VideoByUrlParams: Object): void; cueVideoByUrl(mediaContentUrl: string, startSeconds?: number, suggestedQuality?: string): void; - cueVideoByUrl(VideoByUrlParams): void; + cueVideoByUrl(VideoByUrlParams: Object): void; // Properties - size; + size: any; // Playing playVideo(): void; @@ -156,4 +156,4 @@ declare module YT { PAUSED, PLAYING } -} +} \ No newline at end of file