diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 73a873bfaf..7d495dca8f 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,6 +5,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](acc-wizard/acc-wizard.d.ts) [acc-wizard](https://github.com/sathomas/acc-wizard) by [Cyril Schumacher](https://github.com/cyrilschumacher) * [:link:](accounting/accounting.d.ts) [accounting.js](http://josscrowcroft.github.io/accounting.js) by [Sergey Gerasimov](https://github.com/gerich-home) * [:link:](ace/ace.d.ts) [Ace Ajax.org Cloud9 Editor](http://ace.ajax.org) by [Diullei Gomes](https://github.com/Diullei) +* [:link:](acorn/acorn.d.ts) [Acorn](https://github.com/marijnh/acorn) by [RReverser](https://github.com/RReverser) * [:link:](add2home/add2home.d.ts) [add2home](http://cubiq.org/add-to-home-screen) by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw) * [:link:](adm-zip/adm-zip.d.ts) [adm-zip](https://github.com/cthackers/adm-zip) by [John Vilk](https://github.com/jvilk) * [:link:](alertify/alertify.d.ts) [alertify](http://fabien-d.github.io/alertify.js) by [John Jeffery](http://github.com/jjeffery) @@ -12,6 +13,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](amplifyjs/amplifyjs.d.ts) [AmplifyJs](http://amplifyjs.com) by [Jonas Eriksson](https://github.com/joeriks) * [:link:](amqp-rpc/amqp-rpc.d.ts) [amqp-rpc](https://github.com/demchenkoe/node-amqp-rpc) by [Wonshik Kim](https://github.com/wokim) * [:link:](angular-file-upload/angular-file-upload.d.ts) [Angular File Upload](https://github.com/danialfarid/angular-file-upload) by [John Reilly](https://github.com/johnnyreilly) +* [: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) @@ -41,6 +43,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [: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) * [:link:](cordova/cordova.d.ts) [Apache Cordova](http://cordova.apache.org) by [Microsoft Open Technologies Inc.](http://msopentech.com) +* [:link:](cordova-plugin-email-composer/cordova-plugin-email-composer.d.ts) [Apache Cordova Email Composer plugin](https://github.com/katzer/cordova-plugin-email-composer) by [Dave Taylor](http://davetayls.me) * [:link:](polymer/polymer.app-router.d.ts) [app-router](https://github.com/erikringsmuth/app-router) by [Louis Grignon](https://github.com/lgrignon) * [:link:](appframework/appframework.d.ts) [AppFramework](http://app-framework-software.intel.com) by [kyo_ago](https://github.com/kyo-ago) * [:link:](arbiter/Arbiter.d.ts) [Arbiter.js](http://arbiterjs.com) by [Arash Shakery](https://github.com/arash16) @@ -57,6 +60,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](atpl/atpl.d.ts) [atpl](https://github.com/soywiz/atpl.js) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](auth0/auth0.d.ts) [Auth0.js](http://auth0.com) by [Robert McLaws](https://github.com/advancedrei) * [:link:](auth0.widget/auth0.widget.d.ts) [Auth0Widget.js](http://auth0.com) by [Robert McLaws](https://github.com/advancedrei) +* [:link:](auth0.lock/auth0.lock.d.ts) [Auth0Widget.js](http://auth0.com) by [Robert McLaws](https://github.com/advancedrei) +* [:link:](autobahn/autobahn.d.ts) [AutobahnJS](http://autobahn.ws/js) by [Elad Zelingher](https://github.com/darkl) * [:link:](aws-sdk/aws-sdk.d.ts) [aws-sdk](https://github.com/aws/aws-sdk-js) by [midknight41](https://github.com/midknight41) * [:link:](axios/axios.d.ts) [axios](https://github.com/mzabriskie/axios) by [Marcel Buesing](https://github.com/marcelbuesing) * [:link:](node-azure/azure.d.ts) [Azure SDK for Node](https://github.com/WindowsAzure/azure-sdk-for-node) by [Andrew Gaspar](https://github.com/AndrewGaspar), [Anti Veeranna](https://github.com/antiveeranna), [Maxime LUCE](https://github.com/SomaticIT) @@ -83,8 +88,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](bootstrap-notify/bootstrap-notify.d.ts) [bootstrap-notify](https://github.com/Nijikokun/bootstrap-notify) by [Blake Niemyjski](https://github.com/niemyjski) * [:link:](bootstrap.datepicker/bootstrap.datepicker.d.ts) [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) by [Boris Yankov](https://github.com/borisyankov) * [:link:](bootstrap.paginator/bootstrap.paginator.d.ts) [bootstrap.paginator](https://github.com/lyonlai/bootstrap-paginator) by [derikwhittaker](https://github.com/derikwhittaker) -* [:link:](bootstrap.timepicker/bootstrap.timepicker.d.ts) [bootstrap.timepicker](https://github.com/jdewit/bootstrap-timepicker) by [derikwhittaker](https://github.com/derikwhittaker) * [:link:](box2d/box2dweb.d.ts) [bootstrap.timepicker](http://code.google.com/p/box2dweb) by [jbaldwin](https://github.com/jbaldwin) +* [:link:](bootstrap.timepicker/bootstrap.timepicker.d.ts) [bootstrap.timepicker](https://github.com/jdewit/bootstrap-timepicker) by [derikwhittaker](https://github.com/derikwhittaker) * [:link:](breeze/breeze.d.ts) [Breeze 1.5.x](http://www.breezejs.com) by [Boris Yankov](https://github.com/borisyankov), [IdeaBlade](https://github.com/IdeaBlade/Breeze) * [:link:](browser-harness/browser-harness.d.ts) [Browser Harness](https://github.com/scriby/browser-harness) by [Chris Scribner](https://github.com/scriby) * [:link:](browser-sync/browser-sync.d.ts) [browser-sync](http://www.browsersync.io) by [Asana](https://asana.com) @@ -191,7 +196,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](errorhandler/errorhandler.d.ts) [errorhandler](https://github.com/expressjs/errorhandler) by [Santi Albo](https://github.com/santialbo) * [:link:](es6-promise/es6-promise.d.ts) [es6-promise](https://github.com/jakearchibald/ES6-Promise) by [François de Campredon](https://github.com/fdecampredon), [vvakame](https://github.com/vvakame) * [:link:](escape-latex/escape-latex.d.ts) [escape-latex](https://github.com/dangmai/escape-latex) by [Oliver Schneider](https://github.com/olsio) -* [:link:](esprima/esprima.d.ts) [Esprima](http://esprima.org) by [teppeis](https://github.com/teppeis) +* [:link:](esprima/esprima.d.ts) [Esprima](http://esprima.org) by [teppeis](https://github.com/teppeis), [RReverser](https://github.com/RReverser) +* [:link:](estree/estree.d.ts) [ESTree AST specification](https://github.com/estree/estree) by [RReverser](https://github.com/RReverser) * [:link:](event-loop-lag/event-loop-lag.d.ts) [event-loop-lag](https://github.com/pebble/event-loop-lag) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](eventemitter2/eventemitter2.d.ts) [EventEmitter2](https://github.com/asyncly/EventEmitter2) by [ryiwamoto](https://github.com/ryiwamoto) * [:link:](eventemitter3/eventemitter3.d.ts) [EventEmitter3](https://github.com/primus/eventemitter3) by [Yuichi Murata](https://github.com/mrk21) @@ -239,6 +245,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](fs-finder/fs-finder.d.ts) [fs-finder](https://github.com/sakren/node-fs-finder) by [Michael Zabka](https://github.com/misak113) * [:link:](fs-mock/fs-mock.d.ts) [fs-mock](https://github.com/sakren/node-fs-mock) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](ftdomdelegate/ftdomdelegate.d.ts) [ftdomdelegate](https://github.com/ftlabs/ftdomdelegate) by [Christian Holm Nielsen](https://github.com/dotnetnerd) +* [:link:](ftp/ftp.d.ts) [ftp](https://github.com/mscdex/node-ftp) by [Rogier Schouten](https://github.com/rogierschouten) +* [:link:](ftpd/ftpd.d.ts) [ftpd](https://github.com/sstur/nodeftpd) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](fullCalendar/fullCalendar.d.ts) [FullCalendar](http://arshaw.com/fullcalendar) by [Neil Stalker](https://github.com/nestalk) * [:link:](fuse/fuse.d.ts) [Fuse.js](https://github.com/krisk/Fuse) by [Greg Smith](https://github.com/smrq) * [:link:](jquery-galleria/jquery-galleria.d.ts) [galleria.js](https://github.com/aino/galleria) by [Robert Imig](https://github.com/rimig) @@ -299,6 +307,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](hapi/hapi.d.ts) [hapi](http://github.com/spumko/hapi) by [Jason Swearingen](http://github.com/jasonswearingen) * [:link:](hasher/hasher.d.ts) [Hasher.js](https://github.com/millermedeiros/hasher) by [flyfishMT](https://github.com/flyfishMT) * [:link:](hashmap/hashmap.d.ts) [HashMap](https://github.com/flesler/hashmap) by [Rafał Wrzeszcz](http://wrzasq.pl) +* [:link:](he/he.d.ts) [he](https://github.com/mathiasbynens/he) by [Simon Edwards](https://github.com/sedwards2009) * [:link:](Headroom/headroom.d.ts) [headroom.js](http://wicky.nillia.ms/headroom.js) by [Jakub Olek](https://github.com/hakubo) * [:link:](heatmap.js/heatmap.d.ts) [heatmap.js](https://github.com/pa7/heatmap.js) by [Yang Guan](https://github.com/lookuptable) * [:link:](hellojs/hellojs.d.ts) [hello.js](http://adodson.com/hello.js) by [Pavel Zika](https://github.com/PavelPZ) @@ -319,6 +328,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](icheck/icheck.d.ts) [iCheck](http://damirfoy.com/iCheck) by [Dániel Tar](https://github.com/qcz) * [:link:](imagemagick/imagemagick.d.ts) [imagemagick](http://github.com/rsms/node-imagemagick) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](imap/imap.d.ts) [imap](https://www.npmjs.com/package/imap) by [Peter Snider](https://github.com/psnider) +* [:link:](imgur-rest-api/imgur-rest-api.d.ts) [Imgur REST API v3](https://api.imgur.com) by [Luke William Westby](http://github.com/lukewestby) * [:link:](impress/impress.d.ts) [Impress.js](https://github.com/bartaz/impress.js) by [Boris Yankov](https://github.com/borisyankov) * [:link:](inflection/inflection.d.ts) [inflection](https://github.com/dreamerslab/node.inflection) by [Shogo Iwano](https://github.com/shiwano) * [:link:](ini/ini.d.ts) [ini](https://github.com/isaacs/ini) by [Marcin Porębski](https://github.com/marcinporebski) @@ -357,7 +367,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jquery.contextMenu/jquery.contextMenu.d.ts) [jQuery contextMenu](http://medialize.github.com/jQuery-contextMenu) by [Natan Vivo](https://github.com/nvivo) * [:link:](jquery.cookie/jquery.cookie.d.ts) [jQuery Cookie Plugin](https://github.com/carhartl/jquery-cookie) by [Roy Goode](https://github.com/RoyGoode) * [:link:](jquery.cycle2/jquery.cycle2.d.ts) [jQuery Cycle2 version (build 20140216)](http://jquery.malsup.com/cycle2) by [Donny Nadolny](https://github.com/dnadolny) -* [:link:](jquery.dataTables/jquery.dataTables.d.ts) [JQuery DataTables](http://www.datatables.net) by [Armin Sander](https://github.com/pragmatrix) +* [:link:](jquery.dataTables/jquery.dataTables.d.ts) [JQuery DataTables](http://www.datatables.net) by [Kiarash Ghiaseddin](https://github.com/Silver-Connection/DefinitelyTyped), [Omid Rad](https://github.com/omidkrad), [Armin Sander](https://github.com/pragmatrix) * [:link:](jquery.fileupload/jquery.fileupload.d.ts) [jQuery File Upload Plugin](https://github.com/blueimp/jQuery-File-Upload) by [Rob Alarcon](https://github.com/rob-alarcon) * [:link:](jquery.joyride/jquery.joyride.d.ts) [jQuery JoyRide Plugin](https://github.com/zurb/joyride) by [Vincent Bortone](https://github.com/vbortone) * [:link:](jqgrid/jqgrid.d.ts) [jQuery jqgrid Plugin](https://github.com/tonytomov/jqGrid) by [Lokesh Peta](https://github.com/lokeshpeta) @@ -376,6 +386,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jquery.ui.datetimepicker/jquery.ui.datetimepicker.d.ts) [jQuery UI DateTimePicker](http://trentrichardson.com/examples/timepicker) by [dougajmcdonald](https://github.com/dougajmcdonald) * [:link:](jquery.ui.layout/jquery.ui.layout.d.ts) [jQuery UI Layout Plug-in](http://layout.jquery-dev.net) by [Steve Fenton](https://github.com/Steve-Fenton) * [:link:](jquery.timepicker/jquery.timepicker.d.ts) [jQuery UI Timepicker](http://fgelinas.com/code/timepicker) by [Anwar Javed](https://github.com/anwarjaved) +* [:link:](jquery-fullscreen/jquery-fullscreen.d.ts) [jquery-fullscreen](https://github.com/kayahr/jquery-fullscreen-plugin) by [Bruno Grieder](https://github.com/bgrieder) * [:link:](jquery-handsontable/jquery-handsontable.d.ts) [jquery-handsontable](http://handsontable.com) by [Ted John](https://github.com/intelorca) * [:link:](jquery.menuaim/jquery.menuaim.d.ts) [jQuery-menu-aim](https://github.com/kamens/jQuery-menu-aim) by [Robert Fonseca-Ensor](http://www.robfe.com) * [:link:](jquery.pjax/jquery.pjax.d.ts) [jquery-pjax](https://github.com/defunkt/jquery-pjax) by [Junle Li](https://github.com/lijunle) @@ -449,6 +460,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](keymaster/keymaster.d.ts) [keymaster](https://github.com/madrobby/keymaster) by [Martin W. Kirst](https://github.com/nitram509) * [:link:](keypress/keypress.d.ts) [Keypress](https://github.com/dmauro/Keypress) by [Roger Chen](https://github.com/rcchen) * [:link:](kineticjs/kineticjs.d.ts) [KineticJS](http://kineticjs.com) by [Basarat Ali Syed](http://www.github.com/basarat), [Ralph de Ruijter](http://www.superdopey.nl/techblog) +* [:link:](knex/knex.d.ts) [Knex.js](https://github.com/tgriesser/knex) by [Qubo](https://github.com/tkQubo) * [:link:](knockback/knockback.d.ts) [Knockback.js](http://kmalakoff.github.io/knockback) by [Boris Yankov](https://github.com/borisyankov) * [:link:](knockout/knockout.d.ts) [Knockout](http://knockoutjs.com) by [Boris Yankov](https://github.com/borisyankov), [Igor Oleinikov](https://github.com/Igorbek), [Clément Bourgeois](https://github.com/moonpyk) * [:link:](knockout.deferred.updates/knockout.deferred.updates.d.ts) [Knockout Deferred Updates](https://github.com/mbest/knockout-deferred-updates) by [Sebastián Galiano](https://github.com/sgaliano) @@ -488,6 +500,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](log4javascript/log4javascript.d.ts) [log4javascript](http://log4javascript.org) by [Markus Wagner](https://github.com/Ritzlgrmft) * [:link:](log4js/log4js.d.ts) [log4js](https://github.com/nomiddlename/log4js-node) by [Kentaro Okuno](http://github.com/armorik83) * [:link:](logg/logg.d.ts) [logg](https://github.com/dpup/node-logg) by [Bret Little](https://github.com/blittle) +* [:link:](loggly/loggly.d.ts) [loggly](https://github.com/nodejitsu/node-loggly) by [Ray Martone](https://github.com/rmartone) * [:link:](logrotate-stream/logrotate-stream.d.ts) [logrotate-stream](https://github.com/dstokes/logrotate-stream) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](lolex/lolex.d.ts) [lolex](https://github.com/sinonjs/lolex) by [Wim Looman](https://github.com/Nemo157) * [:link:](long/long.d.ts) [Long.js](https://github.com/dcodeIO/Long.js) by [Toshihide Hara](https://github.com/kerug) @@ -585,8 +598,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](xml2js/xml2js.d.ts) [node-xml2js](https://github.com/Leonidas-from-XIV/node-xml2js) by [Michel Salib](https://github.com/michelsalib), [Jason McNeil](https://github.com/jasonrm) * [:link:](node/node.d.ts) [Node.js](http://nodejs.org) by [Microsoft TypeScript](http://typescriptlang.org), [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) * [:link:](restify/restify.d.ts) [node.js REST framework](https://github.com/mcavage/node-restify) by [Bret Little](https://github.com/blittle) -* [:link:](acl/acl-mongodbBackend.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) * [:link:](acl/acl.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) +* [:link:](acl/acl-mongodbBackend.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) * [:link:](acl/acl-redisBackend.d.ts) [node_acl](https://github.com/optimalbits/node_acl) by [Qubo](https://github.com/tkQubo) * [:link:](mdns/mdns.d.ts) [node_mdns](https://github.com/agnat/node_mdns) by [Stefan Steinhart](https://github.com/reppners) * [:link:](node_redis/node_redis.d.ts) [node_redis](https://github.com/mranney/node_redis) by [Boris Yankov](https://github.com/borisyankov) @@ -597,16 +610,18 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](nopt/nopt.d.ts) [nopt](https://github.com/npm/nopt) by [jbondc](https://github.com/jbondc) * [:link:](notifyjs/notifyjs.d.ts) [notify.js](https://github.com/alexgibson/notify.js) by [soundTricker](https://github.com/soundTricker) * [:link:](notify/notify.d.ts) [Notify.js](https://github.com/jpillora/notifyjs) by [Xiaohan Zhang](https://github.com/hellochar) -* [:link:](nouislider/nouislider.d.ts) [nouislider](https://github.com/leongersen/noUiSlider) by [Corey Jepperson](https://github.com/acoreyj) * [:link:](wnumb/wnumb.d.ts) [nouislider](https://github.com/leongersen/wnumb) by [Corey Jepperson](https://github.com/acoreyj) +* [:link:](nouislider/nouislider.d.ts) [nouislider](https://github.com/leongersen/noUiSlider) by [Corey Jepperson](https://github.com/acoreyj) * [:link:](noVNC/noVNC.d.ts) [noVNC](https://github.com/kanaka/noVNC) by [Ken Smith](https://github.com/smithkl42) * [:link:](npm/npm.d.ts) [npm](https://github.com/npm/npm) by [Maxime LUCE](https://github.com/SomaticIT) * [:link:](nprogress/NProgress.d.ts) [NProgress](https://github.com/rstacruz/nprogress) by [Judah Gabriel Himango](http://debuggerdotbreak.wordpress.com) * [:link:](numeraljs/numeraljs.d.ts) [Numeral.js](https://github.com/adamwdraper/Numeral-js) by [Vincent Bortone](https://github.com/vbortone) * [:link:](object-hash/object-hash.d.ts) [object-hash](https://github.com/puleos/object-hash) by [Michael Zabka](https://github.com/misak113) -* [:link:](object-path/object-path.d.ts) [objectPath](https://github.com/mariocasciaro/object-path) by [Paulo Cesar](https://github.com/pocesar) +* [:link:](object-path/object-path.d.ts) [objectPath v0.9.x](https://github.com/mariocasciaro/object-path) by [Paulo Cesar](https://github.com/pocesar) * [:link:](oboe/oboe.d.ts) [oboe](https://github.com/jimhigson/oboe.js) by [Jared Klopper](https://github.com/optical) * [:link:](oclazyload/oclazyload.d.ts) [oc.LazyLoad](https://github.com/ocombe/ocLazyLoad) by [Roland Zwaga](https://github.com/rolandzwaga) +* [:link:](on-finished/on-finished.d.ts) [on-finished](https://github.com/jshttp/on-finished) by [Honza Dvorsky](http://github.com/czechboy0) +* [:link:](onsenui/onsenui.d.ts) [Onsen UI](http://onsen.io) by [Fran Dios](https://github.com/frankdiox) * [:link:](open/open.d.ts) [open](https://github.com/jjrdn/node-open) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](openlayers/openlayers.d.ts) [OpenLayers.js](https://github.com/openlayers/openlayers) by [Ilya Bolkhovsky](https://github.com/bolhovsky) * [:link:](opn/opn.d.ts) [opn](https://github.com/sindresorhus/opn) by [Shinnosuke Watanabe](https://github.com/shinnn) @@ -631,6 +646,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](phantom/phantom.d.ts) [PhantomJS bridge for NodeJS](https://github.com/sgentle/phantomjs-node) by [horiuchi](https://github.com/horiuchi) * [:link:](phantomjs/phantomjs.d.ts) [PhantomJS v1.9.0 API](https://github.com/ariya/phantomjs/wiki/API-Reference) by [Jed Hunsaker](https://github.com/jedhunsaker), [Mike Keesey](https://github.com/keesey) * [:link:](phonegap/phonegap.d.ts) [PhoneGap](http://phonegap.com) by [Boris Yankov](https://github.com/borisyankov), [Dick van den Brink](https://github.com/DickvdBrink) +* [:link:](photoswipe/photoswipe.d.ts) [PhotoSwipe](http://photoswipe.com) by [Xiaohan Zhang](https://github.com/hellochar) * [:link:](physijs/physijs.d.ts) [Physijs](http://chandlerprall.github.io/Physijs) by [Satoru Kimura](https://github.com/gyohk) * [:link:](pickadate/pickadate.d.ts) [pickadate.js](https://github.com/amsul/pickadate.js) by [Adi Dahiya](https://github.com/adidahiya) * [:link:](pixi/pixi.d.ts) [PIXI](https://github.com/GoodBoyDigital/pixi.js) by [xperiments](http://github.com/xperiments) @@ -641,8 +657,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](podcast/podcast.d.ts) [podcast](http://github.com/maxnowack/node-podcast) by [Niklas Mollenhauer](https://github.com/nikeee) * [:link:](poly2tri/poly2tri.d.ts) [poly2tri](http://github.com/r3mi/poly2tri.js) by [Elemar Junior](https://github.com/elemarjr) * [:link:](polymer/polymer.d.ts) [polymer](https://github.com/polymer) by [Louis Grignon](https://github.com/lgrignon) +* [:link:](polymer/polymer.paper-dialog.d.ts) [polymer's paper-dialog](https://github.com/Polymer/paper-dialog) by [Louis Grignon](https://github.com/lgrignon) +* [:link:](polymer/polymer.core-overlay.d.ts) [polymer's paper-toast](https://github.com/Polymer/core-selector) by [Louis Grignon](https://github.com/lgrignon) * [:link:](polymer/polymer.paper-toast.d.ts) [polymer's paper-toast](https://github.com/Polymer/paper-toast) by [Louis Grignon](https://github.com/lgrignon) * [:link:](polymer/polymer.core-drawer-panel.d.ts) [polymer's paper-toast](https://github.com/Polymer/core-drawer-panel) by [Louis Grignon](https://github.com/lgrignon) +* [:link:](polymer/polymer.core-selector.d.ts) [polymer's paper-toast](https://github.com/Polymer/core-selector) by [Louis Grignon](https://github.com/lgrignon) * [:link:](popcorn/popcorn.d.ts) [Popcorn](https://github.com/mozilla/popcorn-js) by [grapswiz](https://github.com/grapswiz) * [:link:](pouchDB/pouch.d.ts) [Pouch](http://pouchdb.com) by [Bill Sears](https://github.com/MrBigDog2U) * [:link:](power-assert/power-assert.d.ts) [power-assert](https://github.com/twada/power-assert) by [vvakame](https://github.com/vvakame) @@ -717,6 +736,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](semver/semver.d.ts) [semver](https://github.com/isaacs/node-semver) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](sendgrid/sendgrid.d.ts) [sendgrid](https://github.com/sendgrid/sendgrid-nodejs) by [Maxime LUCE](https://github.com/SomaticIT) * [:link:](sequelize/sequelize.d.ts) [Sequelize 2.0.0 dev13](http://sequelizejs.com) by [samuelneff](https://github.com/samuelneff), [Peter Harris](https://github.com/codeanimal) +* [:link:](on-headers/on-headers.d.ts) [serve-favicon](https://github.com/jshttp/on-headers) by [John Jeffery](https://github.com/jjeffery) * [:link:](serve-favicon/serve-favicon.d.ts) [serve-favicon](https://github.com/expressjs/serve-favicon) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](serve-static/serve-static.d.ts) [serve-static](https://github.com/expressjs/serve-static) by [Uros Smolnik](https://github.com/urossmolnik) * [:link:](sharedworker/SharedWorker.d.ts) [SharedWorker](http://www.w3.org/TR/workers) by [Toshiya Nakakura](https://github.com/nakakura) @@ -735,6 +755,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [: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) +* [:link:](slickgrid/slick.autotooltips.d.ts) [SlickGrid AutoToolTips Plugin](https://github.com/mleibman/SlickGrid) by [Ryo Iwamoto](https://github.com/ryiwamoto) * [:link:](slickgrid/slick.headerbuttons.d.ts) [SlickGrid HeaderButtons Plugin](https://github.com/mleibman/SlickGrid) by [Derek Cicerone](https://github.com/derekcicerone) * [:link:](slickgrid/slick.rowselectionmodel.d.ts) [SlickGrid RowSelectionModel Plugin](https://github.com/mleibman/SlickGrid) by [Derek Cicerone](https://github.com/derekcicerone) * [:link:](smoothie/smoothie.d.ts) [Smoothie Charts](https://github.com/joewalnes/smoothie) by [Drew Noakes](https://drewnoakes.com), [Mike H. Hawley](https://github.com/mikehhawley) @@ -753,6 +774,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](sprintf/sprintf.d.ts) [sprintff](https://github.com/maritz/node-sprintff) by [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](sharepoint/SharePoint.d.ts) [sptypescript](http://sptypescript.codeplex.com) by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru), [Andrey Markeev](http://markeev.com) * [:link:](sqlite3/sqlite3.d.ts) [sqlite3](https://github.com/mapbox/node-sqlite3) by [Nick Malaguti](https://github.com/nmalaguti) +* [:link:](squirejs/squirejs.d.ts) [Squire](https://github.com/iammerrick/Squire.js) by [Bradley Ayers](https://github.com/bradleyayers) * [:link:](stack-mapper/stack-mapper.d.ts) [stack-mapper](https://github.com/thlorenz/stack-mapper) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](stampit/stampit.d.ts) [stampit](https://github.com/ericelliott/stampit) by [Vasyl Boroviak](https://github.com/koresar) * [:link:](stats/stats.d.ts) [Stats.js r12](http://github.com/mrdoob/stats.js) by [Gregory Dalton](https://github.com/gregolai) @@ -774,6 +796,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](swig/swig.d.ts) [swig](http://github.com/paularmstrong/swig) by [Peter Harris](https://github.com/CodeAnimal), [Carlos Ballesteros Velasco](https://github.com/soywiz) * [:link:](swiper/swiper.d.ts) [Swiper](https://github.com/nolimits4web/Swiper) by [Sebastián Galiano](https://github.com/sgaliano) * [:link:](swipeview/swipeview.d.ts) [SwipeView](http://cubiq.org/swipeview) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](switchery/switchery.d.ts) [switchery](https://github.com/abpetkov/switchery) by [Bruno Grieder](https://github.com/bgrieder) * [:link:](swiz/swiz.d.ts) [swiz](https://github.com/racker/node-swiz) by [Jeff Goddard](https://github.com/jedigo) * [:link:](tape/tape.d.ts) [tape](https://github.com/substack/tape) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](tar/tar.d.ts) [tar](https://github.com/npm/node-tar) by [Maxime LUCE](https://github.com/SomaticIT) @@ -803,7 +826,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](timezonecomplete/timezonecomplete.d.ts) [timezonecomplete](https://github.com/SpiritIT/timezonecomplete) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](tv4/tv4.d.ts) [Tiny Validator tv4](https://github.com/geraintluff/tv4) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](tinycolor/tinycolor.d.ts) [tinycolor](https://github.com/bgrins/TinyColor) by [Mordechai Zuber](https://github.com/M-Zuber) -* [:link:](titanium/titanium.d.ts) [Titanium Movile 3.1.3.GA](http://www.appcelerator.com) by [Airam Rguez](https://github.com/airamrguez) +* [:link:](titanium/titanium.d.ts) [Titanium Mobile](http://www.appcelerator.com) by [Craig Younkins](https://github.com/cyounkins) * [:link:](tmp/tmp.d.ts) [tmp](https://www.npmjs.com/package/tmp) by [Jared Klopper](https://github.com/optical) * [:link:](toastr/toastr.d.ts) [Toastr](https://github.com/CodeSeven/toastr) by [Boris Yankov](https://github.com/borisyankov) * [:link:](sencha_touch/SenchaTouch.d.ts) [Touch](http://www.sencha.com/products/touch) by [Brian Kotek](https://github.com/brian428) @@ -818,6 +841,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [: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:](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) * [:link:](typescript/typescript.d.ts) [TypeScript API](http://www.typescriptlang.org) by [Microsoft TypeScript](http://typescriptlang.org) +* [:link:](typescript-deferred/typescript-deferred.d.ts) [typescript-deferred](https://github.com/DirtyHairy/typescript-deferred) by [Christian Speckner](https://github.com/DirtyHairy) * [:link:](typescript-services/typescriptServices.d.ts) [TypeScript-Services](https://www.npmjs.org/package/typescript-services) by [Basarat Ali Syed](http://github.com/basarat) * [:link:](unity-webapi/unity-webapi.d.ts) [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) by [John Vrbanac](jhttps://github.com/jmvrbanac) * [:link:](underscore/underscore.d.ts) [Underscore](http://underscorejs.org) by [Boris Yankov](https://github.com/borisyankov), [Josh Baldwin](https://github.com/jbaldwin) @@ -834,6 +858,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](validator/validator.d.ts) [validator.js](https://github.com/chriso/validator.js) by [tgfjt](https://github.com/tgfjt) * [: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:](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) @@ -847,12 +872,14 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](webmidi/webmidi.d.ts) [Web MIDI API](http://www.w3.org/TR/webmidi) by [Toshiya Nakakura](https://github.com/nakakura) * [:link:](webspeechapi/webspeechapi.d.ts) [Web Speech API](https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html) by [SaschaNaz](https://github.com/saschanaz) * [:link:](webcola/webcola.d.ts) [webcola](https://github.com/tgdwyer/WebCola) by [Qinfeng Chen](https://github.com/qinfchen) +* [:link:](webcomponents.js/webcomponents.js.d.ts) [webcomponents.js](https://github.com/webcomponents/webcomponentsjs) by [Adi Dahiya](https://github.com/adidahiya) * [:link:](webcrypto/WebCrypto.d.ts) [WebCrypto](http://www.w3.org/TR/WebCryptoAPI) by [Lucas Dixon](https://github.com/iislucas) * [:link:](webix/webix.d.ts) [Webix UI](http://webix.com) by [Maksim Kozhukh](http://github.com/mkozhukh) * [:link:](webrtc/MediaStream.d.ts) [WebRTC](http://dev.w3.org/2011/webrtc) by [Ken Smith](https://github.com/smithkl42) * [:link:](websocket/websocket.d.ts) [websocket](https://github.com/Worlize/WebSocket-Node) by [Paul Loyd](https://github.com/loyd) * [:link:](when/when.d.ts) [When](https://github.com/cujojs/when) by [Derek Cicerone](https://github.com/derekcicerone), [Wim Looman](https://github.com/Nemo157) * [:link:](which/which.d.ts) [which](https://github.com/isaacs/node-which) by [vvakame](https://github.com/vvakame) +* [:link:](jquery.window/jquery.window.d.ts) [Window plugin for jQuery](http://fstoke.me/jquery/window) by [Ryan Graham](https://github.com/ryan-codingintrigue) * [:link:](windows-service/windows-service.d.ts) [windows-service](https://bitbucket.org/stephenwvickers/node-windows-service) by [Rogier Schouten](https://github.com/rogierschouten) * [:link:](winjs/winjs.d.ts) [WinJS](http://try.buildwinjs.com) by [TypeScript samples](https://www.typescriptlang.org), [Adam Hewitt](https://github.com/adamhewitt627), [Craig Treasure](https://github.com/craigktreasure), [Jeff Fisher](https://github.com/xirzec) * [:link:](winrt/winrt.d.ts) [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) by [TypeScript samples](https://www.typescriptlang.org) @@ -866,6 +893,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](xpath/xpath.d.ts) [xpath](https://github.com/goto100/xpath) by [Andrew Bradley](https://github.com/cspotcode) * [:link:](xregexp/xregexp.d.ts) [XRegExp](http://xregexp.com) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](xsockets/XSockets.d.ts) [XSockets.NET](http://xsockets.net) by [Jeffery Grajkowski](https://github.com/pushplay) +* [:link:](yamljs/yamljs.d.ts) [yamljs](https://github.com/jeremyfa/yaml.js) by [Tim Jonischkat](http://www.tim-jonischkat.de) * [:link:](yargs/yargs.d.ts) [yargs](https://github.com/chevex/yargs) by [Martin Poelstra](https://github.com/poelstra) * [:link:](yeoman-generator/yeoman-generator.d.ts) [yeoman-generator](https://github.com/yeoman/generator) by [Kentaro Okuno](http://github.com/armorik83) * [:link:](yosay/yosay.d.ts) [yosay](https://github.com/yeoman/yosay) by [Kentaro Okuno](http://github.com/armorik83) diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts new file mode 100644 index 0000000000..1c5cf27bae --- /dev/null +++ b/acorn/acorn-tests.ts @@ -0,0 +1,30 @@ +/// +/// + +import acorn = require('acorn'); + +var token: acorn.Token; +var tokens: acorn.Token[]; +var comment: acorn.Comment; +var comments: acorn.Comment[]; +var program: ESTree.Program; +var any: any; +var string: string; + +// acorn +string = acorn.version; +program = acorn.parse('code'); +program = acorn.parse('code', {range: true, onToken: tokens, onComment: comments}); +program = acorn.parse('code', { + ranges: true, + onToken: (token) => tokens.push(token), + onComment: (isBlock, text, start, end) => { } +}); + +// Token +token = tokens[0]; +string = token.type.label; +any = token.value; + +// Comment +string = comment.value; diff --git a/acorn/acorn.d.ts b/acorn/acorn.d.ts new file mode 100644 index 0000000000..eaba47e3b6 --- /dev/null +++ b/acorn/acorn.d.ts @@ -0,0 +1,67 @@ +// Type definitions for Acorn v1.0.1 +// Project: https://github.com/marijnh/acorn +// Definitions by: RReverser +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module acorn { + var version: string; + function parse(input: string, options?: Options): ESTree.Program; + function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression; + var defaultOptions: Options; + + interface TokenType { + label: string; + keyword: string; + beforeExpr: boolean; + startsExpr: boolean; + isLoop: boolean; + isAssign: boolean; + prefix: boolean; + postfix: boolean; + binop: number; + updateContext: (prevType: TokenType) => any; + } + + interface AbstractToken { + start: number; + end: number; + loc: ESTree.SourceLocation; + range: [number, number]; + } + + interface Token extends AbstractToken { + type: TokenType; + value: any; + } + + interface Comment extends AbstractToken { + type: string; + value: string; + } + + interface Options { + ecmaVersion?: number; + sourceType?: string; + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any; + allowReserved?: boolean; + allowReturnOutsideFunction?: boolean; + allowImportExportEverywhere?: boolean; + allowHashBang?: boolean; + locations?: boolean; + onToken?: ((token: Token) => any) | Token[]; + onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[]; + ranges?: boolean; + program?: ESTree.Program; + sourceFile?: string; + directSourceFile?: string; + preserveParens?: boolean; + plugins?: { [name: string]: Function; }; + } +} + +declare module "acorn" { + export = acorn +} diff --git a/angular-growl-v2/angular-growl-v2-test.ts b/angular-growl-v2/angular-growl-v2-test.ts new file mode 100644 index 0000000000..c9297932e5 --- /dev/null +++ b/angular-growl-v2/angular-growl-v2-test.ts @@ -0,0 +1,53 @@ +/// + +var app = angular.module("ag", ["pascalprecht.translate", "$httpProvider"]); + +app.config((growlProvider:angular.growl.IGrowlProvider, $httpProvider:angular.IHttpProvider) => { + var ttl:angular.growl.IGrowlTTLConfig = { + success: 5000, + error: 4000 + }; + + growlProvider.globalTimeToLive(ttl); + growlProvider.globalTimeToLive(5000); + growlProvider.globalDisableCloseButton(true); + growlProvider.globalDisableIcons(true); + growlProvider.globalReversedOrder(false); + growlProvider.globalDisableCountDown(true); + growlProvider.messageVariableKey("someKey"); + growlProvider.globalInlineMessages(false); + growlProvider.globalPosition("top-center"); + growlProvider.messagesKey("someKey"); + growlProvider.messageTextKey("someKey"); + growlProvider.messageTitleKey("someKey"); + growlProvider.messageSeverityKey("someKey"); + growlProvider.onlyUniqueMessages(false); + + $httpProvider.interceptors.push(growlProvider.serverMessagesInterceptor); +}); + +app.controller("Ctrl", ($scope:angular.IScope, growl:angular.growl.IGrowlService) => { + var config:angular.growl.IGrowlMessageConfig = { + ttl: 5000, + disableCountDown: true, + disableCloseButton: true + }; + + var message = "Some message"; + + growl.warning(message); + growl.warning(message, config); + growl.error(message); + growl.error(message, config); + growl.info(message); + growl.info(message, config); + growl.success(message); + growl.success(message, config); + growl.general(message); + growl.general(message, config); + growl.general(message, config, "error"); + growl.onlyUnique(); + growl.reverseOrder(); + growl.inlineMessages(); + growl.position(); +}); diff --git a/angular-growl-v2/angular-growl-v2.d.ts b/angular-growl-v2/angular-growl-v2.d.ts new file mode 100644 index 0000000000..1c324723f6 --- /dev/null +++ b/angular-growl-v2/angular-growl-v2.d.ts @@ -0,0 +1,211 @@ +// Type definitions for Angular Growl 2 v.0.7.3 +// Project: http://janstevens.github.io/angular-growl-2 +// Definitions by: Tadeusz Hucal +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular.growl { + + /** + * Global Time-To-Leave configuration. + */ + interface IGrowlTTLConfig { + success?: number; + error?: number; + warning?: number; + info?: number; + } + + /** + * Custom configuration used in single message call. + */ + interface IGrowlMessageConfig { + title?: string; + ttl?: number; + disableCountDown?: boolean; + disableIcons?: boolean; + disableCloseButton?: boolean; + referenceId?: number; + onclose?: Function; + onopen?: Function; + } + + /** + * Growl message with configuration. + */ + interface IGrowlMessage extends IGrowlMessageConfig { + text: string; + } + + /** + * Growl service provider. + */ + interface IGrowlProvider extends angular.IServiceProvider { + /** + * Pre-defined server error interceptor. + */ + serverMessagesInterceptor: (string|Function)[]; + + /** + * Set default TTL settings. + * @param ttl configuration of TTL for different type of message + */ + globalTimeToLive(ttl: IGrowlTTLConfig): void; + /** + * Set default TTL settings. + * @param ttl ttl in milliseconds + */ + globalTimeToLive(ttl: number): void; + /** + * Set default setting for disabling close button. + * @param disableCloseButton + */ + globalDisableCloseButton(disableCloseButton: boolean): void; + /** + * Set default setting for disabling icons. + * @param disableIcons + */ + globalDisableIcons(disableIcons: boolean): void; + /** + * Set reversing order of displaying new messages. + * @param reverseOrder + */ + globalReversedOrder(reverseOrder: boolean): void + /** + * Set default setting for displaying message disappear countdown. + * @param disableCountDown + */ + globalDisableCountDown(disableCountDown: boolean): void; + /** + * Set default allowance for inline messages. + * @param inline + */ + globalInlineMessages(inline: boolean): void; + /** + * Set default message position. + * @param position + */ + globalPosition(position: string): void; + /** + * Enable/disable displaying only unique messages. + * @param onlyUniqueMessages + */ + onlyUniqueMessages(onlyUniqueMessages: boolean): void; + + /** + * Set key where messages are stored (for http interceptor). + * @param messageVariableKey + */ + messagesKey(messageKey: string): void; + /** + * Set key where message text is stored (for http interceptor). + * @param messageVariableKey + */ + messageTextKey(messageTextKey: string): void; + /** + * Set key where title of message is stored (for http interceptor). + * @param messageVariableKey + */ + messageTitleKey(messageTitleKey: string): void; + /** + * Set key where severity of message is stored (for http interceptor). + * @param messageVariableKey + */ + messageSeverityKey(messageSeverityKey: string): void; + /** + * Set key where variables for message are stored (for http interceptor). + * @param messageVariableKey + */ + messageVariableKey(messageVariableKey: string): void; + } + + /** + * Growl service. + */ + interface IGrowlService { + /** + * Show warning message. + * @param message text to display (or code for angular-translate) + */ + warning(message: string): IGrowlMessage; + /** + * Show warning message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + warning(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show error message. + * @param message text to display (or code for angular-translate) + */ + error(message: string): IGrowlMessage; + /** + * Show error message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + error(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show information message. + * @param message text to display (or code for angular-translate) + */ + info(message: string): IGrowlMessage; + /** + * Show information message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + info(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show success message. + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + success(message: string): IGrowlMessage; + /** + * Show success message. + * @param message text to display (or code for angular-translate) + */ + success(message: string, config: IGrowlMessageConfig): IGrowlMessage; + + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + */ + general(message: string): IGrowlMessage; + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + */ + general(message: string, config: IGrowlMessageConfig): IGrowlMessage; + /** + * Show message (generic). + * @param message text to display (or code for angular-translate) + * @param config additional message configuration + * @param severity message severity (error, warning, success, info). + */ + general(message: string, config: IGrowlMessageConfig, severity: string): IGrowlMessage; + + /** + * Get current setting for displaying only unique messages. + */ + onlyUnique(): boolean; + /** + * Get current setting for reversing messages order. + */ + reverseOrder(): boolean; + /** + * Get current allowance for inline messages. + */ + inlineMessages(): boolean; + /** + * Get current messages position. + */ + position(): string; + } +} diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index cf7a20d79e..1e3eda18af 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Material 0.8.3+ (ng.material module) +// Type definitions for Angular Material 0.8.3+ (angular.material module) // Project: https://github.com/angular/material // Definitions by: Matt Traynham // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -12,14 +12,14 @@ declare module angular.material { controller?: any; locals?: {[index: string]: any}; targetEvent?: any; - resolve?: {[index: string]: ng.IPromise} + resolve?: {[index: string]: angular.IPromise} controllerAs?: string; parent?: Element; disableParentScroll?: boolean; } interface MDBottomSheetService { - show(options: MDBottomSheetOptions): ng.IPromise; + show(options: MDBottomSheetOptions): angular.IPromise; hide(response?: any): void; cancel(response?: any): void; } @@ -49,14 +49,14 @@ declare module angular.material { controller?: any; locals?: {[index: string]: any}; bindToController?: boolean; - resolve?: {[index: string]: ng.IPromise} + resolve?: {[index: string]: angular.IPromise} controllerAs?: string; parent?: Element; onComplete?: Function; } interface MDDialogService { - show(dialog: MDDialogOptions|MDPresetDialog): ng.IPromise; + show(dialog: MDDialogOptions|MDPresetDialog): angular.IPromise; confirm(): MDConfirmDialog; alert(): MDAlertDialog; hide(response?: any): void; @@ -64,7 +64,7 @@ declare module angular.material { } interface MDIcon { - (path: string): ng.IPromise; + (path: string): angular.IPromise; } interface MDIconProvider { @@ -110,14 +110,14 @@ declare module angular.material { controller?: any; locals?: {[index: string]: any}; bindToController?: boolean; - resolve?: {[index: string]: ng.IPromise} + resolve?: {[index: string]: angular.IPromise} controllerAs?: string; parent?: Element; } interface MDToastService { - show(optionsOrPreset: MDToastOptions|MDToastPreset): ng.IPromise; - showSimple(): ng.IPromise; + show(optionsOrPreset: MDToastOptions|MDToastPreset): angular.IPromise; + showSimple(): angular.IPromise; simple(): MDSimpleToastPreset; build(): MDToastPreset; updateContent(): void; diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index c9bf91c016..d7e65c77ca 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -190,15 +190,15 @@ declare module angular.ui.bootstrap { /** * a promise that is resolved when a modal is closed and rejected when a modal is dismissed */ - result: ng.IPromise; + result: angular.IPromise; /** * a promise that is resolved when a modal gets opened after downloading content's template and resolving all variables */ - opened: ng.IPromise; + opened: angular.IPromise; } - interface IModalScope extends ng.IScope { + interface IModalScope extends angular.IScope { /** * Those methods make it easy to close a modal window without a need to create a dedicated controller */ @@ -623,7 +623,7 @@ declare module angular.ui.bootstrap { * * @return A promise that is resolved when the transition finishes. */ - (element: ng.IAugmentedJQuery, trigger: any, options?: ITransitionServiceOptions): ng.IPromise; + (element: angular.IAugmentedJQuery, trigger: any, options?: ITransitionServiceOptions): angular.IPromise; } interface ITransitionServiceOptions { diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 0cf796832f..f5dfbeca51 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -62,7 +62,7 @@ declare module angular.ui { reloadOnSearch?: boolean; } - interface IStateProvider extends IServiceProvider { + interface IStateProvider extends ng.IServiceProvider { state(name:string, config:IState): IStateProvider; state(config:IState): IStateProvider; decorator(name?: string, decorator?: (state: IState, parent: Function) => any): any; @@ -81,7 +81,7 @@ declare module angular.ui { type(name: string, definition: any, definitionFn?: any): any; } - interface IUrlRouterProvider extends IServiceProvider { + interface IUrlRouterProvider extends ng.IServiceProvider { when(whenPath: RegExp, handler: Function): IUrlRouterProvider; when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; when(whenPath: RegExp, toPath: string): IUrlRouterProvider; @@ -143,7 +143,7 @@ declare module angular.ui { * * @param options Options object. */ - go(to: string, params?: {}, options?: IStateOptions): IPromise; + go(to: string, params?: {}, options?: IStateOptions): ng.IPromise; transitionTo(state: string, params?: {}, updateLocation?: boolean): void; transitionTo(state: string, params?: {}, options?: IStateOptions): void; includes(state: string, params?: {}): boolean; diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 9f7efea892..31f59d9fa6 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -452,9 +452,9 @@ declare module angular { $invalid: boolean; $submitted: boolean; $error: any; - $addControl(control: ng.INgModelController): void; - $removeControl(control: ng.INgModelController): void; - $setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void; + $addControl(control: INgModelController): void; + $removeControl(control: INgModelController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; $setDirty(): void; $setPristine(): void; $commitViewValue(): void; @@ -509,7 +509,7 @@ declare module angular { } interface IAsyncModelValidators { - [index: string]: (...args: any[]) => ng.IPromise; + [index: string]: (...args: any[]) => IPromise; } interface IModelParser { @@ -665,6 +665,7 @@ declare module angular { // TODO undocumented, so we need to get it from the source code /////////////////////////////////////////////////////////////////////////// interface IBrowserService { + defer: ng.ITimeoutService; [key: string]: any; } @@ -931,11 +932,19 @@ declare module angular { /** * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. * - * Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. * - * @param promises An array or hash of promises. + * @param promises An array of promises. */ - all(promises: IPromise[]|{ [id: string]: IPromise; }): IPromise; + all(promises: IPromise[]): IPromise; + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises A hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; /** * Creates a Deferred object which represents a task which will finish in the future. */ @@ -1573,12 +1582,12 @@ declare module angular { * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. */ decorator(name: string, inlineAnnotatedFunction: any[]): void; - factory(name: string, serviceFactoryFunction: Function): ng.IServiceProvider; - factory(name: string, inlineAnnotatedFunction: any[]): ng.IServiceProvider; - provider(name: string, provider: ng.IServiceProvider): ng.IServiceProvider; - provider(name: string, serviceProviderConstructor: Function): ng.IServiceProvider; - service(name: string, constructor: Function): ng.IServiceProvider; - value(name: string, value: any): ng.IServiceProvider; + factory(name: string, serviceFactoryFunction: Function): IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; + provider(name: string, provider: IServiceProvider): IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): IServiceProvider; + service(name: string, constructor: Function): IServiceProvider; + value(name: string, value: any): IServiceProvider; } } diff --git a/auth0.lock/auth0.lock-tests.ts b/auth0.lock/auth0.lock-tests.ts new file mode 100644 index 0000000000..fd646ee1bb --- /dev/null +++ b/auth0.lock/auth0.lock-tests.ts @@ -0,0 +1,13 @@ +/// +/// + +var lock: Auth0LockStatic = new Auth0Lock("dsa7d77dsa7d7", "mine.auth0.com"); + +lock.showSignin({ + connections: ["facebook", "google-oauth2", "twitter", "Username-Password-Authentication"], + icon: "https://contoso.com/logo-32.png", + socialBigButtons: true + }, + () => { + // The Auth0 Widget is now loaded. +}); diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts new file mode 100644 index 0000000000..e8ba3cb996 --- /dev/null +++ b/auth0.lock/auth0.lock.d.ts @@ -0,0 +1,80 @@ +// Type definitions for Auth0Widget.js +// Project: http://auth0.com +// Definitions by: Robert McLaws +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface Auth0LockPopupOptions { + width: number; + height: number; + left: number; + top: number; +} + +interface Auth0LockOptions { + authParams?: any; + callbackURL?: string; + connections?: string[]; + container?: string; + closable?: boolean; + dict?: any; + defaultUserPasswordConnection?: string; + defaultADUsernameFromEmailPrefix?: boolean; + disableResetAction?: boolean; + disableSignupAction?: boolean; + focusInput?: boolean; + forceJSONP?: boolean; + gravatar?: boolean; + integratedWindowsLogin?: boolean; + loginAfterSignup?: boolean; + popup?: boolean; + popupOptions?: Auth0LockPopupOptions; + rememberLastLogin?: boolean; + resetLink?: string; + responseType?: string; + signupLink?: string; + socialBigButtons?: boolean; + sso?: boolean; + theme?: string; + usernameStyle?: any; +} + +interface Auth0LockConstructorOptions { + cdn?: string; + assetsUrl?: string; + useCordovaSocialPlugins?: boolean; +} + +interface Auth0LockStatic { + new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; + + show(): void; + show(options: Auth0LockOptions): void; + show(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + show(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + + showSignin(): void; + showSignin(options: Auth0LockOptions): void; + showSignin(callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + showSignin(options: Auth0LockOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, token?: string) => void) : void; + + showSignup(): void; + showSignup(options: Auth0LockOptions): void; + showSignup(callback: (error?: Auth0Error) => void) : void; + showSignup(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; + + showReset(): void; + showReset(options: Auth0LockOptions): void; + showReset(callback: (error?: Auth0Error) => void) : void; + showReset(options: Auth0LockOptions, callback: (error?: Auth0Error) => void) : void; + + hide(callback: () => void): void; + logout(callback: () => void): void; +} + +declare var Auth0Lock: Auth0LockStatic; + +declare module "Auth0Lock" { + export = Auth0Lock; +} diff --git a/autobahn/autobahn-tests.ts b/autobahn/autobahn-tests.ts new file mode 100644 index 0000000000..ee9c41b3e8 --- /dev/null +++ b/autobahn/autobahn-tests.ts @@ -0,0 +1,47 @@ +/// + +class MyClass { + add2Count: number = 0; + session: autobahn.Session; + + constructor(session: autobahn.Session) { + this.session = session; + } + + add2(args: Array): number { + this.add2Count++; + return args[0] + args[1]; + } + + onEvent(args: Array): void { + console.log("Event:", args[0]); + } +} + +function test_client() { + var options: autobahn.IConnectionOptions = + { url: 'ws://127.0.0.1:8080/ws', realm: 'realm1' }; + + var connection = new autobahn.Connection(options); + + connection.onopen = session => { + var myInstance = new MyClass(session); + + // 1) subscribe to a topic + session.subscribe('com.myapp.hello', myInstance.onEvent); + + // 2) publish an event + session.publish('com.myapp.hello', ['Hello, world!']); + + // 3) register a procedure for remoting + session.register('com.myapp.add2', myInstance.add2); + + // 4) call a remote procedure + session.call('com.myapp.add2', [2, 3]).then( + res => { + console.log("Result:", res); + }); + }; + + connection.open(); +} \ No newline at end of file diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts new file mode 100644 index 0000000000..7191e9c4f9 --- /dev/null +++ b/autobahn/autobahn.d.ts @@ -0,0 +1,195 @@ +// Type definitions for AutobahnJS v0.9.6 +// Project: http://autobahn.ws/js/ +// Definitions by: Elad Zelingher +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module autobahn { + + export class Session { + id: number; + realm: string; + isOpen: boolean; + features: any; + caller_disclose_me: boolean; + publisher_disclose_me: boolean; + subscriptions: ISubscription[][]; + registrations: IRegistration[]; + + constructor(transport: ITransport, defer: DeferFactory, challenge: OnChallengeHandler); + + join(realm: string, authmethods: string[], authid: string): void; + + leave(reason: string, message: string): void; + + call(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise; + + publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise; + + subscribe(topic: string, handler: SubscribeHandler, options?: ISubscribeOptions): When.Promise; + + register(procedure: string, endpoint: RegisterEndpoint, options?: IRegisterOptions): When.Promise; + + unsubscribe(subscription: ISubscription): When.Promise; + + unregister(registration: IRegistration): When.Promise; + + prefix(prefix: string, uri: string): void; + + resolve(curie: string): string; + + onjoin: (roleFeatures: any) => void; + onleave: (reason: string, details: any) => void; + } + + interface IInvocation { + caller?: number; + progress?: boolean; + procedure: string; + } + + interface IEvent { + publication: number; + publisher?: number; + topic: string; + } + + interface IResult { + args: any[]; + kwargs: any; + } + + interface IError { + error: string; + args: any[]; + kwargs: any; + } + + type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void; + + interface ISubscription { + topic: string; + handler: SubscribeHandler; + options: ISubscribeOptions; + session: Session; + id: number; + active: boolean; + unsubscribe(): When.Promise; + } + + type RegisterEndpoint = (args?: any[], kwargs?: any, details?: IInvocation) => void; + + interface IRegistration { + procedure: string; + endpoint: RegisterEndpoint; + options: IRegisterOptions; + session: Session; + id: number; + active: boolean; + unregister(): When.Promise; + } + + interface IPublication { + id: number; + } + + interface ICallOptions { + timeout?: number; + receive_progress?: boolean; + disclose_me?: boolean; + } + + interface IPublishOptions { + exclude?: number[]; + eligible?: number[]; + disclose_me? : Boolean; + } + + interface ISubscribeOptions { + match? : string; + } + + interface IRegisterOptions { + disclose_caller?: boolean; + } + + export class Connection { + constructor(options?: IConnectionOptions); + + open(): void; + + close(reason: string, message: string): void; + + onopen: (session: Session, details: any) => void; + onclose: (reason: string, details: any) => boolean; + } + + interface ITransportDefinition { + url?: string; + protocols?: string[]; + type: string; + } + + type DeferFactory = () => any; + + type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise; + + interface IConnectionOptions { + use_es6_promises?: boolean; + // use explicit deferred factory, e.g. jQuery.Deferred or Q.defer + use_deferred?: DeferFactory; + transports?: ITransportDefinition[]; + retry_if_unreachable?: boolean; + max_retries?: number; + initial_retry_delay?: number; + max_retry_delay?: number; + retry_delay_growth?: number; + retry_delay_jitter?: number; + url?: string; + protocols?: string[]; + onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; + realm?: string; + authmethods?: string[]; + authid?: string; + } + + interface ICloseEventDetails { + wasClean: boolean; + reason: string; + code: number; + } + + interface ITransport { + onopen: () => void; + onmessage: (message: any[]) => void; + onclose: (details: ICloseEventDetails) => void; + + send(message: any[]): void; + close(errorCode: number, reason?: string): void; + } + + interface ITransportFactory { + //constructor(options: any); + type: string; + create(): ITransport; + } + + interface ITransports { + register(name: string, factory: any): void; + isRegistered(name: string): boolean; + get(name: string): any; + list(): any[]; + } + + interface ILog { + debug(...args: any[]): void; + } + + interface IUtil { + assert(condition: boolean, message: string): void; + } + + var util: IUtil; + var log: ILog; + var transports: ITransports; +} \ No newline at end of file diff --git a/axios/axios-tests.ts b/axios/axios-tests.ts index a11421e19e..93787cf3d7 100644 --- a/axios/axios-tests.ts +++ b/axios/axios-tests.ts @@ -1,23 +1,18 @@ /// -interface InputBody { - random: number; -} +enum HttpMethod { GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH } +enum ResponseType { arraybuffer, blob, document, json, text } interface Repository { id: number; name: string; } -function convenientGet () { - axios.get("https://api.github.com/repos/mzabriskie/axios") - .then(r => console.log(r.config.data.random)); -} +axios.get("https://api.github.com/repos/mzabriskie/axios") + .then(r => console.log(r.config.method)); -function get() { - axios({ - url: "https://api.github.com/repos/mzabriskie/axios", - method: Axios.HTTPMethod.GET, - headers: {}, - }).then(r => console.log("ID:" + r.data.id + " Name: " + r.data.name)); -} \ No newline at end of file +axios({ + url: "https://api.github.com/repos/mzabriskie/axios", + method: HttpMethod[HttpMethod.GET], + headers: {}, +}).then(r => console.log("ID:" + r.data.id + " Name: " + r.data.name)); diff --git a/axios/axios.d.ts b/axios/axios.d.ts index 5455ba167d..c2a2873eac 100644 --- a/axios/axios.d.ts +++ b/axios/axios.d.ts @@ -6,8 +6,6 @@ /// declare module Axios { - export enum HTTPMethod { GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH } - export enum ResponseType { arraybuffer, blob, document, json, text } /** * - request body data type @@ -46,7 +44,7 @@ declare module Axios { * indicates the type of data that the server will respond with * options are 'arraybuffer', 'blob', 'document', 'json', 'text' */ - responseType?: Axios.ResponseType; + responseType?: string; /** * name of the cookie to use as a value for xsrf token @@ -65,14 +63,15 @@ declare module Axios { */ interface AxiosXHRConfig extends AxiosXHRConfigBase { /** - * server URL that will be used for the request + * server URL that will be used for the request, options are: + * GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH */ url: string; /** * request method to be used when making the request */ - method?: Axios.HTTPMethod; + method?: string; /** * data to be sent as the request body @@ -86,7 +85,7 @@ declare module Axios { * - expected response type, * - request body data type */ - interface AxiosXHR { + interface AxiosXHR { /** * Response that was provided by the server */ @@ -110,7 +109,7 @@ declare module Axios { /** * config that was provided to `axios` for the request */ - config: AxiosXHRConfig; + config: AxiosXHRConfig; } /** @@ -119,40 +118,40 @@ declare module Axios { */ interface AxiosStatic { - (config: AxiosXHRConfig): Promise>; + (config: AxiosXHRConfig): Promise>; - new (config: AxiosXHRConfig): Promise>; + new (config: AxiosXHRConfig): Promise>; /** * convenience alias, method = GET */ - get(url: string, config?: AxiosXHRConfigBase): Promise>; + get(url: string, config?: AxiosXHRConfigBase): Promise>; /** * convenience alias, method = DELETE */ - delete(url: string, config?: AxiosXHRConfigBase): Promise>; + delete(url: string, config?: AxiosXHRConfigBase): Promise>; /** * convenience alias, method = HEAD */ - head(url: string, config?: AxiosXHRConfigBase): Promise>; + head(url: string, config?: AxiosXHRConfigBase): Promise>; /** * convenience alias, method = POST */ - post(url: string, data?: any, config?: AxiosXHRConfigBase): Promise>; + post(url: string, data?: any, config?: AxiosXHRConfigBase): Promise>; /** * convenience alias, method = PUT */ - put(url: string, data?: any, config?: AxiosXHRConfigBase): Promise>; + put(url: string, data?: any, config?: AxiosXHRConfigBase): Promise>; /** * convenience alias, method = PATCH */ - patch(url: string, data?: any, config?: AxiosXHRConfigBase): Promise>; + patch(url: string, data?: any, config?: AxiosXHRConfigBase): Promise>; } } diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 834ebc8318..7de8eb8072 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -238,7 +238,7 @@ declare module Backbone { initial(n: number): TModel[]; inject(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; isEmpty(object: any): boolean; - invoke(methodName: string, arguments?: any[]): any; + invoke(methodName: string, args?: any[]): any; last(): TModel; last(n: number): TModel[]; lastIndexOf(element: TModel, fromIndex?: number): number; diff --git a/bootstrap-touchspin/bootstrap-touchspin-tests.ts b/bootstrap-touchspin/bootstrap-touchspin-tests.ts new file mode 100644 index 0000000000..552c26f52f --- /dev/null +++ b/bootstrap-touchspin/bootstrap-touchspin-tests.ts @@ -0,0 +1,68 @@ +/// +/// + +$(function () { + // Example 1 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo1']").TouchSpin({ + min: 0, + max: 100, + step: 0.1, + decimals: 2, + boostat: 5, + maxboostedstep: 10, + postfix: '%' + }); + + // Example 2 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo2']").TouchSpin({ + min: -1000000000, + max: 1000000000, + stepinterval: 50, + maxboostedstep: 10000000, + prefix: '$' + }); + + // Example 3 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo_vertical']").TouchSpin({ + verticalbuttons: true + }); + + // Example 4 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo_vertical2']").TouchSpin({ + verticalbuttons: true, + verticalupclass: 'glyphicon glyphicon-plus', + verticaldownclass: 'glyphicon glyphicon-minus' + }); + + // Example 5 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo3']").TouchSpin(); + + // Example 6 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo3_21']").TouchSpin({ + initval: 40 + }); + + // Example 7 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo4']").TouchSpin({ + postfix: "a button", + postfix_extraclass: "btn btn-default" + }); + + // Example 8 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo4_2']").TouchSpin({ + postfix: "a button", + postfix_extraclass: "btn btn-default" + }); + + // Example 9 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo5']").TouchSpin({ + prefix: "pre", + postfix: "post" + }); + + // Example 10 from http://www.virtuosoft.eu/code/bootstrap-touchspin/ + $("input[name='demo6']").TouchSpin({ + buttondown_class: "btn btn-link", + buttonup_class: "btn btn-link" + }); +}); \ No newline at end of file diff --git a/bootstrap-touchspin/bootstrap-touchspin.d.ts b/bootstrap-touchspin/bootstrap-touchspin.d.ts new file mode 100644 index 0000000000..2dcf628842 --- /dev/null +++ b/bootstrap-touchspin/bootstrap-touchspin.d.ts @@ -0,0 +1,130 @@ +// Type definitions for Bootstrap TouchSpin +// Project: http://www.virtuosoft.eu/code/bootstrap-touchspin/ +// Definitions by: Albin Sunnanbo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * TouchSpinOptions. All options are optional + */ +interface TouchSpinOptions { + /** + * Applied when no explicit value is set on the input with the value attribute. + * Empty string means that the value remains empty on initialization. + */ + initval?: number | string; + + /** + * Minimum value. + */ + min?: number; + + /** + * Maximum value. + */ + max?: number; + + /** + * Incremental/decremental step on up/down change. + */ + step?: number; + + /** + * How to force the value to be divisible by step value: 'none' | 'round' | 'floor' | 'ceil' + */ + forcestepdivisibility?: string; + + /** + * Number of decimal points. + */ + decimals?: number; + + /** + * Refresh rate of the spinner in milliseconds. + */ + stepinterval?: number; + + /** + * Time in milliseconds before the spinner starts to spin. + */ + stepintervaldelay?: number; + + /** + * Enables the traditional up/down buttons. + */ + verticalbuttons?: boolean; + + /** + * Class of the up button with vertical buttons mode enabled. + */ + verticalupclass?: string; + + /** + * Class of the down button with vertical buttons mode enabled. + */ + verticaldownclass?: string; + + /** + * Text before the input. + */ + prefix?: string; + + /** + * Text after the input. + */ + postfix?: string; + + /** + * Extra class(es) for prefix. + */ + prefix_extraclass?: string; + + /** + * Extra class(es) for postfix. + */ + postfix_extraclass?: string; + + /** + * If enabled, the the spinner is continually becoming faster as holding the button. + */ + booster?: boolean; + + /** + * Boost at every nth step. + */ + boostat?: number; + + /** + * Maximum step when boosted. + */ + maxboostedstep?: number | boolean; + + /** + * Enables the mouse wheel to change the value of the input. + */ + mousewheel?: boolean; + + /** + * Class(es) of down button. + */ + buttondown_class?: string; + + /** + * Class(es) of up button. + */ + buttonup_class?: string; +} + +interface JQuery { + /** + * Initialize TouchSpin + */ + TouchSpin(): JQuery; + + /** + * Inialize TouchSpin with options + * @param options a TouchSpinOptions object with one or more options + */ + TouchSpin(options: TouchSpinOptions): JQuery; +} diff --git a/breeze/breeze-tests.ts b/breeze/breeze-tests.ts index 979bc56835..f309462afa 100644 --- a/breeze/breeze-tests.ts +++ b/breeze/breeze-tests.ts @@ -3,7 +3,6 @@ import core = breeze.core; import config = breeze.config; - function test_dataType() { var typ = breeze.DataType.DateTime; var nm = typ.getName(); @@ -888,4 +887,4 @@ function test_config() { config.registerType(f1, "myCtor"); s = config.stringifyPad; o = config.typeRegistry; -} \ No newline at end of file +} diff --git a/calq/calq-tests.ts b/calq/calq-tests.ts new file mode 100644 index 0000000000..6f8019261d --- /dev/null +++ b/calq/calq-tests.ts @@ -0,0 +1,28 @@ +/// +function calq_base() +{ + calq.init("bfff14a4e0225789be3d9d22c4bb42a1"); + + calq.init("bfff14a4e0225789be3d9d22c4bb42a1", { your: "config" }); + + calq.action.track("Product Review", {"Rating": 9.0}); + + calq.action.trackSale("Product Sale", { "Product Id": 149, "Product Name": "Dinosaur T-Shirt XL" }, "USD",10); + + calq.action.trackHTMLLink('Link', { 'Target': 'Calq'}); + + calq.action.trackPageView(); + + calq.action.trackPageView("Custom Action"); + + calq.action.setGlobalProperty("Referral Source", "Google Campaign"); +} + +function calq_people() +{ + calq.user.identify("1001"); + + calq.user.clear(); + + calq.user.profile( { "Company": "MegaCorp", "$email": "super_customer1@notarealemail.com" }); +} diff --git a/calq/calq.d.ts b/calq/calq.d.ts new file mode 100644 index 0000000000..c574df58fe --- /dev/null +++ b/calq/calq.d.ts @@ -0,0 +1,34 @@ +// Type definitions for calq +// Project: https://calq.io/docs/client/javascript/reference +// Definitions by: Eirik Hoem +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Calq +{ + action:Calq.Action; + user:Calq.User; + + init(writeKey:string, options?:{[index:string]:any}):void; +} + +declare module Calq +{ + interface Action + { + track(action:string, params?:{[index:string]:any}):void; + trackSale(action:string, params:{[index:string]:any}, currency:string, amount:number):void; + trackHTMLLink(action:string, params?:{[index:string]:any}):void; + trackPageView(action?:string):void; + setGlobalProperty(name:string,value:any):void; + } + + interface User + { + identify(userId:string):void; + clear():void; + profile(params:{[index:string]:any}):void; + + } +} + +declare var calq:Calq; \ No newline at end of file diff --git a/chartjs/chart-tests.ts b/chartjs/chart-tests.ts index 2374b6228a..4bd8820c6c 100644 --- a/chartjs/chart-tests.ts +++ b/chartjs/chart-tests.ts @@ -252,12 +252,12 @@ var myPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData, { var myPolarAreaChartLegend: string = myPolarAreaChart.generateLegend(); var myPolarAreaChartImage: string = myPolarAreaChart.toBase64Image(); -myPolarAreaChart.addData([{ +myPolarAreaChart.addData({ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" -}], 0); +}, 0); myPolarAreaChart.clear(); myPolarAreaChart.removeData(0); myPolarAreaChart.resize(); @@ -301,12 +301,12 @@ var myPieChart = new Chart(ctx).Pie(pieData, { var myPieChartLegend: string = myPieChart.generateLegend(); var myPieChartImage: string = myPieChart.toBase64Image(); -myPieChart.addData([{ +myPieChart.addData({ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" -}], 0); +}, 0); myPieChart.clear(); myPieChart.removeData(0); myPieChart.resize(); @@ -329,12 +329,12 @@ var myDoughnutChart = new Chart(ctx).Doughnut(pieData, { var myDoughnutChartLegend: string = myDoughnutChart.generateLegend(); var myDoughnutChartImage: string = myDoughnutChart.toBase64Image(); -myPieChart.addData([{ +myPieChart.addData({ value: 120, color: "#4D5360", highlight: "#616774", label: "Dark Grey" -}], 0); +}, 0); myDoughnutChart.clear(); myDoughnutChart.removeData(0); myDoughnutChart.resize(); diff --git a/chartjs/chart.d.ts b/chartjs/chart.d.ts index a73ecc94e2..9da7245f61 100644 --- a/chartjs/chart.d.ts +++ b/chartjs/chart.d.ts @@ -113,8 +113,9 @@ interface LinearInstance extends ChartInstance { interface CircularInstance extends ChartInstance { getSegmentsAtEvent: (event: Event) => {}[]; update: () => void; - addData: (valuesArray: CircularChartData[], index: number) => void; + addData: (valuesArray: CircularChartData, index?: number) => void; removeData: (index: number) => void; + segments: Array; } interface LineChartOptions extends ChartOptions { diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts index 890b4221ec..1c95073394 100644 --- a/chosen/chosen.jquery.d.ts +++ b/chosen/chosen.jquery.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Chosen.JQuery 0.9 +// Type definitions for Chosen.JQuery 1.4.2 // Project: http://harvesthq.github.com/chosen/ // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -8,18 +8,23 @@ interface ChosenOptions { allow_single_deselect?: boolean; - disable_search_threshold?: number; disable_search?: boolean; + disable_search_threshold?: number; + enable_split_word_search?: boolean; + inherit_select_classes?: boolean; + max_selected_options?: number; + no_results_text?: string; + placeholder_text_multiple?: string; + placeholder_text_single?: string; search_contains?: boolean; single_backstroke_delete?: boolean; - max_selected_options?: number; - placeholder_text_multiple?: string; - placeholder_text?: string; - placeholder_text_single?: string; - no_results_text?: string; + width?: number; + display_disabled_options?: boolean; + display_selected_options?: boolean; + include_group_label_in_selected?: boolean; } interface JQuery { chosen(): JQuery; chosen(options: ChosenOptions): JQuery; -} \ No newline at end of file +} diff --git a/circular-json/circular-json-tests.ts b/circular-json/circular-json-tests.ts new file mode 100644 index 0000000000..d3f2e0951c --- /dev/null +++ b/circular-json/circular-json-tests.ts @@ -0,0 +1,31 @@ +/// + +import CircularJSON = require('circular-json'); + +var replacer = (key: any, val: any) => { + return val; +} + +var replacerArray = ['a', 'x']; + +// implements JSON interface +var json_obj: JSON = CircularJSON; + +CircularJSON.parse('{"a":"b"}'); + +CircularJSON.parse('{"a":"b"}', replacer); + +// just stringify a value +CircularJSON.stringify({a: 'b'}); + +// do replacements for part of the object +CircularJSON.stringify({a: 'b'}, replacer); +CircularJSON.stringify({a: 'b'}, replacerArray); + +// add whitespace to the output +CircularJSON.stringify({a: 'b'}, replacer, 5); +CircularJSON.stringify({a: 'b'}, replacerArray, 5); + +// do not actually set up a re-parseable object +CircularJSON.stringify({a: 'b'}, replacer, 5, true); +CircularJSON.stringify({a: 'b'}, replacerArray, 5, true); diff --git a/circular-json/circular-json.d.ts b/circular-json/circular-json.d.ts new file mode 100644 index 0000000000..2aa27e947a --- /dev/null +++ b/circular-json/circular-json.d.ts @@ -0,0 +1,15 @@ +// Type definitions for circular-json v0.1.6 +// Project: https://github.com/WebReflection/circular-json +// Definitions by: Jonathan Pevarnek +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'circular-json' { + interface ICircularJSON extends JSON { + parse(text: string, reviver?: (key: any, value: any) => any): any; + stringify(value: any, replacer?: ((key: string, value: any) => any) | any[], space?: any, placeholder?: boolean): string; + } + + var CircularJSON: ICircularJSON; + + export = CircularJSON; +} diff --git a/cordova-ionic/cordova-ionic.d.ts b/cordova-ionic/cordova-ionic.d.ts index c9b1e635b3..5f0adee3ec 100644 --- a/cordova-ionic/cordova-ionic.d.ts +++ b/cordova-ionic/cordova-ionic.d.ts @@ -5,10 +5,6 @@ /// -interface Cordova { - plugins:Plugins; -} - -interface Plugins { +interface CordovaPlugins { Keyboard:Ionic.Keyboard; } diff --git a/cordova-plugin-email-composer/cordova-plugin-email-composer-tests.ts b/cordova-plugin-email-composer/cordova-plugin-email-composer-tests.ts new file mode 100644 index 0000000000..ccd1e725d4 --- /dev/null +++ b/cordova-plugin-email-composer/cordova-plugin-email-composer-tests.ts @@ -0,0 +1,19 @@ +/// +/// + +cordova.plugins.email.isAvailable((isAvailable) => {}, {}); +cordova.plugins.email.open({ + to: ['foo@bar.com'], + body: 'foo bar' +}); +cordova.plugins.email.open(); +cordova.plugins.email.open({}, () => {}); +cordova.plugins.email.open({}, () => {}, {}); + +cordova.plugins.email.openDraft({ + to: ['foo@bar.com'], + body: 'foo bar' +}); +cordova.plugins.email.openDraft(); +cordova.plugins.email.openDraft({}, () => {}); +cordova.plugins.email.openDraft({}, () => {}, {}); diff --git a/cordova-plugin-email-composer/cordova-plugin-email-composer.d.ts b/cordova-plugin-email-composer/cordova-plugin-email-composer.d.ts new file mode 100644 index 0000000000..9472ccf356 --- /dev/null +++ b/cordova-plugin-email-composer/cordova-plugin-email-composer.d.ts @@ -0,0 +1,33 @@ +// Type definitions for Apache Cordova Email Composer plugin +// Project: https://github.com/katzer/cordova-plugin-email-composer +// Definitions by: Dave Taylor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * The plugin provides access to the standard interface that manages the + * editing and sending an email message + */ +interface CordovaPluginEmailComposer { + /** Determine if the device is capable to send emails */ + isAvailable(callback:(isAvailable:boolean) => void, scope?:any):void; + /** Open a pre-filled email draft */ + open(options?:ICordovaPluginEmailComposerOpenOptions, callback?:() => void, scope?:any):void; + openDraft(options?:ICordovaPluginEmailComposerOpenOptions, callback?:() => void, scope?:any):void; +} + +interface ICordovaPluginEmailComposerOpenOptions { + /** An configured email account is required to send emails */ + to?:string[]; + body?:string; + cc?:string[]; + bcc?:string[]; + /** Attachments can be either base64 encoded datas, files from the the device storage or assets from within the www folder */ + attachments?:any[]; + subject?:string; + /** The default value for isHTML is true */ + isHtml?:boolean; +} + +interface CordovaPlugins { + email:CordovaPluginEmailComposer; +} diff --git a/cordova/cordova.d.ts b/cordova/cordova.d.ts index 75b77ebe2c..32ef0a76b6 100644 --- a/cordova/cordova.d.ts +++ b/cordova/cordova.d.ts @@ -43,8 +43,12 @@ interface Cordova { define(moduleName: string, factory: (require: any, exports: any, module: any) => any): void; /** Access a Cordova module by name. */ require(moduleName: string): any; + /** Namespace for Cordova plugin functionality */ + plugins:CordovaPlugins; } +interface CordovaPlugins {} + interface Document { addEventListener(type: "deviceready", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "pause", listener: (ev: Event) => any, useCapture?: boolean): void; diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index 51c51f608f..bdc7509b76 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -476,7 +476,7 @@ function callenderView() { .style("text-anchor", "middle") .text(function (d) { return d; }); - var rect = svg.selectAll(".day") + var rect: D3.UpdateSelection = svg.selectAll(".day") .data(function (d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) .enter().append("rect") .attr("class", "day") @@ -960,7 +960,7 @@ function forcedBasedLabelPlacemant() { var anchorLink = vis.selectAll("line.anchorLink").data(labelAnchorLinks)//.enter().append("svg:line").attr("class", "anchorLink").style("stroke", "#999"); - var anchorNode = vis.selectAll("g.anchorNode").data(force2.nodes()).enter().append("svg:g").attr("class", "anchorNode"); + var anchorNode: D3.Selection = vis.selectAll("g.anchorNode").data(force2.nodes()).enter().append("svg:g").attr("class", "anchorNode"); anchorNode.append("svg:circle").attr("r", 0).style("fill", "#FFF"); anchorNode.append("svg:text").text(function (d, i) { return i % 2 == 0 ? "" : d.node.label @@ -1404,7 +1404,7 @@ function quadtree() { .attr("width", function (d) { return d.width; } ) .attr("height", function (d) { return d.height; } ); - var point = svg.selectAll(".point") + var point: D3.Selection = svg.selectAll(".point") .data(data) .enter().append("circle") .attr("class", "point") @@ -2656,4 +2656,18 @@ function multiTest() { .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); -} \ No newline at end of file +} + +// Tests miscellaneous keyboard events +function keyboardEventsTest() { + var keyPressed: string; + d3.select("body").on("keydown", () => { + if (d3.event.metaKey) { + keyPressed = "meta"; + } else if (d3.event.ctrlKey) { + keyPressed = "ctrl"; + } else if (d3.event.altKey) { + keyPressed = "alt"; + } + }); +} diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 57e817818d..b71610f944 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -12,19 +12,19 @@ declare module D3 { /** * Returns the empty selection */ - (): Selection; + (): _Selection; /** * Selects the first element that matches the specified selector string * * @param selector Selection String to match */ - (selector: string): Selection; + (selector: string): _Selection; /** * Selects the specified node * * @param element Node element to select */ - (element: EventTarget): Selection; + (element: EventTarget): _Selection; }; /** @@ -36,13 +36,13 @@ declare module D3 { * * @param selector Selection String to match */ - (selector: string): Selection; + (selector: string): _Selection; /** * Selects the specified array of elements * * @param elements Array of node elements to select */ - (elements: EventTarget[]): Selection; + (elements: EventTarget[]): _Selection; }; } @@ -57,7 +57,9 @@ declare module D3 { x: number; y: number; keyCode: number; - altKey: any; + altKey?: boolean; + ctrlKey?: boolean; + metaKey?: boolean; type: string; } @@ -458,7 +460,7 @@ declare module D3 { /** * Returns the root selection */ - selection(): Selection; + selection(): _Selection; ns: { /** * The map of registered namespace prefixes @@ -726,56 +728,56 @@ declare module D3 { format(rows: any[]): string; } - export interface Selection extends Selectors, Array { + export interface _Selection extends Selectors, Array { attr: { (name: string): string; - (name: string, value: any): Selection; - (name: string, valueFunction: (data: any, index: number) => any): Selection; - (attrValueMap : Object): Selection; + (name: string, value: any): _Selection; + (name: string, valueFunction: (data: T, index: number) => any): _Selection; + (attrValueMap: Object): _Selection; }; classed: { (name: string): boolean; - (name: string, value: any): Selection; - (name: string, valueFunction: (data: any, index: number) => any): Selection; - (classValueMap: Object): Selection; + (name: string, value: any): _Selection; + (name: string, valueFunction: (data: T, index: number) => any): _Selection; + (classValueMap: Object): _Selection; }; style: { (name: string): string; - (name: string, value: any, priority?: string): Selection; - (name: string, valueFunction: (data: any, index: number) => any, priority?: string): Selection; - (styleValueMap : Object): Selection; + (name: string, value: any, priority?: string): _Selection; + (name: string, valueFunction: (data: T, index: number) => any, priority?: string): _Selection; + (styleValueMap: Object): _Selection; }; property: { (name: string): void; - (name: string, value: any): Selection; - (name: string, valueFunction: (data: any, index: number) => any): Selection; - (propertyValueMap : Object): Selection; + (name: string, value: any): _Selection; + (name: string, valueFunction: (data: T, index: number) => any): _Selection; + (propertyValueMap: Object): _Selection; }; text: { (): string; - (value: any): Selection; - (valueFunction: (data: any, index: number) => any): Selection; + (value: any): _Selection; + (valueFunction: (data: T, index: number) => any): _Selection; }; html: { (): string; - (value: any): Selection; - (valueFunction: (data: any, index: number) => any): Selection; + (value: any): _Selection; + (valueFunction: (data: T, index: number) => any): _Selection; }; - append: (name: string) => Selection; - insert: (name: string, before: string) => Selection; - remove: () => Selection; + append: (name: string) => _Selection; + insert: (name: string, before: string) => _Selection; + remove: () => _Selection; empty: () => boolean; data: { - (values: (data: any, index?: number) => any[], key?: (data: any, index?: number) => any): UpdateSelection; - (values: any[], key?: (data: any, index?: number) => any): UpdateSelection; - (): any[]; + (values: (data: T, index?: number) => U[], key?: (data: U, index?: number) => any): _UpdateSelection; + (values: U[], key?: (data: U, index?: number) => any): _UpdateSelection; + (): T[]; }; datum: { @@ -789,36 +791,31 @@ declare module D3 { * element. The function is then used to set each element's data. A null value will * delete the bound data. This operator has no effect on the index. */ - (values: (data: any, index: number) => any): UpdateSelection; + (values: (data: U, index: number) => any): _UpdateSelection; /** * Sets the element's bound data to the specified value on all selected elements. * Unlike the D3.Selection.data method, this method does not compute a join (and thus * does not compute enter and exit selections). * @param values The same data to be given to all elements. */ - (values: any): UpdateSelection; + (values: U): _UpdateSelection; /** * Returns the bound datum for the first non-null element in the selection. * This is generally useful only if you know the selection contains exactly one element. */ - (): any; - /** - * Returns the bound datum for the first non-null element in the selection. - * This is generally useful only if you know the selection contains exactly one element. - */ - (): T; + (): T; }; filter: { - (filter: (data: any, index: number) => boolean, thisArg?: any): UpdateSelection; - (filter: string): UpdateSelection; + (filter: (data: T, index: number) => boolean, thisArg?: any): _UpdateSelection; + (filter: string): _UpdateSelection; }; - call(callback: (selection: Selection, ...args: any[]) => void, ...args: any[]): Selection; - each(eachFunction: (data: any, index: number) => any): Selection; + call(callback: (selection: _Selection, ...args: any[]) => void, ...args: any[]): _Selection; + each(eachFunction: (data: T, index: number) => any): _Selection; on: { (type: string): (data: any, index: number) => any; - (type: string, listener: (data: any, index: number) => any, capture?: boolean): Selection; + (type: string, listener: (data: any, index: number) => any, capture?: boolean): _Selection; }; /** @@ -840,38 +837,44 @@ declare module D3 { * to compare, and should return either a negative, positive, or zero value to indicate * their relative order. */ - sort(comparator?: (a: T, b: T) => number): Selection; + sort(comparator?: (a: T, b: T) => number): _Selection; /** * Re-inserts elements into the document such that the document order matches the selection * order. This is equivalent to calling sort() if the data is already sorted, but much * faster. */ - order: () => Selection; + order: () => _Selection; /** * Returns the first non-null element in the current selection. If the selection is empty, * returns null. */ - node: () => T; + node: () => E; } - export interface EnterSelection { - append: (name: string) => Selection; - insert: (name: string, before?: string) => Selection; - select: (selector: string) => Selection; + export interface Selection extends _Selection { } + + export interface _EnterSelection { + append: (name: string) => _Selection; + insert: (name: string, before?: string) => _Selection; + select: (selector: string) => _Selection; empty: () => boolean; node: () => Element; - call: (callback: (selection: EnterSelection) => void) => EnterSelection; + call: (callback: (selection: _EnterSelection) => void) => _EnterSelection; size: () => number; } - export interface UpdateSelection extends Selection { - enter: () => EnterSelection; - update: () => Selection; - exit: () => Selection; + export interface EnterSelection extends _EnterSelection { } + + export interface _UpdateSelection extends _Selection { + enter: () => _EnterSelection; + update: () => _Selection; + exit: () => _Selection; } + export interface UpdateSelection extends _UpdateSelection { } + export interface NestKeyValue { key: string; values: any; @@ -1279,6 +1282,13 @@ declare module D3 { (angle: (d : any) => number): PieLayout (angle: (d : any, i: number) => number): PieLayout; }; + padAngle: { + (): number; + (angle: number): PieLayout; + (angle: () => number): PieLayout; + (angle: (d : any) => number): PieLayout + (angle: (d : any, i: number) => number): PieLayout; + }; } export interface ArcDescriptor { @@ -1363,7 +1373,20 @@ declare module D3 { (number:number): ForceLayout; (accessor: (d: any, index: number) => number): ForceLayout; }; - + /** + * If distance is specified, sets the maximum distance over which + * charge forces are applied. If distance is not specified, returns + * the current maximum charge distance, which defaults to infinity. + * Specifying a finite charge distance improves the performance of + * the force layout and produces a more localized layout; + * distance-limited charge forces are especially useful in + * conjunction with custom gravity. + */ + chargeDistance: { + (): number; + (distance: number): ForceLayout; + (accessor: (d: any, index: number) => number): ForceLayout; + }; theta: { (): number; (number:number): ForceLayout; @@ -1727,14 +1750,14 @@ declare module D3 { export interface Symbol { type: (symbolType: string | ((datum: any, index: number) => string)) => Symbol; size: (size: number | ((datum: any, index: number) => number)) => Symbol; - (datum:any, index:number): string; + (datum?: any, index?: number): string; } export interface Brush { /** * Draws or redraws this brush into the specified selection of elements */ - (selection: Selection): void; + (selection: _Selection): void; /** * Gets or sets the x-scale associated with the brush */ @@ -1802,7 +1825,7 @@ declare module D3 { } export interface Axis { - (selection: Selection): void; + (selection: _Selection): void; (transition: Transition.Transition): void; scale: { @@ -1944,13 +1967,13 @@ declare module D3 { /** * Get the interpolation accessor. */ - (): string; + (): string | ((points: number[][]) => string); /** * Set the interpolation accessor. * * @param interpolate The interpolation mode */ - (interpolate: string): Line; + (interpolate: string | ((points: number[][]) => string)): Line; }; /** * Get or set the cardinal spline tension. @@ -2240,13 +2263,13 @@ declare module D3 { /** * Get the interpolation accessor. */ - (): string; + (): string | ((points: number[][]) => string); /** * Set the interpolation accessor. * * @param interpolate The interpolation mode */ - (interpolate: string): Area; + (interpolate: string | ((points: number[][]) => string)): Area; }; /** * Get or set the cardinal spline tension. @@ -2775,7 +2798,7 @@ declare module D3 { * registering the necessary event listeners to support * panning and zooming. */ - (selection: Selection): void; + (selection: _Selection): void; /** * Registers a listener to receive events diff --git a/dompurify/dompurify-tests.ts b/dompurify/dompurify-tests.ts new file mode 100644 index 0000000000..d9d6e0bd6b --- /dev/null +++ b/dompurify/dompurify-tests.ts @@ -0,0 +1,8 @@ +/// + +import dompurify = require('dompurify'); + +dompurify.sanitize(''); +dompurify.addHook('beforeSanitizeElements', (el, data, config) => { + return el; +}); diff --git a/dompurify/dompurify.d.ts b/dompurify/dompurify.d.ts new file mode 100644 index 0000000000..b1f24b00ed --- /dev/null +++ b/dompurify/dompurify.d.ts @@ -0,0 +1,15 @@ +// Type definitions for DOM Purify +// Project: https://github.com/cure53/DOMPurify +// Definitions by: Dave Taylor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface IDOMPurify { + sanitize(s:string):string; + addHook(hook:string, cb:(currentNode:Element, data:any, config:any) => Element):void; +} + +declare var DOMPurify:IDOMPurify; + +declare module 'dompurify' { + export = DOMPurify; +} diff --git a/drop/drop.d.ts b/drop/drop.d.ts index 18568afdd6..e3615d5105 100644 --- a/drop/drop.d.ts +++ b/drop/drop.d.ts @@ -9,6 +9,12 @@ declare module drop { interface DropStatic { new(options: IDropOptions): Drop; + createContext(options: IDropContextOptions): DropStatic; + } + + interface IDropContextOptions { + classPrefix?: string; + defaults?: IDropOptions; } interface IDropOptions { diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 22cbb8ab57..636a7af685 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -444,7 +444,7 @@ declare module Ember { static metaForProperty(key: string): {}; static isClass: boolean; static isMethod: boolean; - static initializer(arguments?: ApplicationInitializerArguments): void; + static initializer(args?: ApplicationInitializerArguments): void; /** Call advanceReadiness after any asynchronous setup logic has completed. Each call to deferReadiness must be matched by a call to advanceReadiness @@ -1318,9 +1318,9 @@ declare module Ember { Creates an instance of the class. @param arguments A hash containing values with which to initialize the newly instantiated object. **/ - static create(arguments?: {}): T; + static create(args: {}): T; detect(obj: any): boolean; - reopen(arguments?: {}): T; + reopen(args?: {}): T; } class MutableArray implements Array, MutableEnumberable { addArrayObserver(target: any, opts?: EnumerableConfigurationOptions): any[]; @@ -1581,17 +1581,17 @@ declare module Ember { /** Creates a subclass of the Object class. **/ - static extend(arguments?: CoreObjectArguments): T; - static extend(mixins? : Mixin, arguments?: CoreObjectArguments): T; + static extend(args?: CoreObjectArguments): T; + static extend(mixins? : Mixin, args?: CoreObjectArguments): T; /** Creates an instance of the class. @param arguments A hash containing values with which to initialize the newly instantiated object. **/ - static create(arguments?: {}): T; + static create(args?: {}): T; /** Equivalent to doing extend(arguments).create(). If possible use the normal create method instead. **/ - static createWithMixins(arguments?: {}): T; + static createWithMixins(args?: {}): T; static detect(obj: any): boolean; static detectInstance(obj: any): boolean; /** @@ -1608,13 +1608,13 @@ declare module Ember { Augments a constructor's prototype with additional properties and functions. To add functions and properties to the constructor itself, see reopenClass. **/ - static reopen(arguments?: {}): T; + static reopen(args?: {}): T; /** Augments a constructor's own properties and functions. To add functions and properties to instances of a constructor by extending the constructor's prototype see reopen. **/ - static reopenClass(arguments?: {}): T; + static reopenClass(args?: {}): T; static isClass: boolean; static isMethod: boolean; addObserver: ModifyObserver; diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts index 31bf44ce11..40f845d098 100644 --- a/errorhandler/errorhandler.d.ts +++ b/errorhandler/errorhandler.d.ts @@ -7,6 +7,6 @@ declare module "errorhandler" { import express = require('express'); - function e(): express.ErrorRequestHandler; + function e(options?: {log?: any}): express.ErrorRequestHandler; export = e; -} \ No newline at end of file +} diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index d2635a4043..f1a0f7ad92 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -1,27 +1,12 @@ +/// /// import esprima = require('esprima'); -import Syntax = esprima.Syntax; var token: esprima.Token; -var options: esprima.Options; -var comment: Syntax.Comment; -var program: Syntax.Program; -var statement: Syntax.Statement; -var expression: Syntax.Expression; -var property: Syntax.Property; -var identifier: Syntax.Identifier; -var literal: Syntax.Literal; -var switchCase: Syntax.SwitchCase; -var catchClause: Syntax.CatchClause; -var variableDeclaratorOrExpression: Syntax.VariableDeclaratorOrExpression; -var literalOrIdentifier: Syntax.LiteralOrIdentifier; -var blockStatementOrExpression: Syntax.BlockStatementOrExpression; -var identifierOrExpression: Syntax.IdentifierOrExpression; -var any: any; +var comment: esprima.Comment; +var program: ESTree.Program; var string: string; -var boolean: boolean; -var number: number; // esprima string = esprima.version; @@ -34,171 +19,5 @@ token = esprima.tokenize('code', {range: true})[0]; string = token.type; string = token.value; -// Program -string = program.type; -statement = program.body[0]; -comment = program.comments[0] - -// Location -number = program.loc.start.line; -number = program.loc.start.column; -number = program.loc.end.line; -number = program.loc.end.column; -number = program.range[0]; - // Comment string = comment.value; - -// Statement -// BlockStatement -var blockStatement: Syntax.BlockStatement; -string = blockStatement.type; -statement = blockStatement.body[0]; -comment = blockStatement.leadingComments[0]; -comment = blockStatement.trailingComments[0]; - -// ExpressionStatement -var expressionStatement: Syntax.ExpressionStatement; -expression = expressionStatement.expression; - -// IfStatement -var ifStatement: Syntax.IfStatement; -expression = ifStatement.test; -statement = ifStatement.consequent; -statement = ifStatement.alternate; - -// LabeledStatement -var labeledStatement: Syntax.LabeledStatement; -identifier = labeledStatement.label; -statement = labeledStatement.body; - -// WithStatement -var withStatement: Syntax.WithStatement; -expression = withStatement.object; - -// SwitchStatement -var switchStatement: Syntax.SwitchStatement; -expression = switchStatement.discriminant; -switchCase = switchStatement.cases[0]; -boolean = switchStatement.lexical; - -// ReturnStatement -var returnStatement: Syntax.ReturnStatement; -expression = returnStatement.argument; - -// TryStatement -var tryStatement: Syntax.TryStatement; -blockStatement = tryStatement.block; -catchClause = tryStatement.handler; -catchClause = tryStatement.guardedHandlers[0]; -blockStatement = tryStatement.finalizer; - -// ForStatement -var forStatement: Syntax.ForStatement; -variableDeclaratorOrExpression = forStatement.init; -expression = forStatement.update; - -// ForInStatement -var forInStatement: Syntax.ForInStatement; -variableDeclaratorOrExpression = forInStatement.left; -expression = forInStatement.right; -boolean = forInStatement.each; - -// Expression -// ArrayExpression -var arrayExpression: Syntax.ArrayExpression; -string = arrayExpression.type; -expression = arrayExpression.elements[0]; - -// ObjectExpression -var objectExpression: Syntax.ObjectExpression; -property = objectExpression.properties[0]; -string = property.type; -literalOrIdentifier = property.key; -expression = property.value; -string = property.kind; - -// FunctionExpression -var functionExpression: Syntax.FunctionExpression; -identifier = functionExpression.id; -identifier = functionExpression.params[0]; -expression = functionExpression.defaults[0]; -identifier = functionExpression.rest; -blockStatementOrExpression = functionExpression.body; -boolean = functionExpression.generator; -boolean = functionExpression.expression; - -// SequenceExpression -var sequenceExpression: Syntax.SequenceExpression; -expression = sequenceExpression.expressions[0] - -// UnaryExpression -var unaryExpression: Syntax.UnaryExpression; -string = unaryExpression.operator; -boolean = unaryExpression.prefix; - -// BinaryExpression -var binaryExpression: Syntax.BinaryExpression; -expression = binaryExpression.left; -expression = binaryExpression.right; - -// ConditionalExpression -var conditionalExpression: Syntax.ConditionalExpression; -expression = conditionalExpression.test; -expression = conditionalExpression.alternate; -expression = conditionalExpression.consequent; - -// NewExpression -var newExpression: Syntax.NewExpression; -expression = newExpression.callee; -expression = newExpression.arguments[0]; - -// CallExpression -var callExpression: Syntax.CallExpression; -expression = callExpression.callee; -expression = callExpression.arguments[0]; - -// MemberExpression -var memberExpression: Syntax.MemberExpression; -expression = memberExpression.object; -identifierOrExpression = memberExpression.property; -boolean = memberExpression.computed; - -// Declarations -var functionDeclaration: Syntax.FunctionDeclaration; -identifier = functionDeclaration.id; -var params:Syntax.Identifier[] = functionDeclaration.params; -var defaults:Syntax.Expression[] = functionDeclaration.defaults; -identifier = functionDeclaration.rest; -var body:Syntax.BlockStatementOrExpression = functionDeclaration.body; -boolean = functionDeclaration.generator; -boolean = functionDeclaration.expression; - -var variableDeclaration: Syntax.VariableDeclaration; -var declarations:Syntax.VariableDeclarator[] = variableDeclaration.declarations; -string = variableDeclaration.kind; // "var" | "let" | "const" - -var variableDeclarator: Syntax.VariableDeclarator; -identifier = variableDeclarator.id; // Pattern -expression = variableDeclarator.init; - -// Clauses -// SwitchCase -string = switchCase.type; -expression = switchCase.test; -statement = switchCase.consequent[0]; - -// CatchClause -string = catchClause.type; -identifier = catchClause.param; -expression = catchClause.guard; -blockStatement = catchClause.body; - -// Misc -// Identifier -string = identifier.type; -string = identifier.name; - -// Literal -string = literal.type; -any = literal.value; diff --git a/esprima/esprima.d.ts b/esprima/esprima.d.ts index d62bb09bb1..10e37a5309 100644 --- a/esprima/esprima.d.ts +++ b/esprima/esprima.d.ts @@ -1,18 +1,24 @@ -// Type definitions for Esprima v1.2.0 +// Type definitions for Esprima v2.1.0 // Project: http://esprima.org -// Definitions by: teppeis +// Definitions by: teppeis , RReverser // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module esprima { - var version: string; - function parse(code: string, options?: Options): Syntax.Program; - function tokenize(code: string, options?: Options): Array; + var version: string + function parse(code: string, options?: Options): ESTree.Program + function tokenize(code: string, options?: Options): Array interface Token { type: string value: string } + interface Comment extends ESTree.Node { + value: string + } + interface Options { loc?: boolean range?: boolean @@ -23,244 +29,6 @@ declare module esprima { tolerant?: boolean source?: boolean } - - module Syntax { - // Node - interface Node { - type: string - loc?: LineLocation - range?: number[] - leadingComments?: Comment[] - trailingComments?: Comment[] - } - interface LineLocation { - start: Position - end: Position - } - interface Position { - line: number - column: number - } - - // Comment - interface Comment extends Node { - value: string - } - - // Program - interface Program extends Node { - body: Statement[] - comments?: Comment[] - } - - // Function - interface Function extends Node { - id: Identifier // | null - params: Identifier[] - defaults: Expression[] - rest: Identifier // | null - body: BlockStatementOrExpression - generator: boolean - expression: boolean - } - interface BlockStatementOrExpression extends BlockStatement, Expression { - } - - // Statement - interface Statement extends Node { - } - interface EmptyStatement extends Statement { - } - interface BlockStatement extends Statement { - body: Statement[] - } - interface ExpressionStatement extends Statement { - expression: Expression - } - interface IfStatement extends Statement { - test: Expression - consequent: Statement - alternate: Statement - } - interface LabeledStatement extends Statement { - label: Identifier - body: Statement - } - interface BreakStatement extends Statement { - label: Identifier // | null - } - interface ContinueStatement extends Statement { - label: Identifier // | null - } - interface WithStatement extends Statement { - object: Expression - body: Statement - } - interface SwitchStatement extends Statement { - discriminant: Expression - cases: SwitchCase[] - lexical: boolean - } - interface ReturnStatement extends Statement { - argument: Expression // | null - } - interface ThrowStatement extends Statement { - argument: Expression - } - interface TryStatement extends Statement { - block: BlockStatement - handler: CatchClause // | null - guardedHandlers: CatchClause[] - finalizer: BlockStatement // | null - } - interface WhileStatement extends Statement { - test: Expression - body: Statement - } - interface DoWhileStatement extends Statement { - body: Statement - test: Expression - } - interface ForStatement extends Statement { - init: VariableDeclaratorOrExpression // | null - test: Expression // | null - update: Expression // | null - body: Statement - } - interface ForInStatement extends Statement { - left: VariableDeclaratorOrExpression - right: Expression - body: Statement - each: boolean - } - interface VariableDeclaratorOrExpression extends VariableDeclarator, Expression { - } - interface DebuggerStatement extends Statement { - } - interface StatementOrList extends Array, Statement { - } - - // Declaration - interface Declaration extends Statement { - } - interface FunctionDeclaration extends Declaration { - id: Identifier - params: Identifier[] // Pattern - defaults: Expression[] - rest: Identifier - body: BlockStatementOrExpression - generator: boolean - expression: boolean - } - interface VariableDeclaration extends Declaration { - declarations: VariableDeclarator[] - kind: string // "var" | "let" | "const" - } - interface VariableDeclarator extends Node { - id: Identifier // Pattern - init: Expression - } - - // Expression - interface Expression extends Node { // | Pattern - } - //interface Expression extends - // ThisExpression, ArrayExpression, ObjectExpression, FunctionExpression, - // ArrowFunctionExpression, SequenceExpression, UnaryExpression, BinaryExpression, - // AssignmentExpression, UpdateExpression, LogicalExpression, ConditionalExpression, - // NewExpression, CallExpression, MemberExpression { - //} - interface ThisExpression extends Expression { - } - interface ArrayExpression extends Expression { - elements: Expression[] // [ Expression | null ] - } - interface ObjectExpression extends Expression { - properties: Property[] - } - interface Property extends Node { - key: LiteralOrIdentifier // Literal | Identifier - value: Expression - kind: string // "init" | "get" | "set" - } - interface LiteralOrIdentifier extends Literal, Identifier { - } - interface FunctionExpression extends Function, Expression { - } - interface ArrowFunctionExpression extends Function, Expression { - } - interface SequenceExpression extends Expression { - expressions: Expression[] - } - interface UnaryExpression extends Expression { - operator: string // UnaryOperator - prefix: boolean - argument: Expression - } - interface BinaryExpression extends Expression { - operator: string // BinaryOperator - left: Expression - right: Expression - } - interface AssignmentExpression extends Expression { - operator: string // AssignmentOperator - left: Expression - right: Expression - } - interface UpdateExpression extends Expression { - operator: string // UpdateOperator - argument: Expression - prefix: boolean - } - interface LogicalExpression extends Expression { - operator: string // LogicalOperator - left: Expression - right: Expression - } - interface ConditionalExpression extends Expression { - test: Expression - alternate: Expression - consequent: Expression - } - interface NewExpression extends Expression { - callee: Expression - arguments: Expression[] - } - interface CallExpression extends Expression { - callee: Expression - arguments: Expression[] - } - interface MemberExpression extends Expression { - object: Expression - property: IdentifierOrExpression // Identifier | Expression - computed: boolean - } - interface IdentifierOrExpression extends Identifier, Expression { - } - - // Pattern - // interface Pattern extends Node { - // } - - // Clauses - interface SwitchCase extends Node { - test: Expression - consequent: Statement[] - } - interface CatchClause extends Node { - param: Identifier // Pattern - guard: Expression - body: BlockStatement - } - - // Misc - interface Identifier extends Node, Expression { // | Pattern - name: string - } - interface Literal extends Node, Expression { - value: any // string | boolean | null | number | RegExp - } - } } declare module "esprima" { diff --git a/estree/estree-tests.ts b/estree/estree-tests.ts new file mode 100644 index 0000000000..bbf16586d4 --- /dev/null +++ b/estree/estree-tests.ts @@ -0,0 +1,177 @@ +/// + +var program: ESTree.Program; +var statement: ESTree.Statement; +var expression: ESTree.Expression; +var property: ESTree.Property; +var identifier: ESTree.Identifier; +var literal: ESTree.Literal; +var switchCase: ESTree.SwitchCase; +var catchClause: ESTree.CatchClause; +var pattern: ESTree.Pattern; +var assignmentPattern: ESTree.AssignmentPattern; +var variableDeclaratorOrExpression: ESTree.VariableDeclaration | ESTree.Expression; +var literalOrIdentifier: ESTree.Literal | ESTree.Identifier; +var blockStatementOrExpression: ESTree.BlockStatement | ESTree.Expression; +var identifierOrExpression: ESTree.Expression; +var any: any; +var string: string; +var boolean: boolean; +var number: number; + +// Program +string = program.type; +statement = program.body[0]; + +// Location +number = program.loc.start.line; +number = program.loc.start.column; +number = program.loc.end.line; +number = program.loc.end.column; +number = program.range[0]; + +// Statement +// BlockStatement +var blockStatement: ESTree.BlockStatement; +string = blockStatement.type; +statement = blockStatement.body[0]; + +// ExpressionStatement +var expressionStatement: ESTree.ExpressionStatement; +expression = expressionStatement.expression; + +// IfStatement +var ifStatement: ESTree.IfStatement; +expression = ifStatement.test; +statement = ifStatement.consequent; +statement = ifStatement.alternate; + +// LabeledStatement +var labeledStatement: ESTree.LabeledStatement; +identifier = labeledStatement.label; +statement = labeledStatement.body; + +// WithStatement +var withStatement: ESTree.WithStatement; +expression = withStatement.object; + +// SwitchStatement +var switchStatement: ESTree.SwitchStatement; +expression = switchStatement.discriminant; +switchCase = switchStatement.cases[0]; +boolean = switchStatement.lexical; + +// ReturnStatement +var returnStatement: ESTree.ReturnStatement; +expression = returnStatement.argument; + +// TryStatement +var tryStatement: ESTree.TryStatement; +blockStatement = tryStatement.block; +catchClause = tryStatement.handler; +blockStatement = tryStatement.finalizer; + +// ForStatement +var forStatement: ESTree.ForStatement; +variableDeclaratorOrExpression = forStatement.init; +expression = forStatement.update; + +// ForInStatement +var forInStatement: ESTree.ForInStatement; +variableDeclaratorOrExpression = forInStatement.left; +expression = forInStatement.right; + +// Expression +// ArrayExpression +var arrayExpression: ESTree.ArrayExpression; +string = arrayExpression.type; +expression = arrayExpression.elements[0]; + +// ObjectExpression +var objectExpression: ESTree.ObjectExpression; +property = objectExpression.properties[0]; +string = property.type; +expression = property.key; +expression = property.value; +string = property.kind; + +// FunctionExpression +var functionExpression: ESTree.FunctionExpression; +identifier = functionExpression.id; +assignmentPattern = functionExpression.params[0]; +pattern = assignmentPattern.left; +expression = assignmentPattern.right; +blockStatementOrExpression = functionExpression.body; +boolean = functionExpression.generator; + +// SequenceExpression +var sequenceExpression: ESTree.SequenceExpression; +expression = sequenceExpression.expressions[0] + +// UnaryExpression +var unaryExpression: ESTree.UnaryExpression; +string = unaryExpression.operator; +boolean = unaryExpression.prefix; + +// BinaryExpression +var binaryExpression: ESTree.BinaryExpression; +expression = binaryExpression.left; +expression = binaryExpression.right; + +// ConditionalExpression +var conditionalExpression: ESTree.ConditionalExpression; +expression = conditionalExpression.test; +expression = conditionalExpression.alternate; +expression = conditionalExpression.consequent; + +// NewExpression +var newExpression: ESTree.NewExpression; +expression = newExpression.callee; +expression = newExpression.arguments[0]; + +// CallExpression +var callExpression: ESTree.CallExpression; +expression = callExpression.callee; +expression = callExpression.arguments[0]; + +// MemberExpression +var memberExpression: ESTree.MemberExpression; +expression = memberExpression.object; +identifierOrExpression = memberExpression.property; +boolean = memberExpression.computed; + +// Declarations +var functionDeclaration: ESTree.FunctionDeclaration; +identifier = functionDeclaration.id; +var params:ESTree.Pattern[] = functionDeclaration.params; +var body:ESTree.BlockStatement | ESTree.Expression = functionDeclaration.body; +boolean = functionDeclaration.generator; + +var variableDeclaration: ESTree.VariableDeclaration; +var declarations:ESTree.VariableDeclarator[] = variableDeclaration.declarations; +string = variableDeclaration.kind; // "var" | "let" | "const" + +var variableDeclarator: ESTree.VariableDeclarator; +pattern = variableDeclarator.id; // Pattern +expression = variableDeclarator.init; + +// Clauses +// SwitchCase +string = switchCase.type; +expression = switchCase.test; +statement = switchCase.consequent[0]; + +// CatchClause +string = catchClause.type; +pattern = catchClause.param; +expression = catchClause.guard; +blockStatement = catchClause.body; + +// Misc +// Identifier +string = identifier.type; +string = identifier.name; + +// Literal +string = literal.type; +any = literal.value; diff --git a/estree/estree.d.ts b/estree/estree.d.ts new file mode 100644 index 0000000000..329396b7c4 --- /dev/null +++ b/estree/estree.d.ts @@ -0,0 +1,369 @@ +// Type definitions for ESTree AST specification +// Project: https://github.com/estree/estree +// Definitions by: RReverser +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ESTree { + interface Node { + type: string; + loc?: SourceLocation; + range?: [number, number]; + } + + interface SourceLocation { + source?: string; + start: Position; + end: Position; + } + + interface Position { + line: number; + column: number; + } + + interface Program extends Node { + body: Array; + sourceType: string; + } + + interface Function extends Node { + id?: Identifier; + params: Array; + body: BlockStatement | Expression; + generator: boolean; + } + + interface Statement extends Node {} + + interface EmptyStatement extends Statement {} + + interface BlockStatement extends Statement { + body: Array; + } + + interface ExpressionStatement extends Statement { + expression: Expression; + } + + interface IfStatement extends Statement { + test: Expression; + consequent: Statement; + alternate?: Statement; + } + + interface LabeledStatement extends Statement { + label: Identifier; + body: Statement; + } + + interface BreakStatement extends Statement { + label?: Identifier; + } + + interface ContinueStatement extends Statement { + label?: Identifier; + } + + interface WithStatement extends Statement { + object: Expression; + body: Statement; + } + + interface SwitchStatement extends Statement { + discriminant: Expression; + cases: Array; + lexical: boolean; + } + + interface ReturnStatement extends Statement { + argument?: Expression; + } + + interface ThrowStatement extends Statement { + argument: Expression; + } + + interface TryStatement extends Statement { + block: BlockStatement; + handler?: CatchClause; + finalizer?: BlockStatement; + } + + interface WhileStatement extends Statement { + test: Expression; + body: Statement; + } + + interface DoWhileStatement extends Statement { + body: Statement; + test: Expression; + } + + interface ForStatement extends Statement { + init?: VariableDeclaration | Expression; + test?: Expression; + update?: Expression; + body: Statement; + } + + interface ForInStatement extends Statement { + left: VariableDeclaration | Expression; + right: Expression; + body: Statement; + } + + interface DebuggerStatement extends Statement {} + + interface Declaration extends Statement {} + + interface FunctionDeclaration extends Function, Declaration { + id: Identifier; + } + + interface VariableDeclaration extends Declaration { + declarations: Array; + kind: string; + } + + interface VariableDeclarator extends Node { + id: Pattern; + init?: Expression; + } + + interface Expression extends Node {} + + interface ThisExpression extends Expression {} + + interface ArrayExpression extends Expression { + elements: Array; + } + + interface ObjectExpression extends Expression { + properties: Array; + } + + interface Property extends Node { + key: Expression; + value: Expression; + kind: string; + method: boolean; + shorthand: boolean; + computed: boolean; + } + + interface FunctionExpression extends Function, Expression {} + + interface SequenceExpression extends Expression { + expressions: Array; + } + + interface UnaryExpression extends Expression { + operator: UnaryOperator; + prefix: boolean; + argument: Expression; + } + + interface BinaryExpression extends Expression { + operator: BinaryOperator; + left: Expression; + right: Expression; + } + + interface AssignmentExpression extends Expression { + operator: AssignmentOperator; + left: Pattern | MemberExpression; + right: Expression; + } + + interface UpdateExpression extends Expression { + operator: UpdateOperator; + argument: Expression; + prefix: boolean; + } + + interface LogicalExpression extends Expression { + operator: LogicalOperator; + left: Expression; + right: Expression; + } + + interface ConditionalExpression extends Expression { + test: Expression; + alternate: Expression; + consequent: Expression; + } + + interface CallExpression extends Expression { + callee: Expression | Super; + arguments: Array; + } + + interface NewExpression extends CallExpression {} + + interface MemberExpression extends Expression, Pattern { + object: Expression | Super; + property: Expression; + computed: boolean; + } + + interface Pattern extends Node {} + + interface SwitchCase extends Node { + test?: Expression; + consequent: Array; + } + + interface CatchClause extends Node { + param: Pattern; + guard: any; + body: BlockStatement; + } + + interface Identifier extends Node, Expression, Pattern { + name: string; + } + + interface Literal extends Node, Expression { + value?: string | boolean | number | RegExp; + } + + interface RegexLiteral extends Literal { + regex: { + pattern: string; + flags: string; + }; + } + + type UnaryOperator = string; + + type BinaryOperator = string; + + type LogicalOperator = string; + + type AssignmentOperator = string; + + type UpdateOperator = string; + + interface ForOfStatement extends ForInStatement {} + + interface Super extends Node {} + + interface SpreadElement extends Node { + argument: Expression; + } + + interface ArrowFunctionExpression extends Function, Expression { + expression: boolean; + } + + interface YieldExpression extends Expression { + argument?: Expression; + } + + interface TemplateLiteral extends Expression { + quasis: Array; + expressions: Array; + } + + interface TaggedTemplateExpression extends Expression { + tag: Expression; + quasi: TemplateLiteral; + } + + interface TemplateElement extends Node { + tail: boolean; + value: { + cooked: string; + value: string; + }; + } + + interface AssignmentProperty extends Property { + value: Pattern; + kind: string; + method: boolean; + } + + interface ObjectPattern extends Pattern { + properties: Array; + } + + interface ArrayPattern extends Pattern { + elements: Array; + } + + interface RestElement extends Pattern { + argument: Pattern; + } + + interface AssignmentPattern extends Pattern { + left: Pattern; + right: Expression; + } + + interface Class extends Node { + id?: Identifier; + superClass: Expression; + body: ClassBody; + } + + interface ClassBody extends Node { + body: Array; + } + + interface MethodDefinition extends Node { + key: Identifier; + value: FunctionExpression; + kind: string; + computed: boolean; + static: boolean; + } + + interface ClassDeclaration extends Class, Declaration { + id: Identifier; + } + + interface ClassExpression extends Class, Expression {} + + interface MetaProperty extends Expression { + meta: Identifier; + property: Identifier; + } + + interface ImportDeclaration extends Node { + specifiers: Array; + source: Literal; + } + + interface ImportSpecifier { + imported: Identifier; + local: Identifier; + } + + interface ImportDefaultSpecifier { + local: Identifier; + } + + interface ImportNamespaceSpecifier { + local: Identifier; + } + + interface ExportNamedDeclaration extends Node { + declaration?: Declaration; + specifiers: Array; + source?: Literal; + } + + interface ExportSpecifier { + exported: Identifier; + local: Identifier; + } + + interface ExportDefaultDeclaration extends Node { + declaration: Declaration | Expression; + } + + interface ExportAllDeclaration extends Node { + source: Literal; + } +} \ No newline at end of file diff --git a/express-debug/express-debug-tests.ts b/express-debug/express-debug-tests.ts new file mode 100644 index 0000000000..6f702856ed --- /dev/null +++ b/express-debug/express-debug-tests.ts @@ -0,0 +1,21 @@ +/// + +import express = require('express'); +import debug = require('express-debug'); +var app = express(); + +debug(app, { + depth: 4, + theme: 'public/css/debug.css', + extra_panels: [{ + name: 'mypanel', + template: '/absolute/path/to/mypanel.jade', + process: function(locals) { + return { locals: { mypanel: true, }}; + } + }], + panels: ['locals', 'request', 'session'], + path: '/express-debug', + extra_attrs: '', + sort: false, +}); diff --git a/express-debug/express-debug.d.ts b/express-debug/express-debug.d.ts new file mode 100644 index 0000000000..d185f5c696 --- /dev/null +++ b/express-debug/express-debug.d.ts @@ -0,0 +1,83 @@ +// Type definitions for express-debug 1.1.1 +// Project: https://github.com/devoidfury/express-debug +// Definitions by: Federico Bond +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import debug = require('express-debug'); + debug(app, options); + + =============================================== */ + +/// + +declare module "express-debug" { + import express = require('express'); + + interface CustomPanel { + name: string; + + template: string; + + process(locals: any): any; + + standalone?: boolean; + + initialize?(req: express.Request): void; + + finalize?(req: express.Request): void; + + pre_render?(req: express.Request): void; + + post_render?(req: express.Request): void; + + options?: any; + } + + /** + * Node.js middleware for serving a favicon. + */ + function debug(app: express.Application, settings?: { + /** + * How deep to recurse through printed objects. This is the default unless the + * print_obj function is passed an options object with a 'depth' property. + */ + depth?: number; + + /** + * Absolute path to a css file to include and override EDT's default css. + */ + theme?: string; + + /** + * Additional panels to show. + */ + extra_panels?: CustomPanel[]; + + /** + * Allows changing the default panel. + */ + panels?: string[]; + + /** + * Path to render standalone express-debug. + */ + path?: string; + + /** + * If you need to add arbitrary attributes to the containing element of EDT, + * this allows you to. + */ + extra_attrs?: string; + + /** + * Global option to determine sort order of printed object values. false for + * default order, true for basic default sort, or a function to use for sort. + */ + sort?: boolean | ((a: number, b: number) => number); + + }): void; + + export = debug; +} diff --git a/formidable/formidable.d.ts b/formidable/formidable.d.ts index ba0ed81228..d1cbb16f6d 100644 --- a/formidable/formidable.d.ts +++ b/formidable/formidable.d.ts @@ -25,7 +25,7 @@ declare module "formidable" { onPart: (part: Part) => void; handlePart(part: Part): void; - parse(req: http.ServerRequest, callback?: (err: any, fields: Fields, files: Files) => any): void; + parse(req: http.IncomingMessage, callback?: (err: any, fields: Fields, files: Files) => any): void; } export interface Fields { diff --git a/ftp/ftp-tests.ts b/ftp/ftp-tests.ts new file mode 100644 index 0000000000..2e37e53f99 --- /dev/null +++ b/ftp/ftp-tests.ts @@ -0,0 +1,28 @@ +/// +/// + +import Client = require("ftp"); +import fs = require("fs"); + +var c = new Client(); +c.on('ready', (): void => { + c.get('foo.txt', function(err: Error, stream: NodeJS.ReadableStream): void { + if (err) throw err; + stream.once('close', function(): void { + c.end(); + }); + stream.pipe(fs.createWriteStream('foo.local-copy.txt')); + }); +}); +// connect to localhost:21 as anonymous +c.connect(); + +c.connect({ + host: "127.0.0.1", + port: 21, + username: "Boo", + password: "secret" +}); + + + diff --git a/ftp/ftp.d.ts b/ftp/ftp.d.ts new file mode 100644 index 0000000000..764505037d --- /dev/null +++ b/ftp/ftp.d.ts @@ -0,0 +1,294 @@ +// Type definitions for ftp 0.3.8 +// Project: https://github.com/mscdex/node-ftp +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "ftp" { + + import events = require("events"); + import tls = require("tls"); + + module Client { + + /** + * Options for Client#connect() + */ + export interface Options { + /** + * The hostname or IP address of the FTP server. Default: 'localhost' + */ + host?: string; + /** + * The port of the FTP server. Default: 21 + */ + port?: number; + /** + * Set to true for both control and data connection encryption, 'control' for control connection encryption only, or 'implicit' for + * implicitly encrypted control connection (this mode is deprecated in modern times, but usually uses port 990) Default: false + */ + secure?: string|boolean; + /** + * Additional options to be passed to tls.connect(). Default: (none) + */ + secureOptions?: tls.ConnectionOptions; + /** + * Username for authentication. Default: 'anonymous' + */ + user?: string; + /** + * Password for authentication. Default: 'anonymous@' + */ + password?: string; + /** + * How long (in milliseconds) to wait for the control connection to be established. Default: 10000 + */ + connTimeout?: number; + /** + * How long (in milliseconds) to wait for a PASV data connection to be established. Default: 10000 + */ + pasvTimeout?: number; + /** + * How often (in milliseconds) to send a 'dummy' (NOOP) command to keep the connection alive. Default: 10000 + */ + keepalive?: number; + } + + /** + * Element returned by Client#list() + */ + export interface ListingElement { + /** + * A single character denoting the entry type: 'd' for directory, '-' for file (or 'l' for symlink on **\*NIX only**). + */ + "type": string; + /** + * The name of the entry + */ + name: string; + /** + * The size of the entry in bytes + */ + size: string; + /** + * The last modified date of the entry + */ + date: Date; + /** + * The various permissions for this entry **(*NIX only)** + */ + rights?: { + /** + * An empty string or any combination of 'r', 'w', 'x'. + */ + user: string; + /** + * An empty string or any combination of 'r', 'w', 'x'. + */ + group: string; + /** + * An empty string or any combination of 'r', 'w', 'x'. + */ + other: string; + }; + /** + * The user name or ID that this entry belongs to **(*NIX only)**. + */ + owner?: string; + /** + * The group name or ID that this entry belongs to **(*NIX only)**. + */ + group?: string; + /** + * For symlink entries, this is the symlink's target **(*NIX only)**. + */ + target?: string; + /** + * True if the sticky bit is set for this entry **(*NIX only)**. + */ + sticky?: boolean; + } + } + + + /** + * FTP client. + * + * Events: + * @event greeting(< string >msg) - Emitted after connection. msg is the text the server sent upon connection. + * @event ready() - Emitted when connection and authentication were sucessful. + * @event close(< boolean >hadErr) - Emitted when the connection has fully closed. + * @event end() - Emitted when the connection has ended. + * @event error(< Error >err) - Emitted when an error occurs. In case of protocol-level errors, err contains + * a 'code' property that references the related 3-digit FTP response code. + */ + class Client extends events.EventEmitter { + + /** + * Creates and returns a new FTP client instance. + */ + constructor(); + + /** + * Connects to an FTP server. + */ + connect(config?: Client.Options): void; + + /** + * Closes the connection to the server after any/all enqueued commands have been executed. + */ + end(): void; + + /** + * Closes the connection to the server immediately. + */ + destroy(): void; + + /** + * Retrieves the directory listing of path. + * @param path defaults to the current working directory. + * @param useCompression defaults to false. + */ + list(path: string, useCompression: boolean, callback: (error: Error, listing: Client.ListingElement[]) => void): void; + list(path: string, callback: (error: Error, listing: Client.ListingElement[]) => void): void; + list(useCompression: boolean, callback: (error: Error, listing: Client.ListingElement[]) => void): void; + list(callback: (error: Error, listing: Client.ListingElement[]) => void): void; + + /** + * Retrieves a file at path from the server. useCompression defaults to false + */ + get(path: string, callback: (error: Error, stream: NodeJS.ReadableStream) => void): void; + get(path: string, useCompression: boolean, callback: (error: Error, stream: NodeJS.ReadableStream) => void): void; + + /** + * Sends data to the server to be stored as destPath. + * @param input can be a ReadableStream, a Buffer, or a path to a local file. + * @param destPath + * @param useCompression defaults to false. + */ + put(input: NodeJS.ReadableStream|Buffer|string, destPath: string, useCompression: boolean, callback: (error: Error) => void): void; + put(input: NodeJS.ReadableStream|Buffer|string, destPath: string, callback: (error: Error) => void): void; + + /** + * Same as put(), except if destPath already exists, it will be appended to instead of overwritten. + * @param input can be a ReadableStream, a Buffer, or a path to a local file. + * @param destPath + * @param useCompression defaults to false. + */ + append(input: NodeJS.ReadableStream|Buffer|string, destPath: string, useCompression: boolean, callback: (error: Error) => void): void; + append(input: NodeJS.ReadableStream|Buffer|string, destPath: string, callback: (error: Error) => void): void; + + /** + * Renames oldPath to newPath on the server + */ + rename(oldPath: string, newPath: string, callback: (error: Error) => void): void; + + /** + * Logout the user from the server. + */ + logout(callback: (error: Error) => void): void; + + /** + * Delete a file on the server + */ + delete(path: string, callback: (error: Error) => void): void; + + /** + * Changes the current working directory to path. callback has 2 parameters: < Error >err, < string >currentDir. + * Note: currentDir is only given if the server replies with the path in the response text. + */ + cwd(path: string, callback: (error: Error, currentDir?: string) => void): void; + + /** + * Aborts the current data transfer (e.g. from get(), put(), or list()) + */ + abort(callback: (error: Error) => void): void; + + /** + * Sends command (e.g. 'CHMOD 755 foo', 'QUOTA') using SITE. callback has 3 parameters: + * < Error >err, < _string >responseText, < integer >responseCode. + */ + site(command: string, callback: (error: Error, responseText: string, responseCode: number) => void): void; + + /** + * Retrieves human-readable information about the server's status. + */ + status(callback: (error: Error, status: string) => void): void; + + /** + * Sets the transfer data type to ASCII. + */ + ascii(callback: (error: Error) => void): void; + + /** + * Sets the transfer data type to binary (default at time of connection). + */ + binary(callback: (error: Error) => void): void; + + /** + * Optional "standard" commands (RFC 959) + * Creates a new directory, path, on the server. recursive is for enabling a 'mkdir -p' algorithm and defaults to false + */ + mkdir(path: string, recursive: boolean, callback: (error: Error) => void): void; + mkdir(path: string, callback: (error: Error) => void): void; + + + /** + * Optional "standard" commands (RFC 959) + * Removes a directory, path, on the server. If recursive, this call will delete the contents of the directory if it is not empty + */ + rmdir(path: string, recursive: boolean, callback: (error: Error) => void): void; + rmdir(path: string, callback: (error: Error) => void): void; + + /** + * Optional "standard" commands (RFC 959) + * Changes the working directory to the parent of the current directory + */ + cdup(callback: (error: Error) => void): void; + + /** + * Optional "standard" commands (RFC 959) + * Retrieves the current working directory + */ + pwd(callback: (error: Error, path: string) => void): void; + + /** + * Optional "standard" commands (RFC 959) + * Retrieves the server's operating system. + */ + system(callback: (error: Error, OS: string) => void): void; + + /** + * Optional "standard" commands (RFC 959) + * Similar to list(), except the directory is temporarily changed to path to retrieve the directory listing. + * This is useful for servers that do not handle characters like spaces and quotes in directory names well for the LIST command. + * This function is "optional" because it relies on pwd() being available. + */ + listSafe(path: string, useCompression: boolean, callback: (error: Error, listing: Client.ListingElement[]) => void): void; + listSafe(path: string, callback: (error: Error, listing: Client.ListingElement[]) => void): void; + listSafe(useCompression: boolean, callback: (error: Error, listing: Client.ListingElement[]) => void): void; + listSafe(callback: (error: Error, listing: Client.ListingElement[]) => void): void; + + /** + * Extended commands (RFC 3659) + * Retrieves the size of path + */ + size(path: string, callback: (error: Error, size: number) => void): void; + + /** + * Extended commands (RFC 3659) + * Retrieves the last modified date and time for path + */ + lastMod(path: string, callback: (error: Error, lastMod: Date) => void): void; + + /** + * Extended commands (RFC 3659) + * Sets the file byte offset for the next file transfer action (get/put) to byteOffset + */ + restart(byteOffset: number, callback: (error: Error) => void): void; + + } + + export = Client; +} diff --git a/ftpd/ftpd-tests.ts b/ftpd/ftpd-tests.ts new file mode 100644 index 0000000000..9d8485a9ef --- /dev/null +++ b/ftpd/ftpd-tests.ts @@ -0,0 +1,32 @@ +/// + +import ftpd = require("ftpd"); + +var options: ftpd.FtpServerOptions = { + pasvPortRangeStart: 4000, + pasvPortRangeEnd: 5000, + getInitialCwd: function(connection: ftpd.FtpConnection, callback: (error: Error, path: string) => void): void { + callback(null, "boo"); + }, + getRoot: function(connection: ftpd.FtpConnection): string { + return '/'; + } +}; + +var host: string = '10.0.0.42'; + +var server = new ftpd.FtpServer(host, options); + +server.on('client:connected', function(conn: ftpd.FtpConnection): void { + conn.on('command:user', function(user: string, success: () => void, failure: () => void): void { + success(); + }); + conn.on('command:pass', function( + pass: string, + success: (username: string, fs?: ftpd.FtpFileSystem) => void, + failure: () => void) { + success("Rogier"); + }); +}); + +server.listen(21); diff --git a/ftpd/ftpd.d.ts b/ftpd/ftpd.d.ts new file mode 100644 index 0000000000..ac0123256a --- /dev/null +++ b/ftpd/ftpd.d.ts @@ -0,0 +1,202 @@ +// Type definitions for ftpd 0.2.11 +// Project: https://github.com/sstur/nodeftpd +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "ftpd" { + + import events = require("events"); + import fs = require("fs"); + import net = require("net"); + import tls = require("tls"); + + /** + * Options for FtpServer constructor + */ + export interface FtpServerOptions { + /** + * Gets the initial working directory for the user. Called after user is authenticated + * Typical cases where you would want/need the callback involve retrieving configurations from external datasources and suchlike. + */ + getInitialCwd: (connection: FtpConnection, callback?: (error: Error, path: string) => void) => void|string; + /** + * Gets the root directory for the user relative to the CWD. Called after getInitialCwd. The user is not able to escape this directory. + * Typical cases where you would want/need the callback involve retrieving configurations from external datasources and suchlike. + */ + getRoot: (connection: FtpConnection, callback?: (error: Error, path: string) => void) => void|string; + /** + * If set to true, then files which the client uploads are buffered in memory and then written to disk using writeFile. + * If false, files are written using writeStream. + */ + useWriteFile?: boolean; + /** + * If set to true, then files which the client uploads are slurped using 'readFile'. + * If false, files are read using readStream. + */ + useReadFile?: boolean; + /** + * Determines the maximum file size (in bytes) for which uploads are buffered in memory before being written to disk. + * Has an effect only if useWriteFile is set to true. + * If uploadMaxSlurpSize is not set, then there is no limit on buffer size. + */ + uploadMaxSlurpSize?: number; + /** + * The maximum number of concurrent calls to fs.stat which will be made when processing a LIST request. Default 5. + */ + maxStatsAtOnce?: number; + /** + * A function which can be used as the argument of an array's sort method. Used to sort filenames for directory listings. + * See [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort] for more info. + */ + filenameSortFunc?: (a: string, b: string) => number; + /** + * A function which is applied to each filename before sorting. + * If set to false, filenames are unaltered. + */ + filenameSortMap?: ((a: string) => string) | boolean; + /** + * If this is set, then filenames are not sorted in responses to the LIST and NLST commands. + */ + dontSortFilenames?: boolean; + /** + * If set to true, then LIST and NLST treat the characters ? and * as literals instead of as wildcards. + */ + noWildcards?: boolean; + /** + * If this is set, the server will allow explicit TLS authentication. Value should be a dictionary which is suitable as the options argument of tls.createServer. + */ + tlsOptions?: tls.TlsOptions; + /** + * If this is set to true, and tlsOptions is also set, then the server will not allow logins over non-secure connections. + * Default false + */ + tlsOnly?: boolean; + /** + * I obviously set this to true when tlsOnly is on -someone needs to update this. + */ + allowUnauthorizedTls?: boolean; + /** + * Integer, specifies the lower-bound port (min port) for creating PASV connections + */ + pasvPortRangeStart?: number; + /** + * Integer, specifies the upper-bound port (max port) for creating PASV connections + */ + pasvPortRangeEnd?: number; + } + + /** + * Represents one Ftp connection. Incomplete type definition. + * + * @event command:user (username: string, success: () => void, failure: () => void) + * @event command:pass (password: string, success: (username: string, fs?: FtpFileSystem) => void, failure: () => void) + * The server raises a command:pass event which is given pass, success and failure arguments. + * On successful login, success should be called with a username argument. It may also optionally + * be given a second argument, which should be an object providing an implementation of the API for Node's fs module. + */ + export class FtpConnection extends events.EventEmitter { + server: FtpServer; + socket: net.Socket; + pasv: net.Server; + dataSocket: net.Socket; // the actual data socket + mode: string; + username: string; + cwd: string; + root: string; + hasQuit: boolean; + // State for handling TLS upgrades. + secure: boolean; + pbszReceived: boolean; + } + + + /** + * Optional mock fs implementation to set in the command:pass event of FtpConnection + */ + export interface FtpFileSystem { + unlink: (path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; + readdir: (path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void) => void; + mkdir: ((path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void) + | ((path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void) => void) + | ((path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void) => void); + open: ((path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void) + | ((path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void) + | ((path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any) => void); + close: (fd: number, callback?: (err?: NodeJS.ErrnoException) => void) => void; + rmdir: (path: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; + rename: (oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void) => void; + /** + * specific object properties: { mode, isDirectory(), size, mtime } + */ + stat: (path: string, callback?: (err: NodeJS.ErrnoException, stats: fs.Stats) => any) => void; + /** + * if useReadFile option is not set or is false + */ + createReadStream?: (path: string, options?: { + flags?: string; + encoding?: string; + fd?: string; + mode?: string; + bufferSize?: number; + }) => fs.ReadStream; + /** + * if useWriteFile option is not set or is false + */ + createWriteStream?: (path: string, options?: { + flags?: string; + encoding?: string; + string?: string; + }) => fs.WriteStream; + /** + * if useReadFile option is set to 'true' + */ + readFile?: + ((filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void) => void) + | ((filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void) => void) + | ((filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void) => void) + | ((filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void ) => void); + /** + * if useWriteFile option is set to 'true' + */ + writeFile?: + ((filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void) => void) + | ((filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void) => void) + | ((filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void) => void); + + } + + /** + * FTP server + * + * Events: + * @event close net.Server close event + * @event error net.Server error event + * @event client:connected (connection: FtpConnection) + */ + export class FtpServer extends events.EventEmitter { + + /** + * @param host host is a string representation of the IP address clients use to connect to the FTP server. + * It's imperative that this actually reflects the remote IP the clients use to access the server, + * as this IP will be used in the establishment of PASV data connections. If this IP is not the one clients use to connect, + * you will see some strange behavior from the client side (hangs). + * @param options See test.js for a simple example. + */ + constructor(host: string, options: FtpServerOptions); + + /** + * Start listening, see net.Server.listen() + */ + public listen(port: number, host?: string, backlog?: number, listeningListener?: () => void): void; + + /** + * Stop listening + */ + public close(callback?: () => void): void; + } + + + +} diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index eb85899c4b..3ba451c8a5 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1345,6 +1345,55 @@ 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 Autocomplete extends MVCObject { constructor (inputField: HTMLInputElement, opts?: AutocompleteOptions); diff --git a/grecaptcha/grecaptcha-tests.ts b/grecaptcha/grecaptcha-tests.ts new file mode 100644 index 0000000000..cfc86e71b6 --- /dev/null +++ b/grecaptcha/grecaptcha-tests.ts @@ -0,0 +1,21 @@ +/// + +var params: ReCaptchaV2.Parameters = { + "sitekey": "mySuperSecretKey", + "theme": "black", // no type-checking here. + "type": "image", + "tabindex": 5, + "callback": (response: string) => { }, + "expired-callback": () => { }, +} + +var id1: number = grecaptcha.render("foo"); +var id2: number = grecaptcha.render("foo", params); +var id3: number = grecaptcha.render(document.getElementById("foo")); +var id4: number = grecaptcha.render(document.getElementById("foo"), params); + +// response takes a number and returns a string +var response1: string = grecaptcha.getResponse(id1); + +// reset takes a number +grecaptcha.reset(id1); diff --git a/grecaptcha/grecaptcha.d.ts b/grecaptcha/grecaptcha.d.ts new file mode 100644 index 0000000000..e246aaf17b --- /dev/null +++ b/grecaptcha/grecaptcha.d.ts @@ -0,0 +1,67 @@ +// Type definitions for Google Recaptcha v2 +// Project: https://www.google.com/recaptcha +// Definitions by: Kristof Mattei +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var grecaptcha: ReCaptchaV2.ReCaptcha; + +declare module ReCaptchaV2 +{ + class ReCaptcha + { + /** + * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. + * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. + * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. + * @return the ID of the newly created widget. + **/ + render(container: (string | HTMLElement), parameters?: Parameters): number; + /** + * Resets the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + **/ + reset(opt_widget_id?: number): void; + /** + * Gets the response for the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + * @return the response of the reCAPTCHA widget. + **/ + getResponse(opt_widget_id?: number): string; + } + + interface Parameters + { + /** + * Your sitekey. + **/ + sitekey: string; + /** + * Optional. The color theme of the widget. + * Accepted values: "light", "dark" + * @default "light" + **/ + theme?: string; + /** + * Optional. The type of CAPTCHA to serve. + * Accepted values: "audio ", "image" + * @default "image" + **/ + type?: string; + /** + * Optional. The tabindex of the widget and challenge. + * If other elements in your page use tabindex, it should be set to make user navigation easier. + **/ + tabindex?: number; + /** + * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. + * The user's response, g-recaptcha-response, will be the input for your callback function. + **/ + callback?: (response: string) => void; + /** + * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. + **/ + // Notice to the reader + // I need to surround this object with quotes, this will however break intellisense in VS 2013. + "expired-callback"?: () => void; + } +} diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 0589036371..11ad81d2dd 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -21,6 +21,12 @@ plugin.register.attributes = { version: "1.0.0" }; +// optional options parameter +server.register({}, function (err) {}); + +// optional options.routes.vhost parameter +server.register({}, { select: 'api', routes: { prefix: '/prefix' } }, function (err) {}); + //server.pack.register(plugin, (err: Object) => { // if (err) { throw err; } //}); @@ -76,5 +82,18 @@ server.route([{ } }]); +// config.validate parameters should be optional +server.route([{ + method: 'GET', + path: '/hello2', + handler: function(request: Hapi.Request, reply: Function) { + reply('hello world2'); + }, + config: { + validate: { + } + } +}]); + // Start the server server.start(); diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 61a2ef2d5a..de8dba6b8b 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -147,11 +147,11 @@ declare module "hapi" { }; /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/ - mime: any; + mime?: any; /** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */ - minimal: boolean; + minimal?: boolean; /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/ - plugins: IDictionary; + plugins?: IDictionary; } @@ -568,7 +568,7 @@ declare module "hapi" { optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - headers: boolean | IJoi | IValidationFunction; + headers?: boolean | IJoi | IValidationFunction; /** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed: @@ -579,7 +579,7 @@ declare module "hapi" { valuethe object containing the path parameters. optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - params: boolean | IJoi | IValidationFunction; + params?: boolean | IJoi | IValidationFunction; /** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed: trueany query parameters allowed (no validation performed).This is the default. falseno query parameters allowed. @@ -588,7 +588,7 @@ declare module "hapi" { valuethe object containing the query parameters. optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - query: boolean | IJoi | IValidationFunction; + query?: boolean | IJoi | IValidationFunction; /** validation rules for an incoming request payload (request body).Values allowed: trueany payload allowed (no validation performed).This is the default. falseno payload allowed. @@ -597,9 +597,9 @@ declare module "hapi" { valuethe object containing the payload object. optionsthe server validation options. next(err, value)the callback function called when validation is completed. */ - payload: boolean | IJoi | IValidationFunction; + payload?: boolean | IJoi | IValidationFunction; /** an optional object with error fields copied into every validation error response. */ - errorFields: any; + errorFields?: any; /** determines how to handle invalid requests.Allowed values are: 'error'return a Bad Request (400) error response.This is the default value. 'log'log the error but continue processing the request. @@ -609,9 +609,9 @@ declare module "hapi" { replythe continuation reply interface. sourcethe source of the invalid field (e.g. 'path', 'query', 'payload'). errorthe error object prepared for the client response (including the validation function error under error.data). */ - failAction: string | IRouteFailFunction; + failAction?: string | IRouteFailFunction; /** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */ - options: any; + options?: any; }; /** define timeouts for processing durations: */ timeout?: { @@ -726,7 +726,7 @@ declare module "hapi" { a relative or absolute file path string (relative paths are resolved based on the route files configuration). a function with the signature function(request) which returns the relative or absolute file path. an object with the following options */ - file: string | IRequestHandler |IFileHandlerConfig; + file?: string | IRequestHandler |IFileHandlerConfig; /** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. @@ -738,7 +738,7 @@ declare module "hapi" { redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false. lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/ - directory: { + directory?: { path: string |Array | IRequestHandler | IRequestHandler>; index?: boolean; listing?: boolean; @@ -748,7 +748,7 @@ declare module "hapi" { defaultExtension?: string; }; proxy?: IProxyHandlerConfig; - view: string | { + view?: string | { template: string; context: { payload: any; @@ -757,7 +757,7 @@ declare module "hapi" { pre: any; } }; - config: { + config?: { handler: any; bind: any; app: any; @@ -2051,11 +2051,13 @@ declare module "hapi" { register(plugins: any|any[], options: { select: string|string[]; routes: { - prefix: string; vhost: string|string[] + prefix: string; vhost?: string|string[] }; } , callback: (err: any) => void):void; + register(plugins: any|any[], callback: (err: any) => void):void; + /**server.render(template, context, [options], callback) Utilizes the server views manager to render a template where: template - the template filename and path, relative to the views manager templates path (path or relativeTo). diff --git a/he/he-tests.ts b/he/he-tests.ts new file mode 100644 index 0000000000..395eb94ef0 --- /dev/null +++ b/he/he-tests.ts @@ -0,0 +1,52 @@ +/// + +import he = require('he'); + +function main() { + var result: string; + + result = he.encode('foo \xa9 bar \u2260 baz qux'); + // 'foo © bar ≠ baz qux' + + he.encode('foo \0 bar'); + // 'foo \0 bar' + + // Passing an `options` object to `encode`, to explicitly disallow named references: + he.encode('foo \xa9 bar \u2260 baz qux', { + 'useNamedReferences': false + }); + + he.encode('foo \xa9 bar \u2260 baz qux', { + 'encodeEverything': true + }); + + he.encode('foo \xa9 bar \u2260 baz qux', { + 'encodeEverything': true, + 'useNamedReferences': true + }); + + he.encode('\x01', { + 'strict': false + }); + // '' + + he.encode('foo © and & ampersand', { + 'allowUnsafeSymbols': true + }); + + // Override the global default setting: + he.encode.options.useNamedReferences = true; + + he.decode('foo © bar ≠ baz 𝌆 qux'); + + he.decode('foo&bar', { + 'isAttributeValue': false + }); + + he.decode('foo&bar', { + 'strict': false + }); + + he.decode.options.isAttributeValue = true; + he.escape(''); +} diff --git a/he/he.d.ts b/he/he.d.ts new file mode 100644 index 0000000000..6c96840c2c --- /dev/null +++ b/he/he.d.ts @@ -0,0 +1,114 @@ +// Type definitions for he v0.5.0 +// Project: https://github.com/mathiasbynens/he +// Definitions by: Simon Edwards +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// he - "HTML Entities" - A high quality pair of HTML encode and decode functions. + +declare module "he" { + + var version: string; + + interface EncodeOptions { + /** + * The default value for the useNamedReferences option is false. This + * means that encode() will not use any named character references + * (e.g. ©) in the output — hexadecimal escapes (e.g. ©) will + * be used instead. Set it to true to enable the use of named references. + */ + useNamedReferences?: boolean; + + /** + * The default value for the encodeEverything option is false. This means + * that encode() will not use any character references for printable ASCII + * symbols that don’t need escaping. Set it to true to encode every symbol + * in the input string. When set to true, this option takes precedence over + * allowUnsafeSymbols (i.e. setting the latter to true in such a case has + * no effect). + */ + encodeEverything?: boolean; + + /** + * The default value for the strict option is false. This means that + * encode() will encode any HTML text content you feed it, even if it + * contains any symbols that cause parse errors. To throw an error when such + * invalid HTML is encountered, set the strict option to true. This option + * makes it possible to use he as part of HTML parsers and HTML validators. + */ + strict?: boolean; + + /** + * The default value for the allowUnsafeSymbols option is false. This means + * that characters that are unsafe for use in HTML content (&, <, >, ", ', + * and `) will be encoded. When set to true, only non-ASCII characters will + * be encoded. If the encodeEverything option is set to true, this option + * will be ignored. + */ + allowUnsafeSymbols?: boolean; + } + + interface Encode { + /** + * Encode a string of text + * + * This function takes a string of text and encodes (by default) any symbols + * that aren’t printable ASCII symbols and &, <, >, ", ', and `, replacing + * them with character references. + * + * As long as the input string contains allowed code points only, the return + * value of this function is always valid HTML. Any (invalid) code points + * that cannot be represented using a character reference in the input are + * not encoded. + */ + (text: string, options?: EncodeOptions): string; + + options: EncodeOptions; + } + var encode: Encode; + + interface DecodeOptions { + /** + * The default value for the isAttributeValue option is false. This means + * that decode() will decode the string as if it were used in a text + * context in an HTML document. HTML has different rules for parsing + * character references in attribute values — set this option to true to + * treat the input string as if it were used as an attribute value. + */ + isAttributeValue?: boolean; + + /** + * The default value for the strict option is false. This means that + * decode() will decode any HTML text content you feed it, even if it + * contains any entities that cause parse errors. To throw an error when + * such invalid HTML is encountered, set the strict option to true. This + * option makes it possible to use he as part of HTML parsers and HTML + * validators. + */ + strict?: boolean; + } + + interface Decode { + /** + * Decode a string of HTML text + * + * This function takes a string of HTML and decodes any named and numerical + * character references in it using the algorithm described in section + * 12.2.4.69 of the HTML spec. + */ + (html: string, options?: DecodeOptions): string; + + options: DecodeOptions; + } + var decode: Decode; + + /** + * Escape XML entities + * + * This function takes a string of text and escapes it for use in text + * contexts in XML or HTML documents. Only the following characters are + * escaped: &, <, >, ", ', and `. + */ + function escape(text: string): string; + + var unescape: Decode; +} diff --git a/imgur-rest-api/imgur-rest-api-tests.ts b/imgur-rest-api/imgur-rest-api-tests.ts new file mode 100644 index 0000000000..247885557d --- /dev/null +++ b/imgur-rest-api/imgur-rest-api-tests.ts @@ -0,0 +1,103 @@ +/// + +function testAccount(account: ImgurRestApi.Account) : ImgurRestApi.Account { + return account; +} + +function testAccountSettings(accountSettings: ImgurRestApi.AccountSettings) : ImgurRestApi.AccountSettings { + return accountSettings; +} + +function testAlbum(album: ImgurRestApi.Album) : ImgurRestApi.Album { + return album; +} + +function testAlbumImages(album: ImgurRestApi.Album) : ImgurRestApi.Image { + return album.images[0]; +} + +function testComment(comment: ImgurRestApi.Comment) : ImgurRestApi.Comment { + return comment; +} + +function testConversation(conversation: ImgurRestApi.Conversation) : ImgurRestApi.Conversation { + return conversation; +} + +function testCustomGallery(customGallery: ImgurRestApi.CustomGallery) : ImgurRestApi.CustomGallery { + return customGallery; +} + +function testGalleryItem(galleryItem: ImgurRestApi.GalleryItem) : ImgurRestApi.GalleryItem { + return galleryItem; +} + +function testGalleryAlbum(galleryItem: ImgurRestApi.GalleryItem) : ImgurRestApi.GalleryAlbum { + if(galleryItem.is_album) { + var galleryAlbum = galleryItem; + return galleryAlbum; + } + return null; +} + +function testGalleryImage(galleryItem: ImgurRestApi.GalleryItem) : ImgurRestApi.GalleryImage { + if(!galleryItem.is_album) { + var galleryImage = galleryItem; + return galleryImage; + } + return null; +} + +function testGalleryProfile(galleryProfile: ImgurRestApi.GalleryProfile) : ImgurRestApi.GalleryProfile { + return galleryProfile; +} + +function testImage(image: ImgurRestApi.Image) : ImgurRestApi.Image { + return image; +} + +function testMemeMeta(meta: ImgurRestApi.MemeMetadata) : ImgurRestApi.MemeMetadata { + return meta; +} + +function testMessage(message: ImgurRestApi.Message) : ImgurRestApi.Message { + return message; +} + +function testAccountNotificationsReply(accountNotif: ImgurRestApi.AccountNotifications) : ImgurRestApi.Notification { + return accountNotif.replies[0]; +} + +function testAccountNotificationsMessage(accountNotif: ImgurRestApi.AccountNotifications) : ImgurRestApi.Notification { + return accountNotif.messages[0]; +} + +function testTag(tag: ImgurRestApi.Tag) : ImgurRestApi.Tag { + return tag; +} + +function testTagVote(tagVote: ImgurRestApi.TagVote) : ImgurRestApi.TagVote { + return tagVote; +} + +function testTopic(topic: ImgurRestApi.Topic) : ImgurRestApi.Topic { + return topic; +} + +function testVote(vote: ImgurRestApi.Vote) : ImgurRestApi.Vote { + return vote; +} + +function testResponseWithError(response: ImgurRestApi.Response) : ImgurRestApi.Error { + if(response.success === false) { + return response.data; + } + return null; +} + +function testResponseWithValue(response: ImgurRestApi.Response) : ImgurRestApi.GalleryProfile { + if(response.success === true) { + return response.data; + } + return null; +} diff --git a/imgur-rest-api/imgur-rest-api.d.ts b/imgur-rest-api/imgur-rest-api.d.ts new file mode 100644 index 0000000000..2726006568 --- /dev/null +++ b/imgur-rest-api/imgur-rest-api.d.ts @@ -0,0 +1,252 @@ +// Type definitions for Imgur REST API v3 +// Project: https://api.imgur.com/ +// Definitions by: Luke William Westby +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ImgurRestApi { + + interface Response { + data: any; //T|Error; + status: number; + success: boolean; + } + + interface Account { + id: number; + url: string; + bio: string; + reputation: number; + created: number; + pro_expiration: any; //number|boolean; + } + + interface AccountSettings { + email: string; + high_quality: boolean; + public_images: boolean; + album_privacy: string; + pro_expiration: any; //number|boolean; + accepted_gallery_terms: boolean; + active_emails: Array; + messaging_enabled: boolean; + blocked_users: Array; + } + + interface Album { + id: string; + title: string; + description: string; + datetime: number; + cover: string; + cover_width: number; + cover_height: number; + account_url?: string; + account_id?: number; + privacy: string; + layout: string; + views: number; + link: string; + favorite: boolean; + nsfw?: boolean; + section: string; + order: number; + deletehash?: string; + images_count: number; + images: Array; + } + + interface BlockedUser { + blocked_id: number; + blocked_url: string; + } + + interface Comment { + id: number; + image_id: string; + comment: string; + author: string; + author_id: number; + on_album: boolean; + album_cover: string; + ups: number; + downs: number; + points: number; + datetime: number; + parent_id: number; + deleted: boolean; + vote?: string; + children: Array + } + + interface Conversation { + id: number; + last_message_preview: string; + datetime: number; + with_account_id: number; + with_account: string; + message_count: number; + messages?: Array; + done?: boolean; + page?: number; + } + + interface CustomGallery { + account_url: string; + link: string; + tags: Array + item_count: number; + items: Array; + } + + interface GalleryItem { + id: string; + title: string; + description: string; + datetime: number; + account_url?: string; + account_id?: number; + ups: number; + downs: number; + score: number; + is_album: boolean; + views: number; + link: string; + vote?: string; + favorite: boolean; + nsfw?: boolean; + comment_count: number; + topic: string; + topic_id: number; + } + + interface GalleryAlbum extends GalleryItem { + cover: string; + cover_width: number; + cover_height: number; + privacy: string; + layout: string; + images_count: number; + images: Array; + } + + interface GalleryImage extends GalleryItem { + type: string; + animated: boolean; + width: number; + height: number; + size: number; + bandwidth: number; + deletehash?: string; + gifv?: string; + mp4?: string; + webm?: string; + looping?: boolean; + section: string; + } + + interface GalleryProfile { + total_gallery_comments: number; + total_gallery_favorites: number; + total_gallery_submissions: number; + trophies: Array; + } + + interface Trophy { + id: number; + name: string; + name_clean: string; + description: string; + data: string; + data_link: string; + datetime: number; + image: string; + } + + interface Image { + id: string; + title: string; + description: string; + datetime: number; + type: string; + animated: boolean; + width: number; + height: number; + size: number; + views: number; + bandwidth: number; + deletehash?: string; + name?: string; + section: string; + link: string; + gifv?: string; + mp4?: string; + webm?: string; + looping?: boolean; + vote?: string; + favorite: boolean; + nsfw?: boolean; + account_url?: string; + account_id?: number; + } + + interface MemeMetadata { + meme_name: string; + top_text: string; + bottom_text: string; + bg_image: string; + } + + interface Message { + id: number; + from: string; + account_id: number; + sender_id: number; + body: string; + conversation_id: number; + datetime: number; + } + + interface Notification { + id: number; + account_id: number; + viewed: boolean; + content: T; + } + + interface AccountNotifications { + replies: Array>; + messages: Array>; + } + + interface Tag { + name: string; + followers: number; + total_items: number; + following?: boolean; + items: Array + } + + interface TagVote { + ups: number; + downs: number; + name: string; + author: string; + } + + interface Topic { + id: number; + name: string; + description: string; + } + + interface Vote { + ups: number; + downs: number; + } + + interface Error { + error: string; + request: string; + method: string; + } +} diff --git a/jquery-fullscreen/jquery-fullscreen-tests.ts b/jquery-fullscreen/jquery-fullscreen-tests.ts new file mode 100644 index 0000000000..633b3d3934 --- /dev/null +++ b/jquery-fullscreen/jquery-fullscreen-tests.ts @@ -0,0 +1,36 @@ +/// + +// +// Examples from https://github.com/kayahr/jquery-fullscreen-plugin +// + +function enteringFullScreen() { + + $(document).fullScreen(true); + $('#myVideo').fullScreen(true); +} + +function exitingFullScreen() { + + $(document).fullScreen(false); + $('#myVideo').fullScreen(false); +} + + +function queryingFullScreenMode() { + + //The method returns the current fullscreen element (or true if browser doesn't support this) when fullscreen mode is active, + // false if not active or null when the browser does not support fullscreen mode at all + var isFullScreen = $(document).fullScreen() != null; +} + +function fullScreenNotifications() { + + $(document).bind("fullscreenchange", () => { + console.log("Fullscreen " + ($(document).fullScreen() ? "on" : "off")); + }); + + $(document).bind("fullscreenerror", () => { + alert("Browser rejected fullscreen change"); + }); +} \ No newline at end of file diff --git a/jquery-fullscreen/jquery-fullscreen.d.ts b/jquery-fullscreen/jquery-fullscreen.d.ts new file mode 100644 index 0000000000..605b9fb59b --- /dev/null +++ b/jquery-fullscreen/jquery-fullscreen.d.ts @@ -0,0 +1,28 @@ +// Type definitions for jquery-fullscreen 1.1.5 +// Project: https://github.com/kayahr/jquery-fullscreen-plugin +// Definitions by: Bruno Grieder +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JQuery { + + /** + * You can either switch the whole page or a single HTML element to fullscreen mode + * This only works when the code was triggered by a user interaction (For example a onclick event on a button). Browsers don't allow entering fullscreen mode without user interaction. + * Fullscreen mode is always exited via the document but this plugin allows it also via any HTML element. The owner document of the selected HTML element is used + */ + fullScreen(fullScreen: boolean): JQuery | boolean; + + /** + * The method returns the current fullscreen element (or true if browser doesn't support this) when fullscreen mode is active, + * false if not active or null when the browser does not support fullscreen mode at all + */ + fullScreen(): boolean; + + /** + * The plugin provides another method for simple fullscreen mode toggling + */ + toggleFullScreen(): JQuery | boolean; +} + diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts new file mode 100644 index 0000000000..7d23caddfd --- /dev/null +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient-tests.ts @@ -0,0 +1,23 @@ +/// +/// + +var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc' }); +foo.call( + 'bar', ['A parameter', 'B parameter'], + function (result) { alert('Foo bar answered: ' + result.my_answer); }, + function (error) { console.log('There was an error', error); } +); + + +var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc' }); +foo.batch( + function (batch) { + batch.call('bar', ['A parameter', 'B parameter'], function () { }, function () { }); + batch.call('baz', { parameters: 'could be object' }, function () { }, function () { }); + }, + function (all_result_array) { alert('All done.'); }, + function (error_data) { alert('Error in batch response.'); } + ); + +var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc', socketUrl: 'ws://example.com/' }); +foo.call('bar', ['param'], function () { }, function () { }); \ No newline at end of file diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts new file mode 100644 index 0000000000..de008dc092 --- /dev/null +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts @@ -0,0 +1,97 @@ +// Type definitions for jquery.jsonrpc 0.7.0 +// Project: https://github.com/Textalk/jquery.jsonrpcclient.js +// Definitions by: Maksim Karelov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface JsonRpcClientOptions extends JQueryAjaxSettings { + ajaxUrl?: string; + headers?: {[key:string]: any}; + sockerUrl?: string; + onmessage?: () => void; + onopen?: () => void; + onclose?: () => void; + onerror?: () => void; + getSockect?: (onmessageCb: () => void) => WebSocket; +} + +interface JsonRpcClient { + /** + * @fn call + * @memberof JsonRpcClient + * + * @param {string} method The method to run on JSON-RPC server. + * @param {object|array} params The params; an array or object. + * @param {function} successCb A callback for successful request. + * @param {function} errorCb A callback for error. + * + * @return {object} Returns the deferred object that $.ajax returns or {null} for websockets + */ + call(method: string, params: Object | Array, successCb: (result: any) => void, errorCb: (result: any) => void): JQueryDeferred; + + /** + * Notify sends a command to the server that won't need a response. In http, there is probably + * an empty response - that will be dropped, but in ws there should be no response at all. + * + * This is very similar to call, but has no id and no handling of callbacks. + * + * @fn notify + * @memberof JsonRpcClient + * + * @param {string} method The method to run on JSON-RPC server. + * @param {object|array} params The params; an array or object. + * + * @return {object} Returns the deferred object that $.ajax returns or {null} for websockets + */ + notify(method: string, params: Object | Array): JQueryDeferred; + + /** + * Make a batch-call by using a callback. + * + * The callback will get an object "batch" as only argument. On batch, you can call the methods + * "call" and "notify" just as if it was a normal JsonRpcClient object, and all calls will be + * sent as a batch call then the callback is done. + * + * @fn batch + * @memberof JsonRpcClient + * + * @param {function} callback This function will get a batch handler to run call and notify on. + * @param {function} allDoneCb A callback function to call after all results have been handled. + * @param {function} errorCb A callback function to call if there is an error from the server. + * Note, that batch calls should always get an overall success, and the + * only error + */ + batch(callback: (batch: JsonRpcClient) => void, allDoneCb: (result: any) => void, errorCb: (error: any) => void): void; +} + +interface JsonRpcClientFactory { + /** + * @fn new + * @memberof JsonRpcClient + * + * @param {object} options An object stating the backends: + * ajaxUrl A url (relative or absolute) to a http(s) backend. + * headers An object that will be passed along to $.ajax in options.headers + * xhrFields An object that will be passed along to $.ajax in options.xhrFields + * socketUrl A url (relative of absolute) to a ws(s) backend. + * onmessage A socket message handler for other messages (non-responses). + * onopen A socket onopen handler. (Not used for custom getSocket.) + * onclose A socket onclose handler. (Not used for custom getSocket.) + * onerror A socket onerror handler. (Not used for custom getSocket.) + * getSocket A function returning a WebSocket or null. + * It must take an onmessage_cb and bind it to the onmessage event + * (or chain it before/after some other onmessage handler). + * Or, it could return null if no socket is available. + * The returned instance must have readyState <= 1, and if less than 1, + * react to onopen binding. + * timeout (optional) A number of ms to wait before timing out and failing a + * call. If specified a setTimeout will be used to keep track of calls + * made through a websocket. + */ + new (options?: JsonRpcClientOptions): JsonRpcClient; +} + +interface JQueryStatic { + JsonRpcClient: JsonRpcClientFactory; +} \ No newline at end of file diff --git a/jquery.dataTables/jquery.dataTables-1.9.4.d.ts b/jquery.dataTables/jquery.dataTables-1.9.4.d.ts new file mode 100755 index 0000000000..9884b78e29 --- /dev/null +++ b/jquery.dataTables/jquery.dataTables-1.9.4.d.ts @@ -0,0 +1,479 @@ +// Type definitions for JQuery DataTables 1.9.4 +// Project: http://www.datatables.net +// Definitions by: Armin Sander +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// missing: +// - Static methods that are defined in JQueryStatic.fn are not typed. +// - Plugin and extension definitions are not typed. + +interface JQuery +{ + dataTable(param? :DataTables.Options) : DataTables.DataTable; +} + +declare module DataTables +{ + export interface DataTable + { + /// Perform a jQuery selector action on the table's TR elements (from the tbody) and return the resulting jQuery object. + $(selector:string, opts?:RowParams): JQuery; + $(selector:Node[], opts?:RowParams): JQuery; + $(selector:JQuery, opts?:RowParams): JQuery; + + /// Almost identical to $ in operation, but in this case returns the data for the matched rows. + _(selector:string, opts?:RowParams): any[]; + _(selector:Node[], opts?:RowParams): any[]; + _(selector:JQuery, opts?:RowParams): any[]; + + /// Add a single new row or multiple rows of data to the table. + fnAddData(data:any, redraw?:boolean) : number[]; + + /// This function will make DataTables recalculate the column sizes. + fnAdjustColumnSizing(redraw? : boolean) : void; + + /// Quickly and simply clear a table + fnClearTable(redraw? : boolean) : void; + + /// The exact opposite of 'opening' a row, this function will close any rows which are currently 'open'. + fnClose(node: Node) : number; + + /// Remove a row for the table + fnDeleteRow(index: number, callback?: () => void, redraw?: boolean) : any[]; + fnDeleteRow(tr: Node, callback?: () => void, redraw?: boolean) : any[]; + + /// Restore the table to it's original state in the DOM by removing all of DataTables enhancements, + /// alterations to the DOM structure of the table and event listeners. + fnDestroy(remove?: boolean) : void; + + /// Redraw the table + fnDraw(complete? : boolean) : void; + + /// Filter the input based on data + fnFilter(input: string, column? : number, regex?: boolean, smart? : boolean, showGlobal?: boolean, caseInsensitive? : boolean) : void; + + /// Get the data for the whole table, an individual row or an individual cell based on the provided parameters. + fnGetData(row?: Node, col? : number) : any; + fnGetData(row?: number, col? : number) : any; + + /// Get an array of the TR nodes that are used in the table's body. + fnGetNodes(row? : number) : any; // Node[] | Node + + /// Get the array indexes of a particular cell from it's DOM element and column index including hidden columns + fnGetPosition(node: Node) : any; // number | number[] + + /// Check to see if a row is 'open' or not. + fnIsOpen(tr: Node) : boolean; + + /// This function will place a new row directly after a row which is currently on display on the page, + /// with the HTML contents that is passed into the function. + fnOpen(node: Node, html: string, clazz: string) : Node; + fnOpen(node: Node, html: Node, clazz: string) : Node; + fnOpen(node: Node, html: JQuery, clazz: string) : Node; + + /// Change the pagination - provides the internal logic for pagination in a simple API function. + fnPageChange(action: string, redraw?: boolean) : void; + fnPageChange(page: number, redraw?: boolean) : void; + + /// Show a particular column + fnSetColumnVis(column: number, show: boolean, redraw?: boolean) : void; + + /// Get the settings for a particular table for external manipulation + fnSettings() : Settings; + + /// Sort the table by a particular column + fnSort(col: number) : void; + fnSort(col: any[][]) : void; + + /// Attach a sort listener to an element for a given column + fnSortListener(node: Node, column: number, callback? : () => void): void; + + /// Update a table cell or row - this method will accept either a single value to update the cell with, + /// an array of values with one element for each column or an object in the same format as the original data source. + fnUpdate(data: any, row: Node, column?:number, redraw?: boolean, action? : boolean) : number; + fnUpdate(data: any, dataIndex: number, column?:number, redraw?: boolean, action? : boolean) : number; + + /// Provide a common method for plug-ins to check the version of DataTables being used, + /// in order to ensure compatibility. + fnVersionCheck(version: string) : boolean; + } + + export interface Static + { + /// Provide a common method for plug-ins to check the version of DataTables being used, + /// in order to ensure compatibility. + fnVersionCheck(version: string) : boolean; + + /// Check if a TABLE node is a DataTable table already or not. + fnIsDataTable(table: Node) : boolean; + + /// Get all DataTable tables that have been initialised. + fnTables(visible? : boolean) : Node[]; + } + + export interface RowParams + { + /// Select TR elements that meet the current filter criterion ("applied") or all TR elements (i.e. no filter). + filter?: string; + + /// Order of the TR elements in the processed array. + /// Can be either 'current', whereby the current sorting of the table is used, or + /// 'original' whereby the original order the data was read into the table is used. + order?: string; + + /// Limit the selection to the currently displayed page + /// ("current") or not ("all"). If 'current' is given, then order is assumed to be + /// 'current' and filter is 'applied', regardless of what they might be given as. + page?: string; + } + + export interface Options + { + aaData?: any[]; + aaSorting?: any[]; + aaSortingFixed?: any[]; + ajax?: any; + aLengthMenu?: any[]; + aoColumns?: ColumnOptions[]; + aoColumnDefs?: ColumnDef[]; + aoSearchCols?: any[]; + asStripClasses?: string[]; + bAutoWidth?: boolean; + bDeferRender?: boolean; + bDestroy?: boolean; + bFilter?: boolean; + bInfo?: boolean; + bJQueryUI?: boolean; + bLengthChange?: boolean; + bPaginate?: boolean; + bProcessing?: boolean; + bRetrieve?: boolean; + bScrollAutoCss?: boolean; + bScrollCollapse?: boolean; + bScrollInfinite?: boolean; + bServerSide?: boolean; + bSort?: boolean; + bSortCellsTop?: boolean; + bSortClasses?: boolean; + bStateSave?: boolean; + fnCookieCallback?: CookieCallback; + fnCreatedRow?: RowCreatedCallback; + fnDrawCallback?: DrawCallback; + fnFooterCallback?: FooterCallback; + fnFormatNumber?: FormatNumber; + fnHeaderCallback?: HeaderCallback; + fnInfoCallback?: InfoCallback; + fnInitComplete?: InitComplete; + fnPreDrawCallback?: PreDrawCallback; + fnRowCallback?: RowCallback; + + fnStateLoadCallback?: StateLoadCallback; + fnStateLoadParams?: StateLoadParams; + fnStateLoaded?: StateLoaded; + fnStateSaveCallback?: StateSaveCallback; + fnStateSaveParams?: StateSaveParams; + iCookieDuration?: number; + iDeferLoading?: any; + iDisplayLength?: number; + iDisplayStart?: number; + iScrollLoadGap?: number; + iTabIndex?: number; + oLanguage?: LanguageOptions; + oSearch?: any; + sAjaxDataProp?: string; + sAjaxSource?: string; + sCookiePrefix?: string; + sDom?: string; + sPaginationType?: string; + sScrollX?: string; + sScrollXInner?: string; + sScrollY?: string; + sServerMethod? : string; + } + + export interface LanguageOptions + { + oAria? : AriaOptions; + oPaginate? : PaginateOptions; + sEmptyTable?: string; + sInfo?: string; + sInfoEmpty?: string; + sInfoFiltered?: string; + sInfoPostFix?: string; + sInfoThousands?: string; + sLengthMenu?: string; + sLoadingRecords?: string; + sProcessing?: string; + sSearch?: string; + sUrl?: string; + sZeroRecords?: string; + } + + export interface AriaOptions + { + sSortAscending?: string; + sSortDescending?: string; + } + + export interface PaginateOptions + { + sFirst?: string; + sLast?: string; + sNext?: string; + sPrevious?: string; + } + + export interface ColumnOptions + { + aDataSort?: number[]; + asSorting?: string[]; + bSearchable? : boolean; + bSortable? : boolean; + bVisible? : boolean; + _bAutoType? : boolean; + fnCreatedCell?: CreatedCell; + iDataSort?: number; + mData?: any; + mRender?: any; + sCellType?: string; + sClass?: string; + sContentPadding?: string; + sDefaultContent?: string; + sName?: string; + sSortDataType?: string; + sSortingClass?: string; + sTitle?: string; + sType?: string; + sWidth?: string; + } + + export interface ColumnDef extends ColumnOptions + { + aTargets: any[]; + } + + export interface Settings + { + oFeatures : Features; + oScroll: ScrollingSettings; + oLanguage : { fnInfoCallback : InfoCallback; }; + oBrowser : { bScrollOversize : boolean; }; + aanFeatures: Node[][]; + aoData: Row[]; + aiDisplay: number[]; + aiDisplayMaster: number[]; + aoColumns: Column[]; + aoHeader: any[]; + aoFooter: any[]; + asDataSearch: string[]; + oPreviousSearch: any; + aoPreSearchCols: any[]; + aaSorting: any[][]; + aaSortingFixed: any[][]; + asStripeClasses: string[]; + asDestroyStripes: string[]; + sDestroyWidth: number; + aoRowCallback: RowCallback[]; + aoHeaderCallback: HeaderCallback[]; + aoFooterCallback: FooterCallback[]; + aoDrawCallback: DrawCallback[]; + aoRowCreatedCallback: RowCreatedCallback[]; + aoPreDrawCallback: PreDrawCallback[]; + aoInitComplete: InitComplete[]; + aoStateSaveParams: StateSaveParams[]; + aoStateLoadParams: StateLoadParams[]; + aoStateLoaded: StateLoaded[]; + sTableId: string; + nTable: Node; + nTHead: Node; + nTFoot: Node; + nTBody: Node; + nTableWrapper: Node; + bDeferLoading: boolean; + bInitialized: boolean; + aoOpenRows: any[]; + sDom: string; + sPaginationType: string; + iCookieDuration: number; + sCookiePrefix: string; + fnCookieCallback: CookieCallback; + aoStateSave: StateSaveCallback[]; + aoStateLoad: StateLoadCallback[]; + oLoadedState: any; + sAjaxSource: string; + sAjaxDataProp: string; + bAjaxDataGet: boolean; + jqXHR: any; + fnServerData: any; + aoServerParams: any[]; + sServerMethod: string; + fnFormatNumber: FormatNumber; + aLengthMenu: any[]; + iDraw: number; + bDrawing: boolean; + iDrawError: number; + _iDisplayLength: number; + _iDisplayStart: number; + _iDisplayEnd: number; + _iRecordsTotal: number; + _iRecordsDisplay: number; + bJUI: boolean; + oClasses: any; + bFiltered: boolean; + bSorted: boolean; + bSortCellsTop: boolean; + oInit: any; + aoDestroyCallback: any[]; + fnRecordsTotal: () => number; + fnRecordsDisplay: () => number; + fnDisplayEnd: () => number; + oInstance : any; + sInstance: string; + iTabIndex: number; + nScrollHead: Node; + nScrollFoot: Node; + } + + export interface Features + { + bAutoWidth: boolean; + bDeferRender: boolean; + bFilter: boolean; + bInfo: boolean; + bLengthChange: boolean; + bPaginate: boolean; + bProcessing: boolean; + bServerSide: boolean; + bSort: boolean; + bSortClasses: boolean; + bStateSave: boolean; + } + + export interface ScrollingSettings + { + bAutoCss : boolean; + bCollapse: boolean; + bInfinite: boolean; + iBarWidth: number; + iLoadGap: number; + sX: string; + sY: string; + } + + export interface Row + { + nTr: Node; + _aData: any; + _aSortData: any[]; + _anHidden: Node[]; + _sRowStripe: string; + } + + export interface Column + { + aDataSort: any; + asSorting: string[]; + bSearchable : boolean; + bSortable : boolean; + bVisible : boolean; + _bAutoType : boolean; + fnCreatedCell: CreatedCell; + fnGetData: (data: any, specific: string) => any; + fnSetData: (data: any, value: any) => void; + mData: any; + mRender: any; + nTh: Node; + nIf: Node; + sClass: string; + sContentPadding: string; + sDefaultContent: string; + sName: string; + sSortDataType: string; + sSortingClass: string; + sSortingClassJUI: string; + sTitle: string; + sType: string; + sWidth: string; + sWidthOrig: string; + } + + export interface CookieCallback + { + (name: string, data: any, expires: string, path: string, cookie: string) : void; + } + + export interface RowCreatedCallback + { + (row: Node, data: any[], dataIndex: number) : void; + } + + export interface DrawCallback + { + (settings: Settings) : void; + } + + export interface FooterCallback + { + (foot: Element, data: any[], start:number, end:number, display: number[]) : void; + } + + export interface FormatNumber + { + (toFormat: number) : string; + } + + export interface HeaderCallback + { + (head: Element, data: any[], start:number, end:number, display: number[]) : void; + } + + export interface InfoCallback + { + (settings: Settings, start: number, end: number, max:number, total: number, pre: string) : string; + } + + export interface InitComplete + { + (settings: Settings, json: any) : void; + } + + export interface PreDrawCallback + { + (settings: Settings) : boolean; + } + + export interface RowCallback + { + (row : Settings, data: any[], displayIndex: number, displayIndexFull: number) : void; + } + + export interface StateLoadCallback + { + (settings: Settings) : any; + } + + export interface StateLoadParams + { + (settings: Settings, data: any) : void; + } + + export interface StateLoaded + { + (settings: Settings, data: any) : void; + } + + export interface StateSaveCallback + { + (settings: any, data:any) : void; + } + + export interface StateSaveParams + { + (settings: any, data:any) : void; + } + + export interface CreatedCell + { + (nTd: Node, cellData: any, rowData: any, row: number, col: number) : void; + } +} diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index d3fe178c39..c90b40d090 100755 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -1,1445 +1,890 @@ -/// -/// - -// http://www.datatables.net/api - -// $ - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Highlight every second row - oTable.$('tr:odd').css('backgroundColor', 'blue'); -} ); - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Filter to rows with 'Webkit' in them, add a background colour and then - // remove the filter, thus highlighting the 'Webkit' rows only. - oTable.fnFilter('Webkit'); - oTable.$('tr', {"filter": "applied"}).css('backgroundColor', 'blue'); - oTable.fnFilter(''); -} ); - -// _ - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Get the data from the first row in the table - var data = oTable._('tr:first'); - - // Do something useful with the data - alert( "First cell is: "+data[0] ); -} ); - - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Filter to 'Webkit' and get all data for - oTable.fnFilter('Webkit'); - var data = oTable._('tr', {"filter": "applied"}); - - // Do something with the data - alert( data.length+" rows matched the filter" ); -} ); - -// fnAddData - -var giCount = 2; - -$(document).ready(function() { - $('#example').dataTable(); -} ); - -function fnClickAddRow() { - $('#example').dataTable().fnAddData( [ - giCount+".1", - giCount+".2", - giCount+".3", - giCount+".4" ] - ); - - giCount++; -} - -// fnAdjustColumnSizing - -$(document).ready(function() { - var oTable = $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false - } ); - - $(window).bind('resize', function () { - oTable.fnAdjustColumnSizing(); - } ); -} ); - -// fnClearTable - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...) - oTable.fnClearTable(); -} ); - -// fnClose - -$(document).ready(function() { - var oTable; - - // 'open' an information row when a row is clicked on - $('#example tbody tr').click( function () { - if ( oTable.fnIsOpen(this) ) { - oTable.fnClose( this ); - } else { - oTable.fnOpen( this, "Temporary row opened", "info_row" ); - } - } ); - - oTable = $('#example').dataTable(); -} ); - -// fnDeleteRow - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Immediately remove the first row - oTable.fnDeleteRow( 0 ); -} ); - -// fnDestroy - -$(document).ready(function() { - // This example is fairly pointless in reality, but shows how fnDestroy can be used - var oTable = $('#example').dataTable(); - oTable.fnDestroy(); -} ); - -// fnDraw - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Re-draw the table - you wouldn't want to do it here, but it's an example :-) - oTable.fnDraw(); -} ); - -// fnFilter - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Sometime later - filter... - oTable.fnFilter( 'test string' ); -} ); - -// fnGetData - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - oTable.$('tr').click( function () { - var data = oTable.fnGetData( this ); - // ... do something with the array / object of data for the row - } ); -} ); - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - oTable.$('td').click( function () { - var sData = oTable.fnGetData( this ); - alert( 'The cell clicked on had the value of '+sData ); - } ); -} ); - -// fnGetNodes - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Get the nodes from the table - var nNodes = oTable.fnGetNodes( ); -} ); - -// fnGetPosition - -$(document).ready(function() { - $('#example tbody td').click( function () { - // Get the position of the current data from the node - var aPos = oTable.fnGetPosition( this ); - - // Get the data array for this row - var aData = oTable.fnGetData( aPos[0] ); - - // Update the data array and return the value - aData[ aPos[1] ] = 'clicked'; - this.innerHTML = 'clicked'; - } ); - - // Init DataTables - var oTable = $('#example').dataTable(); -} ); - -// fnIsOpen - -$(document).ready(function() { - var oTable; - - // 'open' an information row when a row is clicked on - $('#example tbody tr').click( function () { - if ( oTable.fnIsOpen(this) ) { - oTable.fnClose( this ); - } else { - oTable.fnOpen( this, "Temporary row opened", "info_row" ); - } - } ); - - oTable = $('#example').dataTable(); -} ); - -// fnOpen - -$(document).ready(function() { - var oTable; - - // 'open' an information row when a row is clicked on - $('#example tbody tr').click( function () { - if ( oTable.fnIsOpen(this) ) { - oTable.fnClose( this ); - } else { - oTable.fnOpen( this, "Temporary row opened", "info_row" ); - } - } ); - - oTable = $('#example').dataTable(); -} ); - -// fnPageChange - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - oTable.fnPageChange( 'next' ); -} ); - -// fnSetColumnVis - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Hide the second column after initialisation - oTable.fnSetColumnVis( 1, false ); -} ); - -// fnSettings - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - var oSettings = oTable.fnSettings(); - - // Show an example parameter from the settings - alert("" + oSettings._iDisplayStart); -} ); - -// fnSort - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Sort immediately with columns 0 and 1 - oTable.fnSort( [ [0,'asc'], [1,'asc'] ] ); -} ); - -// fnSortListener - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - - // Sort on column 1, when 'sorter' is clicked on - oTable.fnSortListener( document.getElementById('sorter'), 1 ); -} ); - -// fnUpdate - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell - oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], 1 ); // Row -} ); - -// fnVersionCheck - -$(document).ready(function() { - var oTable = $('#example').dataTable(); - oTable.fnVersionCheck( '1.9.0'); -} ); - -// http://datatables.net/usage/features - -$(document).ready( function () { - $('#example').dataTable( { - "bAutoWidth": false - } ); -} ); - -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/arrays.txt", - "bDeferRender": true - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bFilter": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bInfo": false - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bJQueryUI": true - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bLengthChange": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bPaginate": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bProcessing": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bScrollInfinite": true, - "bScrollCollapse": true, - "sScrollY": "200px" - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "xhr.php" - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bSort": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bSortClasses": false - } ); -} ); - -$(document).ready( function () { - $('#example').dataTable( { - "bStateSave": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollX": "100%", - "bScrollCollapse": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false - } ); -} ); - -// http://datatables.net/usage/options - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false - } ); - - // Some time later.... - $('#example').dataTable( { - "bFilter": false, - "bDestroy": true - } ); -} ); - -$(document).ready( function() { - initTable(); - tableActions(); -} ); - -function initTable () -{ - return $('#example').dataTable( { - "sScrollY": "200px", - "bPaginate": false, - "bRetrieve": true - } ); -} - -function tableActions () -{ - var oTable = initTable(); - // perform API operations with oTable -} - -$(document).ready( function() { - $('#example').dataTable( { - "bScrollAutoCss": false, - "sScrollY": "200px" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollY": "200", - "bScrollCollapse": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bSortCellsTop": true - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "iCookieDuration": 60*60*24 // 1 day - } ); -} ); - -// 57 records available in the table, no filtering applied -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "iDeferLoading": 57 - } ); -} ); - - -// 57 records after filtering, 100 without filtering (an initial filter applied) -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "iDeferLoading": [ 57, 100 ], - "oSearch": { - "sSearch": "my_filter" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "iDisplayLength": 50 - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "iDisplayStart": 20 - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "bScrollInfinite": true, - "bScrollCollapse": true, - "sScrollY": "200px", - "iScrollLoadGap": 50 - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "iTabIndex": 1 - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oSearch": {"sSearch": "Initial search"} - } ); -} ) - -// Get data from { "data": [...] } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data" - } ); -} ); - - -// Get data from { "data": { "inner": [...] } } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data.inner" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php" - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "sCookiePrefix": "my_datatable_" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sDom": '<"top"i>rt<"bottom"flp><"clear">' - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sPaginationType": "full_numbers" - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "sScrollX": "100%", - "sScrollXInner": "110%" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/post.php", - "sServerMethod": "POST" - } ); -} ); - -// http://datatables.net/usage/callbacks - -$(document).ready( function () { - $('#example').dataTable( { - "fnCookieCallback": function (sName, oData, sExpires, sPath) { - // Customise oData or sName or whatever else here - return sName + "="+JSON.stringify(oData)+"; expires=" + sExpires +"; path=" + sPath; - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnCreatedRow": function( nRow, aData, iDataIndex ) { - // Bold the grade for all 'A' grade browsers - if ( aData[4] == "A" ) - { - $('td:eq(4)', nRow).html( 'A' ); - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnDrawCallback": function( oSettings ) { - alert( 'DataTables has redrawn the table' ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) { - ( (nFoot.getElementsByTagName('th')[0])).innerHTML = "Starting index is "+iStart; - } - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "fnFormatNumber": function ( iIn ) { - if ( iIn < 1000 ) { - return iIn.toString(); - } else { - var - s=(iIn+""), - a=s.split(""), out="", - iLen=s.length; - - for ( var i=0 ; i nHead.getElementsByTagName('th')[0]).innerHTML = "Displaying "+(iEnd-iStart)+" records"; - } - } ); -} ) - -$('#example').dataTable( { - "fnInfoCallback": function( oSettings, iStart, iEnd, iMax, iTotal, sPre ) { - return iStart +" to "+ iEnd; - } -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnInitComplete": function(oSettings, json) { - alert( 'DataTables has finished its initialisation.' ); - } - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "fnPreDrawCallback": function( oSettings ) { - if ( $('#test').val() == 1 ) { - return false; - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { - // Bold the grade for all 'A' grade browsers - if ( aData[4] == "A" ) - { - $('td:eq(4)', nRow).html( 'A' ); - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "xhr.php", - "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { - oSettings.jqXHR = $.ajax( { - "dataType": 'json', - "type": "POST", - "url": sSource, - "data": aoData, - "success": fnCallback - } ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "fnServerParams": function ( aoData ) { - aoData.push( { "name": "more_data", "value": "my_value" } ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoad": function (oSettings) { - var o; - - // Send an Ajax request to the server to get the data. Note that - // this is a synchronous request. - $.ajax( { - "url": "/state_load", - "async": false, - "dataType": "json", - "success": function (json) { - o = json; - } - } ); - - return o; - } - } ); -} ); - -// Remove a saved filter, so filtering is never loaded -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoadParams": function (oSettings, oData) { - oData.oSearch.sSearch = ""; - } - } ); -} ); - - -// Disallow state loading by returning false -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoadParams": function (oSettings, oData) { - return false; - } - } ); -} ); - -// Show an alert with the filtering value that was saved -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateLoaded": function (oSettings, oData) { - alert( 'Saved filter was: '+oData.oSearch.sSearch ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateSave": function (oSettings, oData) { - // Send an Ajax request to the server with the state object - $.ajax( { - "url": "/state_save", - "data": oData, - "dataType": "json", - "method": "POST", - "success": function () {} - } ); - } - } ); -} ); - -// Remove a saved filter, so filtering is never saved -$(document).ready( function() { - $('#example').dataTable( { - "bStateSave": true, - "fnStateSaveParams": function (oSettings, oData) { - oData.oSearch.sSearch = ""; - } - } ); -} ); - -// http://datatables.net/usage/columns - -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] }, - { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] }, - { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] } - ] - } ); -} ); - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "aDataSort": [ 0, 1 ] }, - { "aDataSort": [ 1, 0 ] }, - { "aDataSort": [ 2, 3, 4 ] }, - null, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "asSorting": [ "asc" ], "aTargets": [ 1 ] }, - { "asSorting": [ "desc", "asc", "asc" ], "aTargets": [ 2 ] }, - { "asSorting": [ "desc" ], "aTargets": [ 3 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - { "asSorting": [ "asc" ] }, - { "asSorting": [ "desc", "asc", "asc" ] }, - { "asSorting": [ "desc" ] }, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "bSearchable": false, "aTargets": [ 0 ] } - ] } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "bSearchable": false }, - null, - null, - null, - null - ] } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "bSortable": false, "aTargets": [ 0 ] } - ] } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "bSortable": false }, - null, - null, - null, - null - ] } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "bVisible": false, "aTargets": [ 0 ] } - ] } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "bVisible": false }, - null, - null, - null, - null - ] } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [3], - "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) { - if ( sData == "1.7" ) { - $(nTd).css('color', 'blue') - } - } - } ] - }); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "iDataSort": 1, "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "iDataSort": 1 }, - null, - null, - null, - null - ] - } ); -} ); - -// Read table data from objects -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/deep.txt", - "aoColumns": [ - { "mData": "engine" }, - { "mData": "browser" }, - { "mData": "platform.inner" }, - { "mData": "platform.details.0" }, - { "mData": "platform.details.1" } - ] - } ); -} ); - - -// Using mData as a function to provide different information for -// sorting, filtering and display. In this case, currency (price) -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [ 0 ], - "mData": function ( source, type, val ) { - if (type === 'set') { - source.price = val; - // Store the computed dislay and filter values for efficiency - source.price_display = val=="" ? "" : "$"+val; - source.price_filter = val=="" ? "" : "$"+val+" "+val; - return; - } - else if (type === 'display') { - return source.price_display; - } - else if (type === 'filter') { - return source.price_filter; - } - // 'sort', 'type' and undefined all just use the integer - return source.price; - } - } ] - } ); -} ); - -// Create a comma separated list from an array of objects -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/deep.txt", - "aoColumns": [ - { "mData": "engine" }, - { "mData": "browser" }, - { - "mData": "platform", - "mRender": "[, ].name" - } - ] - } ); -} ); - - -// Use as a function to create a link from the data source -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [ 0 ], - "mData": "download_link", - "mRender": function ( data, type, full ) { - return 'Download'; - } - } ] - } ); -} ); - -// Make the first column use TH cells -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "aoColumnDefs": [ { - "aTargets": [ 0 ], - "sCellType": "th" - } ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sClass": "my_class", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sClass": "my_class" }, - null, - null, - null, - null - ] - } ); -} ); - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - null, - null, - { - "sContentPadding": "mmm" - } - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { - "mData": null, - "sDefaultContent": "Edit", - "aTargets": [ -1 ] - } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - null, - null, - { - "mData": null, - "sDefaultContent": "Edit" - } - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sName": "engine", "aTargets": [ 0 ] }, - { "sName": "browser", "aTargets": [ 1 ] }, - { "sName": "platform", "aTargets": [ 2 ] }, - { "sName": "version", "aTargets": [ 3 ] }, - { "sName": "grade", "aTargets": [ 4 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sName": "engine" }, - { "sName": "browser" }, - { "sName": "platform" }, - { "sName": "version" }, - { "sName": "grade" } - ] - } ); -} ); - -/* - -This test does not compile, because - for some hard to find reason - the compiler is missing the aTargets -property of the second element. - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sSortDataType": "dom-text", "aTargets": [ 2, 3 ] }, - { "sType": "numeric", "aTargets": [ 3 ] }, - { "sSortDataType": "dom-select", "aTargets": [ 4 ] }, - { "sSortDataType": "dom-checkbox", "aTargets": [ 5 ] } - ] - } ); -} ); - -*/ - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - null, - null, - { "sSortDataType": "dom-text" }, - { "sSortDataType": "dom-text", "sType": "numeric" }, - { "sSortDataType": "dom-select" }, - { "sSortDataType": "dom-checkbox" } - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sTitle": "My column title", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sTitle": "My column title" }, - null, - null, - null, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sType": "html", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sType": "html" }, - null, - null, - null, - null - ] - } ); -} ); - -// Using aoColumnDefs -$(document).ready( function() { - $('#example').dataTable( { - "aoColumnDefs": [ - { "sWidth": "20%", "aTargets": [ 0 ] } - ] - } ); -} ); - - -// Using aoColumns -$(document).ready( function() { - $('#example').dataTable( { - "aoColumns": [ - { "sWidth": "20%" }, - null, - null, - null, - null - ] - } ); -} ); - -// http://www.datatables.net/usage/i18n - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oAria": { - "sSortAscending": " - click/return to sort ascending" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oAria": { - "sSortDescending": " - click/return to sort descending" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sFirst": "First page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sLast": "Last page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sNext": "Next page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "oPaginate": { - "sPrevious": "Previous page" - } - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sEmptyTable": "No data available in table" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfo": "Got a total of _TOTAL_ entries to show (_START_ to _END_)" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoEmpty": "No entries to show" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoFiltered": " - filtering from _MAX_ records" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoPostFix": "All records shown are derived from real information." - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sInfoThousands": "'" - } - } ); -} ); - -// Language change only -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sLengthMenu": "Display _MENU_ records" - } - } ); -} ); - - -// Language and options change -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sLengthMenu": 'Display records' - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sLoadingRecords": "Please wait - loading..." - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sProcessing": "DataTables is currently busy" - } - } ); -} ); - -// Input text box will be appended at the end automatically -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sSearch": "Filter records:" - } - } ); -} ); - - -// Specify where the filter should appear -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sSearch": "Apply filter _INPUT_ to table" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sUrl": "http://www.sprymedia.co.uk/dataTables/lang.txt" - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "oLanguage": { - "sZeroRecords": "No records to display" - } - } ); -} ); - -// http://www.datatables.net/usage/server-side - -$(document).ready( function () { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "xhr.php" - } ); -} ); - -// POST data to server -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "xhr.php", - "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { - oSettings.jqXHR = $.ajax( { - "dataType": 'json', - "type": "POST", - "url": sSource, - "data": aoData, - "success": fnCallback - } ); - } - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "bProcessing": true, - "bServerSide": true, - "sAjaxSource": "scripts/server_processing.php", - "fnServerParams": function ( aoData ) { - aoData.push( { "name": "more_data", "value": "my_value" } ); - } - } ); -} ); - -// Get data from { "data": [...] } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data" - } ); -} ); - - -// Get data from { "data": { "inner": [...] } } -$(document).ready( function() { - var oTable = $('#example').dataTable( { - "sAjaxSource": "sources/data.txt", - "sAjaxDataProp": "data.inner" - } ); -} ); - -$(document).ready( function() { - $('#example').dataTable( { - "sAjaxSource": "http://www.sprymedia.co.uk/dataTables/json.php" - } ); -} ) - -$(document).ready( function() { - $('#example').dataTable( { - "bServerSide": true, - "sAjaxSource": "scripts/post.php", - "sServerMethod": "POST" - } ); -} ); +/// +/// + +$(document).ready(function () { + //#region "Language" + + var lang: DataTables.LanguageSettings = { + "emptyTable": "No data available in table", + "info": "Showing _START_ to _END_ of _TOTAL_ entries", + "infoEmpty": "Showing 0 to 0 of 0 entries", + "infoFiltered": "(filtered from _MAX_ total entries)", + "infoPostFix": "", + "thousands": ",", + "lengthMenu": "Show _MENU_ entries", + "loadingRecords": "Loading...", + "processing": "Processing...", + "search": "Search:", + "zeroRecords": "No matching records found", + "paginate": { + "first": "First", + "last": "Last", + "next": "Next", + "previous": "Previous" + }, + "aria": { + "sortAscending": ": activate to sort column ascending", + "sortDescending": ": activate to sort column descending" + } + }; + + //#endregion "Language" + + //#region "Column" + + var colCreatedCellFunc: DataTables.FunctionColumnCreatedCell = function (cell, cellData, rowData, rowIndex, colIndex) { + + } + + var colDataObject: DataTables.ObjectColumnData = { + _: "phone", + filter: "phone_filter", + display: "phone_display", + sort: "asc" + }; + + var colDataFunc: DataTables.FunctionColumnData = function (row, type, set, meta) { + }; + + var colRenderObject: DataTables.ObjectColumnRender = { + _: "phone", + filter: "phone_filter", + display: "phone_display", + sort: "asc" + }; + + var colRenderFunc: DataTables.FunctionColumnRender = function (data, type, row, meta) { + + }; + + var col: DataTables.ColumnSettings = + { + cellType: "th", + className: "css", + contentPadding: "mmmm", + createdCell: colCreatedCellFunc, + data: 1, + defaultContent: "edit", + name: "name", + orderable: true, + orderData: 10, + orderDataType: "dom-checkbox", + orderSequence: ['asc', 'desc'], + render: 1, + searchable: true, + title: "title", + visible: true, + width: "200px" + } + col = + { + data: "", + orderData: [10, 11, 20], + render: "", + } + col = + { + data: colDataObject, + render: colRenderObject, + } + col = + { + data: colDataFunc, + render: colRenderFunc, + } + + //#endregion "Column" + + //#region "ColumnDef" + + var colDef: DataTables.ColumnDefsSettings = + { + targets: 1, + cellType: "th", + className: "css", + contentPadding: "mmmm", + createdCell: colCreatedCellFunc, + data: 1, + defaultContent: "edit", + name: "name", + orderable: true, + orderData: 10, + orderDataType: "dom-checkbox", + orderSequence: ['asc', 'desc'], + render: 1, + searchable: true, + title: "title", + visible: true, + width: "200px" + }; + + colDef = + { + targets: "2", + cellType: "th", + }; + + colDef = + { + targets: ["2", 5], + cellType: "th", + }; + + //#endregion "ColumnDef" + + //#region "Callbacks" + + var createRowFunc: DataTables.FunctionCreateRow = function (row, data, dataIndex) { }; + var drawCallbackFunc: DataTables.FunctionDrawCallback = function (settings) { }; + var footerCallbackFunc: DataTables.FunctionFooterCallback = function (tfoot, data, start, end, display) { }; + var formatNumberFunc: DataTables.FunctionFormatNumber = function (toForm) { }; + var headerCallbackFunc: DataTables.FunctionHeaderCallback = function (thead, data, start, end, display) { }; + var infoCallbackFunc: DataTables.FunctionInfoCallback = function (settings, start, end, total, pre) { }; + var initCallbackFunc: DataTables.FunctionInitComplete = function (settings, json) { }; + var preDrawFunc: DataTables.FunctionPreDrawCallback = function (settings) { }; + var rowCallbackFunc: DataTables.FunctionRowCallback = function (row, data) { }; + var stateLoadCallbackFunc: DataTables.FunctionStateLoadCallback = function (settings) { }; + var stateLoadedCallbackFunc: DataTables.FunctionStateLoaded = function (settings, data) { }; + var stateSaveCallbackFunc: DataTables.FunctionStateSaveCallback = function (settings, data) { }; + var stateSaveParamsFunc: DataTables.FunctionStateSaveParams = function (settings, data) { }; + + //#endregion "Callbacks + + //#region "Ajax" + + var ajaxFunc: DataTables.FunctionAjax = function (data, callback, settings) { }; + + var ajaxDataFunc: DataTables.FunctionAjaxData = function (data) { + return data; + }; + + ajaxDataFunc = function (data) { + return ""; + }; + + //#endregion "Ajax" + + //#region "Settings" + + var config: DataTables.Settings = + { + // columns + columns: [ + col, + null, + col, + null, + col, + col + ], + columnDefs: [ + null, + colDef, + colDef, + null, + ], + // Data + ajax: "url", + data: {}, + // Features + autoWidth: true, + deferRender: true, + info: true, + jQueryUI: false, + lengthChange: true, + ordering: true, + paging: true, + scrollX: true, + scrollY: "200px", + searching: true, + serverSide: true, + stateSave: true, + // Options + deferLoading: 10, + destroy: true, + displayStart: 1, + dom: "lrtip", + lengthMenu: [1, 2, 3, 4], + orderCellsTop: true, + orderClasses: true, + order: [[0, 'asc'], [1, 'asc']], + orderFixed: [[0, 'asc'], [1, 'asc']], + orderMulti: true, + pageLength: 10, + pagingType: "simple", + retrieve: true, + renderer: "bootstrap", + scrollCollapse: true, + search: true, + searchCols: [{ "search": "", "smart": true, "regex": false, "caseInsensitive": true }], + searchDelay: 10, + stateDuration: 10, + tabIndex: 10, + }; + + + config = + { + ajax: ajaxFunc, + deferLoading: [10, 100], + lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], + order: [0, 'asc'], + orderFixed: [[0, 'asc'], [1, 'asc']], + renderer: { + header: "bootstrap", + pageButton: "jqueryui" + }, + search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + searchCols: [ + null, + { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + { "search": "" }, + { "search": "", "smart": true }, + null + ], + }; + + config = + { + ajax: { + data: {}, + dataSrc: "", + }, + }; + + config = + { + ajax: { + data: ajaxDataFunc, + dataSrc: function (data) { }, + }, + }; + + //#endregion "Settings" + + //#region "Init" + + var dt = $('#example').DataTable(); + dt = $('#example1').DataTable(config); + dt = $('#example1').DataTable(config); + dt.$('tr:odd').css('backgroundColor', 'blue'); + + //#endregion "Init" + + //#region "Methods-Ajax" + + var json = dt.ajax.json(); + + var params = dt.ajax.params(); + + var reload = dt.ajax.reload(); + reload = dt.ajax.reload(function () { }); + reload = dt.ajax.reload(function () { }, true); + var test = reload.$(""); + + var url = dt.ajax.url(); + dt.ajax.url("url"); + dt.ajax.url("url").load(); + + //#endregion "Methods-Ajax" + + //#region "Methods-Core" + + var clear = dt.clear(); + clear.$(""); + + var data = dt.data(); + data.$(""); + + var destroy = dt.destroy(); + destroy = dt.destroy(true); + destroy.$(""); + + var draw = dt.draw(); + draw = dt.draw(true); + draw.$(""); + + var off = dt.off("event"); + off = dt.off("event", function () { }); + off.$(""); + + var on = dt.on("event", function () { }); + on.$(""); + + var one = dt.one("event", function () { }); + one.$(""); + + var order_get = dt.order(); + var order_set = dt.order([0, "asc"]); + order_set = dt.order([0, "asc"], [1, "desc"]); // TODO: Fíx that + order_set = dt.order([[0, "asc"], [1, "desc"]]); + + var orderListerner = order_set.order.listener("node", 1, function () { }); + + var page_get = dt.page(); + var page_set = dt.page(1); + page_set = dt.page("next"); + + var page = dt.page.info(); + page = { + "page": 1, + "pages": 6, + "start": 10, + "end": 20, + "length": 10, + "recordsTotal": 57, + "recordsDisplay": 57 + }; + + var page_len_get = dt.page.len(); + var page_len_set = dt.page.len(10); + + var search_get = dt.search(); + var search_set = dt.search("searchStr"); + search_set = dt.search("searchStr", true); + search_set = dt.search("searchStr", true, false); + search_set = dt.search("searchStr", true, false, false); + + var settings = dt.settings(); + + var state = dt.state(); + state = { "time": 1423772610230, "start": 0, "length": 25, "order": [[0, "asc"]], "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, "columns": [{ "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }, { "visible": true, "search": { "search": "", "smart": true, "regex": false, "caseInsensitive": true } }] }; + state = dt.state.loaded(); + + var state_clear = dt.state.clear(); + state_clear.$(""); + + var state_save = dt.state.save(); + state_save.$(""); + + //#endregion "Methods-Core" + + var modifier: DataTables.ObjectSelectorModifier = { + order: "current", + search: "none", + page: "all", + }; + + //#region "Methods-Cell" + + var cells = dt.cells(); + cells = dt.cells(":contains('Not shipped')"); + cells = dt.cells(function () { }); + cells = dt.cells($("")); + cells = dt.cells({}); + cells = dt.cells(":contains('Not shipped')r", modifier); + cells = dt.cells("row-selector", "cells-selector", modifier); + + var cells_cache = cells.cache("search"); + // Create the select list and search operation + var select = $('') + .appendTo( + dt.column(colIdx).footer() + ) + .on('change', function () { + dt + .column(colIdx) + .search($(this).val()) + .draw(); + }); + + // Get the search data for the first column and add to the select list + dt + .column(colIdx) + .cache('search') + .sort() + .unique() + .each(function (d) { + select.append($('')); + }); + }); + + var columns_data = columns.data(); + $('#listData').html( + dt + .columns(0) + .data() + .eq(0) // Reduce the 2D array into a 1D array of data + .sort() // Sort data alphabetically + .unique() // Reduce to unique values + .join('
') + ); + + //var idx = dt + // .columns('.check') + // .data() + // .eq(0) // Reduce the 2D array into a 1D array of data + // .indexOf('Yes'); + + var columns_dataSrc = columns.dataSrc(); + //alert('Data source: ' + dt.columns([0, 1]).dataSrc().join(' ')); + + var columns_footer = columns.footer(); + var columns_header = columns.header(); + var columns_indexes = columns.indexes(); + columns_indexes = columns.indexes("visibile"); + var columns_nodes = columns.nodes(); + dt + .columns('.ready') + .nodes() + //.flatten() // Reduce to a 1D array + //.to$() // Convert to a jQuery object + //.addClass('highlight'); + + var columns_search_get = columns.search(); + var columns_search_set = columns.search("string"); + columns_search_set = columns.search("string", true); + columns_search_set = columns.search("string", true, false); + columns_search_set = columns.search("string", true, false, true); + + var columns_visible_get = columns.visible(); + var columns_visible_set = columns.visible(false); + columns_visible_set = columns.visible(false, true); + // Hide a column + dt.column(1).visible(false); + dt.columns([0, 1, 2, 3]).visible(false, false); + dt.columns.adjust().draw(false); // adjust column sizing and redraw + + var columns_adjust = dt.columns.adjust(); + + var column = dt.column("selector"); + column = dt.column("selector", modifier); + + dt.column(0).visible(false); + + $('#example tbody').on('click', 'td', function () { + var visIdx = $(this).index(); + var dataIdx = dt.column.index('fromVisible', visIdx); + + alert('Column data index: ' + dataIdx + ', and visible index: ' + visIdx); + }); + + var column_cache = column.cache("order"); + // Create the select list and search operation + var select = $('') + .appendTo( + dt.column(colIdx).footer() + ) + .on('change', function () { + dt + .column(colIdx) + .search($(this).val()) + .draw(); + }); + + // Get the search data for the first column and add to the select list + dt + .column(colIdx) + .cache('search') + .sort() + .unique() + .each(function (d) { + select.append($('')); + }); + }); + + var column_visible_get = column.visible(); + var column_visible_set = column.visible(false); + column_visible_set = column.visible(false, true); + alert('Column index 0 is ' + + (dt.column(0).visible() === true ? 'visible' : 'not visible') + ); + for (var i = 0; i < 4; i++) { + dt.column(i).visible(false, false); + } + dt.columns.adjust().draw(false); // adjust column sizing and redraw + + //#endregion "Methods-Column" + + //#region "Methods-Row" + + var row_1 = dt.row("selector"); + var row_2 = dt.row("selector").child.hide(); + var row_3 = dt.row("selector").child.isShown(); + var row_4 = dt.row("selector").child.remove(); + var row_5 = dt.row("selector").child.show(); + var row_6 = dt.row("selector").child(); + var row_7 = dt.row("selector").child(false); + var row_8 = dt.row("selector").child(false).hide(); + var row_9 = dt.row("selector").child("data"); + var row_10 = dt.row("selector").child("data").remove(); + var row_11 = dt.row("selector").child("data", "css").show(); + var row_12 = dt.row("selector").child.remove(); + var row_13 = dt.row("selector").child.show(); + var row_14 = dt.row.add({}); + var row_15 = dt.row("selector").invalidate(); + var row_16 = dt.row("selector").invalidate("auto"); + var row_17 = dt.row("selector").data(); + var row_18 = dt.row("selector").data({}); + var row_19 = dt.row("selector").index(); + var row_20 = dt.row("selector").node(); + var row_21 = dt.row("selector").remove(); + + var rows_1 = dt.rows(); + var rows_2 = dt.rows().remove(); + var rows_3 = dt.rows("selector"); + var rows_4 = dt.rows("selector").cache("type"); + var rows_5 = dt.rows("selector").data(); + var rows_6 = dt.rows("selector").data({}); + var rows_7 = dt.rows("selector").indexes(); + var rows_8 = dt.rows("selector").invalidate(); + var rows_9 = dt.rows("selector").invalidate("auto"); + var rows_10 = dt.rows("selector").indexes(); + var rows_11 = dt.rows("selector").remove(); + var rows_12 = dt.rows("selector").nodes(); + var rows_13 = dt.rows.add([{}, {}]); + + var table3 = $('#example').DataTable(); + table3.row.add({ + "name": "Tiger Nixon", + "position": "System Architect", + "salary": "$3,120", + "start_date": "2011/04/25", + "office": "Edinburgh", + "extn": "5421" + }).draw(); + + var table4 = $('#example').DataTable(); + table4.row.add([{ + "name": "Tiger Nixon", + "position": "System Architect", + "salary": "$3,120", + "start_date": "2011/04/25", + "office": "Edinburgh", + "extn": "5421" + }, { + "name": "Garrett Winters", + "position": "Director", + "salary": "$5,300", + "start_date": "2011/07/25", + "office": "Edinburgh", + "extn": "8422" + }]) + .draw(); + + var pupil: any; + var table5 = $('#example').DataTable(); + table5.rows.add([ + pupil, + pupil, + pupil, + ]) + .draw(); + //.nodes() + //.to$() + //.addClass('new'); + + $('#example tbody').on('click', 'td.details-control', function () { + var tr = $(this).parents('tr'); + var row = dt.row(tr); + + if (row.child.isShown()) { + // This row is already open - close it + row.child.hide(); + tr.removeClass('shown'); + } + else { + // Open this row (the format() function would return the data to be shown) + row.child("").show(); + tr.addClass('shown'); + } + }); + + dt.row(':eq(0)').child([ + 'First child row', + 'Second child row', + 'Third child row' + ]) + .show(); + + dt.rows().eq(0).each(function (rowIdx) { + dt + .row(rowIdx) + .child( + $( + '' + + '' + rowIdx + '.1' + + '' + rowIdx + '.2' + + '' + rowIdx + '.3' + + '' + rowIdx + '.4' + + '' + ) + ) + .show(); + }); + + $('#example tbody').on('click', 'td.details-control', function () { + var tr = $(this).parents('tr'); + var row = dt.row(tr); + + if (row.child.isShown()) { + // This row is already open - close it + row.child.hide(); + tr.removeClass('shown'); + } + else { + // Open this row (the format() function would return the data to be shown) + row.child("").show(); + tr.addClass('shown'); + } + }); + + $('#example tbody').on('click', 'td.details-control', function () { + var tr = $(this).parents('tr'); + var row = dt.row(tr); + + if (row.child.isShown()) { + // This row is already open - remove it + row.child.remove(); + tr.removeClass('shown'); + } + else { + // Open this row (the format() function would return the data to be shown) + row.child("").show(); + tr.addClass('shown'); + } + }); + + //#endregion "Methods-Row" + + //#region "Methods-Table" + + var tables = dt.tables(); + tables = dt.tables("selector"); + + var tables_body = tables.body(); + var tables_containers = tables.containers(); + var tables_footer = tables.footer(); + var tables_header = tables.header(); + var tables_nodes = tables.nodes(); + + var table = dt.table("selector"); + + var table_body = table.body(); + var table_container = table.container(); + var table_footer = table.footer(); + var table_header = table.header(); + var table_node = table.node(); + + //#endregion "Methods-Table" + + //#region "Methods-Util" + + //#endregion "Methods-Util" +}); diff --git a/jquery.dataTables/jquery.dataTables.d.ts b/jquery.dataTables/jquery.dataTables.d.ts index 9884b78e29..cbcb1c0257 100755 --- a/jquery.dataTables/jquery.dataTables.d.ts +++ b/jquery.dataTables/jquery.dataTables.d.ts @@ -1,479 +1,1828 @@ -// Type definitions for JQuery DataTables 1.9.4 -// Project: http://www.datatables.net -// Definitions by: Armin Sander -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// missing: -// - Static methods that are defined in JQueryStatic.fn are not typed. -// - Plugin and extension definitions are not typed. - -interface JQuery -{ - dataTable(param? :DataTables.Options) : DataTables.DataTable; -} - -declare module DataTables -{ - export interface DataTable - { - /// Perform a jQuery selector action on the table's TR elements (from the tbody) and return the resulting jQuery object. - $(selector:string, opts?:RowParams): JQuery; - $(selector:Node[], opts?:RowParams): JQuery; - $(selector:JQuery, opts?:RowParams): JQuery; - - /// Almost identical to $ in operation, but in this case returns the data for the matched rows. - _(selector:string, opts?:RowParams): any[]; - _(selector:Node[], opts?:RowParams): any[]; - _(selector:JQuery, opts?:RowParams): any[]; - - /// Add a single new row or multiple rows of data to the table. - fnAddData(data:any, redraw?:boolean) : number[]; - - /// This function will make DataTables recalculate the column sizes. - fnAdjustColumnSizing(redraw? : boolean) : void; - - /// Quickly and simply clear a table - fnClearTable(redraw? : boolean) : void; - - /// The exact opposite of 'opening' a row, this function will close any rows which are currently 'open'. - fnClose(node: Node) : number; - - /// Remove a row for the table - fnDeleteRow(index: number, callback?: () => void, redraw?: boolean) : any[]; - fnDeleteRow(tr: Node, callback?: () => void, redraw?: boolean) : any[]; - - /// Restore the table to it's original state in the DOM by removing all of DataTables enhancements, - /// alterations to the DOM structure of the table and event listeners. - fnDestroy(remove?: boolean) : void; - - /// Redraw the table - fnDraw(complete? : boolean) : void; - - /// Filter the input based on data - fnFilter(input: string, column? : number, regex?: boolean, smart? : boolean, showGlobal?: boolean, caseInsensitive? : boolean) : void; - - /// Get the data for the whole table, an individual row or an individual cell based on the provided parameters. - fnGetData(row?: Node, col? : number) : any; - fnGetData(row?: number, col? : number) : any; - - /// Get an array of the TR nodes that are used in the table's body. - fnGetNodes(row? : number) : any; // Node[] | Node - - /// Get the array indexes of a particular cell from it's DOM element and column index including hidden columns - fnGetPosition(node: Node) : any; // number | number[] - - /// Check to see if a row is 'open' or not. - fnIsOpen(tr: Node) : boolean; - - /// This function will place a new row directly after a row which is currently on display on the page, - /// with the HTML contents that is passed into the function. - fnOpen(node: Node, html: string, clazz: string) : Node; - fnOpen(node: Node, html: Node, clazz: string) : Node; - fnOpen(node: Node, html: JQuery, clazz: string) : Node; - - /// Change the pagination - provides the internal logic for pagination in a simple API function. - fnPageChange(action: string, redraw?: boolean) : void; - fnPageChange(page: number, redraw?: boolean) : void; - - /// Show a particular column - fnSetColumnVis(column: number, show: boolean, redraw?: boolean) : void; - - /// Get the settings for a particular table for external manipulation - fnSettings() : Settings; - - /// Sort the table by a particular column - fnSort(col: number) : void; - fnSort(col: any[][]) : void; - - /// Attach a sort listener to an element for a given column - fnSortListener(node: Node, column: number, callback? : () => void): void; - - /// Update a table cell or row - this method will accept either a single value to update the cell with, - /// an array of values with one element for each column or an object in the same format as the original data source. - fnUpdate(data: any, row: Node, column?:number, redraw?: boolean, action? : boolean) : number; - fnUpdate(data: any, dataIndex: number, column?:number, redraw?: boolean, action? : boolean) : number; - - /// Provide a common method for plug-ins to check the version of DataTables being used, - /// in order to ensure compatibility. - fnVersionCheck(version: string) : boolean; - } - - export interface Static - { - /// Provide a common method for plug-ins to check the version of DataTables being used, - /// in order to ensure compatibility. - fnVersionCheck(version: string) : boolean; - - /// Check if a TABLE node is a DataTable table already or not. - fnIsDataTable(table: Node) : boolean; - - /// Get all DataTable tables that have been initialised. - fnTables(visible? : boolean) : Node[]; - } - - export interface RowParams - { - /// Select TR elements that meet the current filter criterion ("applied") or all TR elements (i.e. no filter). - filter?: string; - - /// Order of the TR elements in the processed array. - /// Can be either 'current', whereby the current sorting of the table is used, or - /// 'original' whereby the original order the data was read into the table is used. - order?: string; - - /// Limit the selection to the currently displayed page - /// ("current") or not ("all"). If 'current' is given, then order is assumed to be - /// 'current' and filter is 'applied', regardless of what they might be given as. - page?: string; - } - - export interface Options - { - aaData?: any[]; - aaSorting?: any[]; - aaSortingFixed?: any[]; - ajax?: any; - aLengthMenu?: any[]; - aoColumns?: ColumnOptions[]; - aoColumnDefs?: ColumnDef[]; - aoSearchCols?: any[]; - asStripClasses?: string[]; - bAutoWidth?: boolean; - bDeferRender?: boolean; - bDestroy?: boolean; - bFilter?: boolean; - bInfo?: boolean; - bJQueryUI?: boolean; - bLengthChange?: boolean; - bPaginate?: boolean; - bProcessing?: boolean; - bRetrieve?: boolean; - bScrollAutoCss?: boolean; - bScrollCollapse?: boolean; - bScrollInfinite?: boolean; - bServerSide?: boolean; - bSort?: boolean; - bSortCellsTop?: boolean; - bSortClasses?: boolean; - bStateSave?: boolean; - fnCookieCallback?: CookieCallback; - fnCreatedRow?: RowCreatedCallback; - fnDrawCallback?: DrawCallback; - fnFooterCallback?: FooterCallback; - fnFormatNumber?: FormatNumber; - fnHeaderCallback?: HeaderCallback; - fnInfoCallback?: InfoCallback; - fnInitComplete?: InitComplete; - fnPreDrawCallback?: PreDrawCallback; - fnRowCallback?: RowCallback; - - fnStateLoadCallback?: StateLoadCallback; - fnStateLoadParams?: StateLoadParams; - fnStateLoaded?: StateLoaded; - fnStateSaveCallback?: StateSaveCallback; - fnStateSaveParams?: StateSaveParams; - iCookieDuration?: number; - iDeferLoading?: any; - iDisplayLength?: number; - iDisplayStart?: number; - iScrollLoadGap?: number; - iTabIndex?: number; - oLanguage?: LanguageOptions; - oSearch?: any; - sAjaxDataProp?: string; - sAjaxSource?: string; - sCookiePrefix?: string; - sDom?: string; - sPaginationType?: string; - sScrollX?: string; - sScrollXInner?: string; - sScrollY?: string; - sServerMethod? : string; - } - - export interface LanguageOptions - { - oAria? : AriaOptions; - oPaginate? : PaginateOptions; - sEmptyTable?: string; - sInfo?: string; - sInfoEmpty?: string; - sInfoFiltered?: string; - sInfoPostFix?: string; - sInfoThousands?: string; - sLengthMenu?: string; - sLoadingRecords?: string; - sProcessing?: string; - sSearch?: string; - sUrl?: string; - sZeroRecords?: string; - } - - export interface AriaOptions - { - sSortAscending?: string; - sSortDescending?: string; - } - - export interface PaginateOptions - { - sFirst?: string; - sLast?: string; - sNext?: string; - sPrevious?: string; - } - - export interface ColumnOptions - { - aDataSort?: number[]; - asSorting?: string[]; - bSearchable? : boolean; - bSortable? : boolean; - bVisible? : boolean; - _bAutoType? : boolean; - fnCreatedCell?: CreatedCell; - iDataSort?: number; - mData?: any; - mRender?: any; - sCellType?: string; - sClass?: string; - sContentPadding?: string; - sDefaultContent?: string; - sName?: string; - sSortDataType?: string; - sSortingClass?: string; - sTitle?: string; - sType?: string; - sWidth?: string; - } - - export interface ColumnDef extends ColumnOptions - { - aTargets: any[]; - } - - export interface Settings - { - oFeatures : Features; - oScroll: ScrollingSettings; - oLanguage : { fnInfoCallback : InfoCallback; }; - oBrowser : { bScrollOversize : boolean; }; - aanFeatures: Node[][]; - aoData: Row[]; - aiDisplay: number[]; - aiDisplayMaster: number[]; - aoColumns: Column[]; - aoHeader: any[]; - aoFooter: any[]; - asDataSearch: string[]; - oPreviousSearch: any; - aoPreSearchCols: any[]; - aaSorting: any[][]; - aaSortingFixed: any[][]; - asStripeClasses: string[]; - asDestroyStripes: string[]; - sDestroyWidth: number; - aoRowCallback: RowCallback[]; - aoHeaderCallback: HeaderCallback[]; - aoFooterCallback: FooterCallback[]; - aoDrawCallback: DrawCallback[]; - aoRowCreatedCallback: RowCreatedCallback[]; - aoPreDrawCallback: PreDrawCallback[]; - aoInitComplete: InitComplete[]; - aoStateSaveParams: StateSaveParams[]; - aoStateLoadParams: StateLoadParams[]; - aoStateLoaded: StateLoaded[]; - sTableId: string; - nTable: Node; - nTHead: Node; - nTFoot: Node; - nTBody: Node; - nTableWrapper: Node; - bDeferLoading: boolean; - bInitialized: boolean; - aoOpenRows: any[]; - sDom: string; - sPaginationType: string; - iCookieDuration: number; - sCookiePrefix: string; - fnCookieCallback: CookieCallback; - aoStateSave: StateSaveCallback[]; - aoStateLoad: StateLoadCallback[]; - oLoadedState: any; - sAjaxSource: string; - sAjaxDataProp: string; - bAjaxDataGet: boolean; - jqXHR: any; - fnServerData: any; - aoServerParams: any[]; - sServerMethod: string; - fnFormatNumber: FormatNumber; - aLengthMenu: any[]; - iDraw: number; - bDrawing: boolean; - iDrawError: number; - _iDisplayLength: number; - _iDisplayStart: number; - _iDisplayEnd: number; - _iRecordsTotal: number; - _iRecordsDisplay: number; - bJUI: boolean; - oClasses: any; - bFiltered: boolean; - bSorted: boolean; - bSortCellsTop: boolean; - oInit: any; - aoDestroyCallback: any[]; - fnRecordsTotal: () => number; - fnRecordsDisplay: () => number; - fnDisplayEnd: () => number; - oInstance : any; - sInstance: string; - iTabIndex: number; - nScrollHead: Node; - nScrollFoot: Node; - } - - export interface Features - { - bAutoWidth: boolean; - bDeferRender: boolean; - bFilter: boolean; - bInfo: boolean; - bLengthChange: boolean; - bPaginate: boolean; - bProcessing: boolean; - bServerSide: boolean; - bSort: boolean; - bSortClasses: boolean; - bStateSave: boolean; - } - - export interface ScrollingSettings - { - bAutoCss : boolean; - bCollapse: boolean; - bInfinite: boolean; - iBarWidth: number; - iLoadGap: number; - sX: string; - sY: string; - } - - export interface Row - { - nTr: Node; - _aData: any; - _aSortData: any[]; - _anHidden: Node[]; - _sRowStripe: string; - } - - export interface Column - { - aDataSort: any; - asSorting: string[]; - bSearchable : boolean; - bSortable : boolean; - bVisible : boolean; - _bAutoType : boolean; - fnCreatedCell: CreatedCell; - fnGetData: (data: any, specific: string) => any; - fnSetData: (data: any, value: any) => void; - mData: any; - mRender: any; - nTh: Node; - nIf: Node; - sClass: string; - sContentPadding: string; - sDefaultContent: string; - sName: string; - sSortDataType: string; - sSortingClass: string; - sSortingClassJUI: string; - sTitle: string; - sType: string; - sWidth: string; - sWidthOrig: string; - } - - export interface CookieCallback - { - (name: string, data: any, expires: string, path: string, cookie: string) : void; - } - - export interface RowCreatedCallback - { - (row: Node, data: any[], dataIndex: number) : void; - } - - export interface DrawCallback - { - (settings: Settings) : void; - } - - export interface FooterCallback - { - (foot: Element, data: any[], start:number, end:number, display: number[]) : void; - } - - export interface FormatNumber - { - (toFormat: number) : string; - } - - export interface HeaderCallback - { - (head: Element, data: any[], start:number, end:number, display: number[]) : void; - } - - export interface InfoCallback - { - (settings: Settings, start: number, end: number, max:number, total: number, pre: string) : string; - } - - export interface InitComplete - { - (settings: Settings, json: any) : void; - } - - export interface PreDrawCallback - { - (settings: Settings) : boolean; - } - - export interface RowCallback - { - (row : Settings, data: any[], displayIndex: number, displayIndexFull: number) : void; - } - - export interface StateLoadCallback - { - (settings: Settings) : any; - } - - export interface StateLoadParams - { - (settings: Settings, data: any) : void; - } - - export interface StateLoaded - { - (settings: Settings, data: any) : void; - } - - export interface StateSaveCallback - { - (settings: any, data:any) : void; - } - - export interface StateSaveParams - { - (settings: any, data:any) : void; - } - - export interface CreatedCell - { - (nTd: Node, cellData: any, rowData: any, row: number, col: number) : void; - } -} +// Type definitions for JQuery DataTables 1.10.5 +// Project: http://www.datatables.net +// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// missing: +// - Static methods that are defined in JQueryStatic.fn are not typed. +// - Plugin and extension definitions are not typed. +// - Some return types are not fully wokring + +/// + +interface JQuery { + DataTable(param?: DataTables.Settings): DataTables.DataTable; +} + +//TODO: Wrong, as jquery.d.ts has no interface for fn +//interface JQueryStatic { +// dataTable: DataTables.StaticFunctions; +//} + +declare module DataTables { + export interface DataTable extends DataTableCore { + /** + * Get the data for the whole table. + */ + data(): DataTable; + + /** + * Order Methods / Object + */ + order: OrderMethods; + + //#region "Cell/Cells" + + /** + * Select the cell found by a cell selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cell(cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellMethods; + + /** + * Select the cell found by a cell selector + * + * @param rowSelector Row selector. + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cell(rowSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellMethods; + + /** + * Select all cells + * + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cells(modifier?: ObjectSelectorModifier): CellsMethods; + + /** + * Select cells found by a cell selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cells(cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellsMethods; + + /** + * Select cells found by both row and column selectors + * + * @param rowSelector Row selector. + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + cells(rowSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], cellSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[], modifier?: ObjectSelectorModifier): CellsMethods; + //#endregion "Cell/Cells" + + //#region "Column/Columns" + + /** + * Column Methods / Object + */ + column: ColumnMethodsModel; + + /** + * Columns Methods / Object + */ + columns: ColumnsMethodsModel; + + //#endregion "Column/Columns" + + //#region "Row/Rows" + + /** + * Row Methode / Object + */ + row: RowMethodsModel + + /** + * Rows Methods / Object + */ + rows: RowsMethodsModel + + //#endregion "Row/Rows" + + //#region "Table/Tables" + + /** + * Select a table based on a selector from the API's context + * + * @param tableSelector Table selector. + */ + table(tableSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[]): TableMethods; + + /** + * Select all tables + */ + tables(): TablesMethods; + + /** + * Select tables based on the given selector + * + * @param tableSelector Table selector. + */ + tables(tableSelector: (string | Node | Function | JQuery | Object) | (string | Node | Function | JQuery | Object)[]): TablesMethods; + + //#endregion "Table/Tables" + } + + export interface DataTables extends DataTableCore { + [index: number]: DataTable; + } + + interface ObjectSelectorModifier { + /** + * The order modifier provides the ability to control which order the rows are processed in. + * Values: 'current', 'applied', 'index', 'original' + */ + order?: string; + + /** + * The search modifier provides the ability to govern which rows are used by the selector using the search options that are applied to the table. + * Values: 'none', 'applied', 'removed' + */ + search?: string; + + /** + * The page modifier allows you to control if the selector should consider all data in the table, regardless of paging, or if only the rows in the currently disabled page should be used. + * Values: 'all', 'current' + */ + page?: string; + } + + //#region "Namespaces" + + //#region "core-methods" + + interface DataTableCore extends UtilityMethods { + /** + * Get jquery object + */ + $(selector: string | Node | Node[]| JQuery, modifier?: ObjectSelectorModifier): JQuery; + + ///// Almost identical to $ in operation, but in this case returns the data for the matched rows. + //_(selector: string | Node | Node[] | JQuery, modifier?: ObjectSelectorModifier): JQuery; + + /** + * Ajax Methods + */ + ajax: AjaxMethodModel; + + /** + * Clear the table of all data. + */ + clear(): DataTable; + + /** + * Destroy the DataTables in the current context. + * + * @param remove Completely remove the table from the DOM (true) or leave it in the DOM in its original plain un-enhanced HTML state (default, false). + */ + destroy(remove?: boolean): DataTable; + + /** + * Destroy the DataTables in the current context. + * + * @param reset Reset (default) or hold the current paging position. A full re-sort and re-filter is performed when this method is called, which is why the pagination reset is the default action. + */ + draw(reset?: boolean): DataTable; + + /** + * Table events removal. + * + * @param event Event name to remove. + * @param callback Specific callback function to remove if you want to unbind a single event listener. + */ + off(event: string, callback?: Function): DataTable; + + /** + * Table events listener. + * + * @param event Event to listen for. + * @param callback Specific callback function to remove if you want to unbind a single event listener. + */ + on(event: string, callback: Function): DataTable; + + /** + * Listen for a table event once and then remove the listener. + * + * @param event Event to listen for. + * @param callback Specific callback function to remove if you want to unbind a single event listener. + */ + one(event: string, callback: Function): DataTable; + + /** + * Page Methods / Object + */ + page: PageMethods; + + /** + * Get current search + */ + search(): string; + + /** + * Search for data in the table. + * + * @param input Search string to apply to the table. + * @param regex Treat as a regular expression (true) or not (default, false). + * @param smart Perform smart search. + * @param caseInsen Do case-insensitive matching (default, true) or not (false). + */ + search(input: string, regex?: boolean, smart?: boolean, caseInsen?: boolean): DataTable; + + /** + * Obtain the table's settings object + */ + settings(): DataTable; + + /** + * Page Methods / Object + */ + state: StateMethods; + } + + //#region "ajax-methods" + + interface AjaxMethods extends DataTable { + /** + * Reload the table data from the Ajax data source. + * + * @param callback Function which is executed when the data as been reloaded and the table fully redrawn. + * @param resetPaging Reset (default action or true) or hold the current paging position (false). + */ + load(callback?: Function, resetPaging?: boolean): DataTable; + } + + interface AjaxMethodModel { + /** + * Get the latest JSON data obtained from the last Ajax request DataTables made + */ + json(): Object; + + /** + * Get the data submitted by DataTables to the server in the last Ajax request + */ + params(): Object; + + /** + * Reload the table data from the Ajax data source. + * + * @param callback Function which is executed when the data as been reloaded and the table fully redrawn. + * @param resetPaging Reset (default action or true) or hold the current paging position (false). + */ + reload(callback?: Function, resetPaging?: boolean): DataTable; + + /** + * Reload the table data from the Ajax data source + */ + url(): string; + + /** + * Reload the table data from the Ajax data source + * + * @param url URL to set to be the Ajax data source for the table. + */ + url(url: string): AjaxMethods; + } + + //#endregion "ajax-methods" + + //#region "order-methods" + + interface OrderMethods { + /** + * Get the ordering applied to the table. + */ + (): (string | number)[][]; + + /** + * Set the ordering applied to the table. + * + * @param order Order Model + */ + (order?: (string | number)[]): DataTable; + (order?: (string | number)[][]): DataTable; + (order: (string | number)[], ...args: any[]): DataTable; + + /** + * Add an ordering listener to an element, for a given column. + * + * @param node Selector + * @param column Column index + * @param callback Callback function + */ + listener(node: string | Node | JQuery, column: number, callback: Function): DataTable; + } + //#endregion "order-methods" + + //#region "page-methods" + + interface PageMethods { + /** + * Get the current page of the table. + */ + (): number; + + /** + * Set the current page of the table. + * + * @param page Index or 'first', 'next', 'previous', 'last' + */ + (page: number | string): DataTable; + + /** + * Get paging information about the table + */ + info(): PageMethodeModelInfoReturn; + + /** + * Get the table's page length. + */ + len(): number; + + /** + * Set the table's page length. + * + * @param length Page length to set. use -1 to show all records. + */ + len(length: number): DataTable; + } + + interface PageMethodeModelInfoReturn { + page: number; + pages: number; + start: number; + end: number; + length: number; + recordsTotal: number; + recordsDisplay: number; + } + + //#endregion "page-methods" + + //#region "state-methods" + + interface StateMethods { + /** + * Get the last saved state of the table + */ + (): StateReturnModel; + + /** + * Clear the saved state of the table. + */ + clear(): DataTable; + + /** + * Get the table state that was loaded during initialisation. + */ + loaded(): StateReturnModel; + + /** + * Trigger a state save. + */ + save(): DataTable; + } + + interface StateReturnModel { + time: number; + start: number; + length: number; + order: (string | number)[][]; + search: SearchSettings; + columns: StateReturnModelColumns[]; + } + + interface StateReturnModelColumns { + search: SearchSettings; + visible: boolean; + } + + //#endregion "state-methods" + + //#endregion "core-methods" + + //#region "util-methods" + + interface UtilityMethods { + /** + * Concatenate two or more API instances together + * + * @param a API instance to concatenate to the initial instance. + * @param b Additional API instance(s) to concatenate to the initial instance. + */ + concat(a: Object, ...b: Object[]): DataTable; + + /** + * Iterate over the contents of the API result set. + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with three parameters + */ + each(fn: Function): DataTable; + + /** + * Reduce an Api instance to a single context and result set. + * + * @param idx Index to select + */ + eq(idx: number): DataTable; + + /** + * Iterate over the result set of an API instance and test each item, creating a new instance from those items which pass. + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with three parameters. + */ + filter(fn: Function): DataTable; + + /** + * Flatten a 2D array structured API instance to a 1D array structure. + */ + flatten(): DataTable; + + /** + * Find the first instance of a value in the API instance's result set. + * + * @param value Value to find in the instance's result set. + */ + indexOf(value: any): number; + + /** + * Join the elements in the result set into a string. + * + * @param separator The string that will be used to separate each element of the result set. + */ + join(separator: string): string; + + /** + * Find the last instance of a value in the API instance's result set. + * + * @param value Value to find in the instance's result set. + */ + lastIndexOf(value: any): number; + + /** + * Number of elements in an API instance's result set. + */ + length: number; + + /** + * Iterate over the result set of an API instance, creating a new API instance from the values returned by the callback. + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with three parameters. + */ + map(fn: Function): DataTable; + + /** + * Iterate over the result set of an API instance, creating a new API instance from the values retrieved from the original elements. + * + * @param property Object property name to use from the element in the original result set for the new result set. + */ + pluck(property: number | string): DataTable; + + /** + * Remove the last item from an API instance's result set. + */ + pop(): any; + + /** + * Add one or more items to the end of an API instance's result set. + * + * @param value_1 Item to add to the API instance's result set. + */ + push(value_1: any | any[], ...value_2: any[]): number; + + /** + * Apply a callback function against and accumulator and each element in the Api's result set (left-to-right). + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with four parameters. + * @param initialValue Value to use as the first argument of the first call to the fn callback. + */ + reduce(fn: Function, initialValue?: any): any; + + /** + * Apply a callback function against and accumulator and each element in the Api's result set (right-to-left). + * + * @param fn Callback function which is called for each item in the API instance result set. The callback is called with four parameters. + * @param initialValue Value to use as the first argument of the first call to the fn callback. + */ + reduceRight(fn: Function, initialValue?: any): any; + + /** + * Reverse the result set of the API instance and return the original array. + */ + reverse(): DataTable; + + /** + * Remove the first item from an API instance's result set. + */ + shift(): any; + + /** + * Sort the elements of the API instance's result set. + * + * @param fn This is a standard Javascript sort comparison function. It accepts two parameters. + */ + sort(fn?: Function): DataTable; + + /** + * Modify the contents of an Api instance's result set, adding or removing items from it as required. + * + * @param index Index at which to start modifying the Api instance's result set. + * @param howMany Number of elements to remove from the result set. + * @param value_1 Item to add to the result set at the index specified by the first parameter. + */ + splice(index: number, howMany: number, value_1?: any | any[], ...value_2: any[]): any[]; + + /** + * Convert the API instance to a jQuery object, with the objects from the instance's result set in the jQuery result set. + */ + to$(): JQuery; + + /** + * Create a native Javascript array object from an API instance. + */ + toArray(): any[]; + + /** + * Convert the API instance to a jQuery object, with the objects from the instance's result set in the jQuery result set. + */ + toJQuery(): JQuery; + + /** + * Create a new API instance containing only the unique items from a the elements in an instance's result set. + */ + unique(): DataTable; + + /** + * Add one or more items to the start of an API instance's result set. + * + * @param value_1 Item to add to the API instance's result set. + */ + unshift(value_1: any | any[], ...value_2: any[]): number; + } + + //#endregion "util-methods" + + interface CommonSubMethods { + /** + * Get the DataTables cached data for the selected cell + * + * @param t Specify which cache the data should be read from. Can take one of two values: search or order + */ + cache(t: string): DataTable; + } + + //#region "cell-methods" + + interface CommonCellMethods extends CommonSubMethods { + /** + * Invalidate the data held in DataTables for the selected cells + * + * @param source Data source to read the new data from. + */ + invalidate(source?: string): DataTable; + + /** + * Get data for the selected cell + * + * @param f Data type to get. This can be one of: 'display', 'filter', 'sort', 'type' + */ + render(t: string): any; + } + + interface CellMethods extends DataTableCore, CommonCellMethods { + /** + * Get data for the selected cell + */ + data(): any; + + /** + * Get data for the selected cell + * + * @param data Value to assign to the data for the cell + */ + data(data: any): DataTable; + + /** + * Get index information about the selected cell + */ + index(): CellIndexReturn; + + /** + * Get the DOM element for the selected cell + */ + node(): Node; + } + + interface CellIndexReturn { + row: number; + column: number; + columnVisible: number; + } + + interface CellsMethods extends DataTableCore, CommonCellMethods { + /** + * Get data for the selected cells + */ + data(): DataTable; + + /** + * Get index information about the selected cells + */ + indexes(): DataTable; + + /** + * Get the DOM elements for the selected cells + */ + nodes(): DataTable; + } + //#endregion "cell-methods" + + //#region "column-methods" + + interface CommonColumnMethod extends CommonSubMethods { + /** + * Get the footer th / td cell for the selected column. + */ + footer(): any; + + /** + * Get the header th / td cell for a column. + */ + header(): Node; + + /** + * Order the table, in the direction specified, by the column selected by the column()DT selector. + * + * @param direction Direction of sort to apply to the selected column - desc (descending) or asc (ascending). + */ + order(direction: string): DataTable; + + /** + * Get the visibility of the selected column. + */ + visible(): boolean; + + /** + * Set the visibility of the selected column. + * + * @param show Specify if the column should be visible (true) or not (false). + * @param redrawCalculations Indicate if DataTables should recalculate the column layout (true - default) or not (false). Typically this would be left as the default value, but it can be useful to disable when using the method in a loop - so the calculations are performed on every call as they can hamper performance. + */ + visible(show: boolean, redrawCalculations?: boolean): DataTable; + } + + interface ColumnMethodsModel { + /** + * Select the column found by a column selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (columnSelector: any, modifier?: ObjectSelectorModifier): ColumnMethods; + + /** + * Convert from the input column index type to that required. + * + * @param t The type on conversion that should take place: 'fromVisible', 'toData', 'fromData', 'toVisible' + * @param index The index to be converted + */ + index(t: string, index: number): number; + } + + interface ColumnMethods extends DataTableCore, CommonColumnMethod { + /** + * Get the data for the cells in the selected column. + */ + data(): DataTable; + + /** + * Get the data source property for the selected column + */ + dataSrc(): number | string | Function; + + /** + * Get index information about the selected cell + * + * @param t Specify if you want to get the column data index (default) or the visible index (visible). + */ + index(t?: string): DataTable; + + /** + * Obtain the th / td nodes for the selected column + */ + nodes(): DataTable[]; + } + + interface ColumnsMethodsModel { + /** + * Select all columns + * + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (modifier?: ObjectSelectorModifier): ColumnsMethods; + + /** + * Select columns found by a cell selector + * + * @param cellSelector Cell selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (columnSelector: any, modifier?: ObjectSelectorModifier): ColumnsMethods; + + /** + * Recalculate the column widths for layout. + */ + adjust(): DataTable; + } + + interface ColumnsMethods extends DataTableCore, CommonColumnMethod { + /** + * Obtain the data for the columns from the selector + */ + data(): DataTable; + + /** + * Get the data source property for the selected columns. + */ + dataSrc(): DataTable; + + /** + * Get the column indexes of the selected columns. + * + * @param t Specify if you want to get the column data index (default) or the visible index (visible). + */ + indexes(t?: string): DataTable; + + /** + * Obtain the th / td nodes for the selected columns + */ + nodes(): DataTable[][]; + } + //#endregion "column-methods" + + //#region "row-methods" + + interface CommonRowMethod extends CommonSubMethods { + /** + * Obtain the th / td nodes for the selected column + * + * @param source Data source to read the new data from. Values: 'auto', 'data', 'dom' + */ + invalidate(source?: string): DataTable; + } + + interface RowChildMethodModel { + /** + * Get the child row(s) that have been set for a parent row + */ + (): JQuery; + + /** + * Get the child row(s) that have been set for a parent row + * + * @param showRemove This parameter can be given as true or false + */ + (showRemove: boolean): RowChildMethods; + + /** + * Set the data to show in the child row(s). Note that calling this method will replace any child rows which are already attached to the parent row. + * + * @param data The data to be shown in the child row can be given in multiple different ways. + * @param className Class name that is added to the td cell node(s) of the child row(s). As of 1.10.1 it is also added to the tr row node of the child row(s). + */ + (data: (string | Node | JQuery) | (string | Node | JQuery)[], className?: string): RowChildMethods; + + /** + * Hide the child row(s) of a parent row + */ + hide(): DataTable; + + /** + * Check if the child rows of a parent row are visible + */ + isShown(): DataTable; + + /** + * Remove child row(s) from display and release any allocated memory + */ + remove(): DataTable; + + /** + * Show the child row(s) of a parent row + */ + show(): DataTable; + } + + interface RowChildMethods extends DataTableCore { + /** + * Hide the child row(s) of a parent row + */ + hide(): DataTable; + + /** + * Remove child row(s) from display and release any allocated memory + */ + remove(): DataTable; + + /** + * Make newly defined child rows visible + */ + show(): DataTable; + } + + interface RowMethodsModel { + /** + * Select a row found by a row selector + * + * @param rowSelector Row selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (rowSelector: any, modifier?: ObjectSelectorModifier): RowMethods; + + /** + * Add a new row to the table using the given data + * + * @param data Data to use for the new row. This may be an array, object or Javascript object instance, but must be in the same format as the other data in the table + */ + add(data: any[]| Object): DataTable; + } + + interface RowMethods extends DataTableCore, CommonRowMethod { + /** + * Order Methods / Object + */ + child: RowChildMethodModel; + + /** + * Get the data for the selected row + */ + data(): any[]| Object; + + /** + * Set the data for the selected row + * + * @param d Data to use for the row. + */ + data(d: any[]| Object): DataTable; + + /** + * Get the row index of the row column. + */ + index(): number; + + /** + * Obtain the tr node for the selected row + */ + node(): Node; + + /** + * Delete the selected row from the DataTable. + */ + remove(): Node; + } + + interface RowsMethodsModel { + /** + * Select all rows + * + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (modifier?: ObjectSelectorModifier): RowsMethods; + + /** + * Select rows found by a row selector + * + * @param cellSelector Row selector. + * @param Option used to specify how the cells should be ordered, and if paging or filtering in the table should be taken into account. + */ + (rowSelector: any, modifier?: ObjectSelectorModifier): RowsMethods; + + /** + * Add new rows to the table using the data given + * + * @param data Array of data elements, with each one describing a new row to be added to the table + */ + add(data: any[]): DataTable; + } + + interface RowsMethods extends DataTableCore, CommonRowMethod { + /** + * Get the data for the rows from the selector + */ + data(): DataTable; + + /** + * Set the data for the selected row + * + * @param d Data to use for the row. + */ + data(d: any[]| Object): DataTable; + + /** + * Get the row indexes of the selected rows. + */ + indexes(): DataTable; + + /** + * Obtain the tr nodes for the selected rows + */ + nodes(): DataTable; + + /** + * Delete the selected rows from the DataTable. + */ + remove(): DataTable; + } + //#endregion "row-methods" + + //#region "table-methods" + + interface TableMethods extends DataTableCore { + /** + * Get the tfoot node for the table in the API's context + */ + footer(): Node; + + /** + * Get the thead node for the table in the API's context + */ + header(): Node; + + /** + * Get the tbody node for the table in the API's context + */ + body(): Node; + + /** + * Get the div container node for the table in the API's context + */ + container(): Node; + + /** + * Get the table node for the table in the API's context + */ + node(): Node; + } + + interface TablesMethods extends DataTableCore { + /** + * Get the tfoot nodes for the tables in the API's context + */ + footer(): DataTable; + + /** + * Get the thead nodes for the tables in the API's context + */ + header(): DataTable; + + /** + * Get the tbody nodes for the tables in the API's context + */ + body(): DataTable; + + /** + * Get the div container nodes for the tables in the API's context + */ + containers(): DataTable; + + /** + * Get the table nodes for the tables in the API's context + */ + nodes(): DataTable; + } + //#endregion "table-methods" + + //#endregion "Namespaces" + + //#region "Static-Methods" + + export interface StaticFunctions { + /** + * Check is a table node is a DataTable or not + * + * @param table Selector string for table + */ + isDataTable(table: string): boolean; + + /** + * Get all DataTables on the page + * + * @param visible Get only visible tables + */ + tables(visible?: boolean): DataTables.DataTable[]; + + /** + * Version number compatibility check function + * + * @param version Version string + */ + versionCheck(version: string): boolean; + + /** + * Utils + */ + util: StaticUtilFunctions; + + /** + * Check is a table node is a DataTable or not + * + * @param table Selector string for table + */ + Api(selector: string | Node | Node[]| JQuery): DataTables.DataTable; + } + + export interface StaticUtilFunctions { + /** + * Escape special characters in a regular expression string. Since: 1.10.4 + * + * @param str String to escape + */ + escapeRegex(str: string): string; + + /** + * Throttle the calls to a method to reduce call frequency. Since: 1.10.3 + * + * @param fn Function + * @param period ms + */ + throttle(fn: Function, period?: number): Function; + } + + //#endregion "Static-Methods" + + //#region "Settings" + + export interface Settings { + + //#region "Features" + + /** + * Feature control DataTables' smart column width handling. Since: 1.10 + */ + autoWidth?: boolean; + + /** + * Feature control deferred rendering for additional speed of initialisation. Since: 1.10 + */ + deferRender?: boolean; + + /** + * Feature control table information display field. Since: 1.10 + */ + info?: boolean; + + /** + * Use markup and classes for the table to be themed by jQuery UI ThemeRoller. Since: 1.10 + */ + jQueryUI?: boolean; + + /** + * Feature control the end user's ability to change the paging display length of the table. Since: 1.10 + */ + lengthChange?: boolean; + + /** + * Feature control ordering (sorting) abilities in DataTables. Since: 1.10 + */ + ordering?: boolean; + + /** + * Enable or disable table pagination. Since: 1.10 + */ + paging?: boolean; + + /** + * Feature control the processing indicator. Since: 1.10 + */ + processing?: boolean; + + /** + * Horizontal scrolling. Since: 1.10 + */ + scrollX?: boolean; + + /** + * Vertical scrolling. Since: 1.10 Exp: "200px" + */ + scrollY?: string; + + /** + * Feature control search (filtering) abilities Since: 1.10 + */ + searching?: boolean; + + /** + * Feature control DataTables' server-side processing mode. Since: 1.10 + */ + serverSide?: boolean; + + /** + * State saving - restore table state on page reload. Since: 1.10 + */ + stateSave?: boolean; + + //#endregion "Features" + + //#region "Data" + + /** + * Load data for the table's content from an Ajax source. Since: 1.10 + */ + ajax?: string | AjaxSettings | FunctionAjax; + + /** + * Data to use as the display data for the table. Since: 1.10 + */ + data?: Object; + + //#endregion "Data" + + //#region "Options" + + /** + * Data to use as the display data for the table. Since: 1.10 + */ + columns?: ColumnSettings[]; + + /** + * Assign a column definition to one or more columns.. Since: 1.10 + */ + columnDefs?: ColumnDefsSettings[]; + + /** + * Delay the loading of server-side data until second draw + */ + deferLoading?: number | number[]; + + /** + * Destroy any existing table matching the selector and replace with the new options. Since: 1.10 + */ + destroy?: boolean; + + /** + * Initial paging start point. Since: 1.10 + */ + displayStart?: number; + + /** + * Define the table control elements to appear on the page and in what order. Since: 1.10 + */ + dom?: string; + + /** + * Change the options in the page length select list. Since: 1.10 + */ + lengthMenu?: (number | string)[]| (number | string)[][]; + + /** + * Control which cell the order event handler will be applied to in a column. Since: 1.10 + */ + orderCellsTop?: boolean; + + /** + * Highlight the columns being ordered in the table's body. Since: 1.10 + */ + orderClasses?: boolean; + + /** + * Initial order (sort) to apply to the table. Since: 1.10 + */ + order?: (string | number)[]| (string | number)[][]; + + /** + * Ordering to always be applied to the table. Since: 1.10 + */ + orderFixed?: (string | number)[]| (string | number)[][]| Object; + + /** + * Multiple column ordering ability control. Since: 1.10 + */ + orderMulti?: boolean; + + /** + * Change the initial page length (number of rows per page). Since: 1.10 + */ + pageLength?: number; + + /** + * Pagination button display options. Basic Types: simple, simple_numbers, full, full_numbers + */ + pagingType?: string; + + /** + * Retrieve an existing DataTables instance. Since: 1.10 + */ + retrieve?: boolean + + /** + * Display component renderer types. Since: 1.10 + */ + renderer?: string | RendererSettings; + + /** + * Allow the table to reduce in height when a limited number of rows are shown. Since: 1.10 + */ + scrollCollapse?: boolean; + + /** + * Set an initial filter in DataTables and / or filtering options. Since: 1.10 + */ + search?: SearchSettings; + + /** + * Define an initial search for individual columns. Since: 1.10 + */ + searchCols?: SearchSettings[]; + + /** + * Set a throttle frequency for searching. Since: 1.10 + */ + searchDelay?: number; + + /** + * Saved state validity duration. Since: 1.10 + */ + stateDuration?: number; + + /** + * Set the zebra stripe class names for the rows in the table. Since: 1.10 + */ + stripeClasses?: string[]; + + /** + * Tab index control for keyboard navigation. Since: 1.10 + */ + tabIndex?: number; + + //#endregion "Options" + + //#region "Callbacks" + + /** + * Callback for whenever a TR element is created for the table's body. Since: 1.10 + */ + createdRow?: FunctionCreateRow; + + /** + * Function that is called every time DataTables performs a draw. Since: 1.10 + */ + drawCallback?: FunctionDrawCallback; + + /** + * Footer display callback function. Since: 1.10 + */ + footerCallback?: FunctionFooterCallback; + + /** + * Number formatting callback function. Since: 1.10 + */ + formatNumber?: FunctionFormatNumber; + + /** + * Header display callback function. Since: 1.10 + */ + headerCallback?: FunctionHeaderCallback; + + /** + * Table summary information display callback. Since: 1.10 + */ + infoCallback?: FunctionInfoCallback; + + /** + * Initialisation complete callback. Since: 1.10 + */ + initComplete?: FunctionInitComplete; + + /** + * Pre-draw callback. Since: 1.10 + */ + preDrawCallback?: FunctionPreDrawCallback; + + /** + * Row draw callback.. Since: 1.10 + */ + rowCallback?: FunctionRowCallback; + + /** + * Callback that defines where and how a saved state should be loaded. Since: 1.10 + */ + stateLoadCallback?: FunctionStateLoadCallback; + + /** + * State loaded callback. Since: 1.10 + */ + stateLoaded?: FunctionStateLoaded; + + /** + * State loaded - data manipulation callback. Since: 1.10 + */ + stateLoadParams?: FunctionStateLoadParams; + + /** + * Callback that defines how the table state is stored and where. Since: 1.10 + */ + stateSaveCallback?: FunctionStateSaveCallback; + + /** + * State save - data manipulation callback. Since: 1.10 + */ + stateSaveParams?: FunctionStateSaveParams; + + //#endregion "Callbacks" + + //#region "Language" + + language?: LanguageSettings; + + //#endregion "Language" + } + + //#region "ajax-settings" + + export interface AjaxDataRequest { + draw: number; + start: number; + length: number; + data: any; + order: AjaxDataRequestOrder[]; + columns: AjaxDataRequestColumn[]; + search: AjaxDataRequestSearch; + } + + export interface AjaxDataRequestSearch { + value: string; + regex: boolean; + } + + export interface AjaxDataRequestOrder { + column: number; + dir: string; + } + + export interface AjaxDataRequestColumn { + data: string | number; + name: string; + searchable: boolean; + orderable: boolean; + search: AjaxDataRequestSearch; + } + + export interface AjaxData { + draw: number; + recordsTotal: number; + recordsFiltered: number; + data: any; + error?: string; + } + + interface AjaxSettings extends JQueryAjaxSettings { + /** + * Add or modify data submitted to the server upon an Ajax request. Since: 1.10 + */ + data?: Object | FunctionAjaxData; + + /** + * Data property or manipulation method for table data. Since: 1.10 + */ + dataSrc?: string | Function; + } + + interface FunctionAjax { + (data: Object, callback: Function, settings: SettingsLegacy): void; + } + + interface FunctionAjaxData { + (data: Object): string | Object; + } + + //#endregion "ajax-settings" + + //#region "colunm-settings" + + export interface ColumnSettings { + /** + * Cell type to be created for a column. th/td Since: 1.10 + */ + cellType?: string; + + /** + * Class to assign to each cell in the column. Since: 1.10 + */ + className?: string; + + /** + * Add padding to the text content used when calculating the optimal with for a table. Since: 1.10 + */ + contentPadding?: string; + + /** + * Cell created callback to allow DOM manipulation. Since: 1.10 + */ + createdCell?: FunctionColumnCreatedCell; + + /** + * Class to assign to each cell in the column. Since: 1.10 + */ + data?: number | string | ObjectColumnData | FunctionColumnData; + + /** + * Set default, static, content for a column. Since: 1.10 + */ + defaultContent?: string; + + /** + * Set a descriptive name for a column. Since: 1.10 + */ + name?: string; + + /** + * Enable or disable ordering on this column. Since: 1.10 + */ + orderable?: boolean; + + /** + * Define multiple column ordering as the default order for a column. Since: 1.10 + */ + orderData?: number | number[]; + + /** + * Live DOM sorting type assignment. Since: 1.10 + */ + orderDataType?: string; + + /** + * Order direction application sequence. Since: 1.10 + */ + orderSequence?: string[]; + + /** + * Render (process) the data for use in the table. Since: 1.10 + */ + render?: number | string | ObjectColumnRender | FunctionColumnRender; + + /** + * Enable or disable filtering on the data in this column. Since: 1.10 + */ + searchable?: boolean; + + /** + * Set the column title. Since: 1.10 + */ + title?: string; + + /** + * Set the column type - used for filtering and sorting string processing. Since: 1.10 + */ + type?: string; + + /** + * Enable or disable the display of this column. Since: 1.10 + */ + visible?: boolean; + + /** + * Column width assignment. Since: 1.10 + */ + width?: string; + } + + interface ColumnDefsSettings extends ColumnSettings { + targets: string | number | (number | string)[] + } + + interface FunctionColumnCreatedCell { + (cell: Node, cellData: any, rowData: any, row: number, col: number): void; + } + + interface FunctionColumnData { + (row: any, t: string, s: any, meta: Object): void; + } + + interface ObjectColumnData { + _: string; + filter?: string; + display?: string; + type?: string; + sort?: string; + } + + interface ObjectColumnRender extends ObjectColumnData { + } + + interface FunctionColumnRender { + (data: Node, t: Node, row: Node, meta: Object): void; + } + + //#endregion "colunm-settings" + + //#region "other-settings" + + export interface RendererSettings { + header?: string; + pageButton?: string; + } + + export interface SearchSettings { + /** + * Control case-sensitive filtering option. Since: 1.10 + */ + caseInsensitive?: boolean; + + /** + * Enable / disable escaping of regular expression characters in the search term. Since: 1.10 + */ + regex?: boolean; + + /** + * Enable / disable DataTables' smart filtering. Since: 1.10 + */ + smart?: boolean; + + /** + * Set an initial filtering condition on the table. Since: 1.10 + */ + search?: string; + } + + //#endregion "other-settings" + + //#region "callback-functions" + + interface FunctionCreateRow { + (row: Node, data: any[]| Object, dataIndex: number): void; + } + + interface FunctionDrawCallback { + (settings: SettingsLegacy): void; + } + + interface FunctionFooterCallback { + (tfoot: Node, data: any[], start: number, end: number, display: any[]): void; + } + + interface FunctionFormatNumber { + (formatNumber: number): void; + } + + interface FunctionHeaderCallback { + (thead: Node, data: any[], start: number, end: number, display: any[]): void; + } + + interface FunctionInfoCallback { + (settings: SettingsLegacy, start: number, end: number, mnax: number, total: number, pre: string): void; + } + + interface FunctionInitComplete { + (settings: SettingsLegacy, json: Object): void; + } + + interface FunctionPreDrawCallback { + (settings: SettingsLegacy): void; + } + + interface FunctionRowCallback { + (row: Node, data: any[]| Object): void; + } + + interface FunctionStateLoadCallback { + (settings: SettingsLegacy): void; + } + + interface FunctionStateLoaded { + (settings: SettingsLegacy, data: Object): void; + } + + interface FunctionStateLoadParams { + (settings: SettingsLegacy, data: Object): void; + } + + interface FunctionStateSaveCallback { + (settings: SettingsLegacy, data: Object): void; + } + + interface FunctionStateSaveParams { + (settings: SettingsLegacy, data: Object): void; + } + + //#endregion "callback-functions" + + //#region "language-settings" + + interface LanguageSettings { + emptyTable: string; + info: string; + infoEmpty: string; + infoFiltered: string; + infoPostFix: string; + thousands: string; + lengthMenu: string; + loadingRecords: string; + processing: string; + search: string; + zeroRecords: string; + paginate: LanguagePaginateSettings; + aria: LanguageAriaSettings; + } + + interface LanguagePaginateSettings { + first: string; + last: string; + next: string; + previous: string; + } + + interface LanguageAriaSettings { + sortAscending: string; + sortDescending: string; + } + + //#endregion "language-settings" + + //#endregion "Settings" + + //#region "SettingsLegacy" + + interface ArrayStringNode { + [index: string]: Node; + } + + export interface SettingsLegacy { + ajax: any; + oApi: any; + oFeatures: FeaturesLegacy; + oScroll: ScrollingLegacy; + oLanguage: LanguageLegacy; // | { fnInfoCallback: FunctionInfoCallback; }; + oBrowser: { bScrollOversize: boolean; }; + aanFeatures: ArrayStringNode[][]; + aoData: RowLegacy[]; + aiDisplay: number[]; + aiDisplayMaster: number[]; + aoColumns: ColumnLegacy[]; + aoHeader: any[]; + aoFooter: any[]; + asDataSearch: string[]; + oPreviousSearch: any; + aoPreSearchCols: any[]; + aaSorting: any[][]; + aaSortingFixed: any[][]; + asStripeClasses: string[]; + asDestroyStripes: string[]; + sDestroyWidth: number; + aoRowCallback: FunctionRowCallback[]; + aoHeaderCallback: FunctionHeaderCallback[]; + aoFooterCallback: FunctionFooterCallback[]; + aoDrawCallback: FunctionDrawCallback[]; + aoRowCreatedCallback: FunctionCreateRow[]; + aoPreDrawCallback: FunctionPreDrawCallback[]; + aoInitComplete: FunctionInitComplete[]; + aoStateSaveParams: FunctionStateSaveParams[]; + aoStateLoadParams: FunctionStateLoadParams[]; + aoStateLoaded: FunctionStateLoaded[]; + sTableId: string; + nTable: Node; + nTHead: Node; + nTFoot: Node; + nTBody: Node; + nTableWrapper: Node; + bDeferLoading: boolean; + bInitialized: boolean; + aoOpenRows: any[]; + sDom: string; + sPaginationType: string; + iCookieDuration: number; + sCookiePrefix: string; + fnCookieCallback: CookieCallbackLegacy; + aoStateSave: FunctionStateSaveCallback[]; + aoStateLoad: FunctionStateLoadCallback[]; + oLoadedState: any; + sAjaxSource: string; + sAjaxDataProp: string; + bAjaxDataGet: boolean; + jqXHR: any; + fnServerData: any; + aoServerParams: any[]; + sServerMethod: string; + fnFormatNumber: FunctionFormatNumber; + aLengthMenu: any[]; + iDraw: number; + bDrawing: boolean; + iDrawError: number; + _iDisplayLength: number; + _iDisplayStart: number; + _iDisplayEnd: number; + _iRecordsTotal: number; + _iRecordsDisplay: number; + bJUI: boolean; + oClasses: any; + bFiltered: boolean; + bSorted: boolean; + bSortCellsTop: boolean; + oInit: any; + aoDestroyCallback: any[]; + fnRecordsTotal: () => number; + fnRecordsDisplay: () => number; + fnDisplayEnd: () => number; + oInstance: any; + sInstance: string; + iTabIndex: number; + nScrollHead: Node; + nScrollFoot: Node; + } + + export interface FeaturesLegacy { + bAutoWidth: boolean; + bDeferRender: boolean; + bFilter: boolean; + bInfo: boolean; + bLengthChange: boolean; + bPaginate: boolean; + bProcessing: boolean; + bServerSide: boolean; + bSort: boolean; + bSortClasses: boolean; + bStateSave: boolean; + } + + export interface ScrollingLegacy { + bAutoCss: boolean; + bCollapse: boolean; + bInfinite: boolean; + iBarWidth: number; + iLoadGap: number; + sX: string; + sY: string; + } + + export interface RowLegacy { + nTr: Node; + _aData: any; + _aSortData: any[]; + _anHidden: Node[]; + _sRowStripe: string; + } + + export interface ColumnLegacy { + aDataSort: any; + asSorting: string[]; + bSearchable: boolean; + bSortable: boolean; + bVisible: boolean; + _bAutoType: boolean; + fnCreatedCell: FunctionColumnCreatedCell; + fnGetData: (data: any, specific: string) => any; + fnSetData: (data: any, value: any) => void; + mData: any; + mRender: any; + nTh: Node; + nIf: Node; + sClass: string; + sContentPadding: string; + sDefaultContent: string; + sName: string; + sSortDataType: string; + sSortingClass: string; + sSortingClassJUI: string; + sTitle: string; + sType: string; + sWidth: string; + sWidthOrig: string; + } + + export interface CookieCallbackLegacy { + (name: string, data: any, expires: string, path: string, cookie: string): void; + } + + export interface LanguageLegacy { + oAria?: LanguageAriaLegacy; + oPaginate?: LanguagePaginateLegacy; + sEmptyTable?: string; + sInfo?: string; + sInfoEmpty?: string; + sInfoFiltered?: string; + sInfoPostFix?: string; + sInfoThousands?: string; + sLengthMenu?: string; + sLoadingRecords?: string; + sProcessing?: string; + sSearch?: string; + sUrl?: string; + sZeroRecords?: string; + } + + export interface LanguageAriaLegacy { + sSortAscending?: string; + sSortDescending?: string; + } + + export interface LanguagePaginateLegacy { + sFirst?: string; + sLast?: string; + sNext?: string; + sPrevious?: string; + } + //#endregion "SettingsLegacy" + +} \ No newline at end of file diff --git a/jquery.pickadate/jquery.pickadate.d.ts b/jquery.pickadate/jquery.pickadate.d.ts index 274f20f909..62b20bb228 100644 --- a/jquery.pickadate/jquery.pickadate.d.ts +++ b/jquery.pickadate/jquery.pickadate.d.ts @@ -39,6 +39,7 @@ interface pickadateOptions extends pickerOptions { 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: @@ -223,23 +224,21 @@ interface TimePickerSetThings extends SetThings { interval?: any; } -interface PickerObject { +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; -} -interface DatePickerObject extends PickerObject { - open(withoutFocus?: boolean): DatePickerObject; - close(withFocus?: boolean): DatePickerObject; + open(withoutFocus?: boolean): TPickerObject; + close(withFocus?: boolean): TPickerObject; /** Rebuild the picker. */ - start(): DatePickerObject; + start(): TPickerObject; /** Destroy the picker. */ - stop(): DatePickerObject; + stop(): TPickerObject; /** * Refresh the picker box after adding something to the holder. @@ -247,10 +246,10 @@ interface DatePickerObject extends PickerObject { * has it’s contents re-rendered. To render the entire picker from * the root up, pass true as the first argument. */ - render(entirePicker?: boolean): DatePickerObject; + render(entirePicker?: boolean): TPickerObject; /** Clear the value in the picker's input element. */ - clear(): DatePickerObject; + clear(): TPickerObject; /** Short for picker.get('value') */ get(): string; @@ -262,19 +261,19 @@ interface DatePickerObject extends PickerObject { get(thing: 'value'): string; /** Returns the item object that is visually selected. */ - get(thing: 'select'): DatePickerItemObject; + get(thing: 'select'): TItemObject; /** Returns the item object that is visually highlighted. */ - get(thing: 'highlight'): DatePickerItemObject; + get(thing: 'highlight'): TItemObject; /** Returns the item object that sets the current view. */ - get(thing: 'view'): DatePickerItemObject; + get(thing: 'view'): TItemObject; /** Returns the item object that limits the picker's lower range. */ - get(thing: 'min'): DatePickerItemObject; + get(thing: 'min'): TItemObject; /** Returns the item object that limits the picker's upper range. */ - get(thing: 'max'): DatePickerItemObject; + get(thing: 'max'): TItemObject; /** Returns a boolean value of whether the picker is open or not. */ get(thing: 'open'): boolean; @@ -292,99 +291,29 @@ interface DatePickerObject extends PickerObject { get(thing: string, format: string): string; /** Set the properties, objects, and states to change the state of the picker. */ - set(thing: string, value?: any): DatePickerObject; - set(things: SetThings): DatePickerObject; + 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 ): DatePickerObject; + on(methodName, callback: () => void): TPickerObject; /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ - on(callbackObject: CallbackObject): DatePickerObject; + on(callbackObject: CallbackObject): TPickerObject; /** Trigger callbacks that have been queued up using the the on method. */ - trigger(event: string): DatePickerObject; + trigger(event: string): TPickerObject; } -interface TimePickerObject extends PickerObject { - open(withoutFocus?: boolean): TimePickerObject; - close(withFocus?: boolean): TimePickerObject; - - /** Rebuild the picker. */ - start(): TimePickerObject; - - /** Destroy the picker. */ - stop(): TimePickerObject; - - /** - * 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): TimePickerObject; - - /** Clear the value in the picker's input element. */ - clear(): TimePickerObject; - - /** 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'): TimePickerItemObject; - - /** Returns the item object that is visually highlighted. */ - get(thing: 'highlight'): TimePickerItemObject; - - /** Returns the item object that sets the current view. */ - get(thing: 'view'): TimePickerItemObject; - - /** Returns the item object that limits the picker's lower range. */ - get(thing: 'min'): TimePickerItemObject; - - /** Returns the item object that limits the picker's upper range. */ - get(thing: 'max'): TimePickerItemObject; - - /** 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): TimePickerObject; - set(things: TimePickerSetThings): TimePickerObject; - - /** Bind callbacks to get fired off when the relative picker method is called. */ - on(methodName, callback: () => void ): TimePickerObject; - - /** Bind multiple callbacks at once to get fired off when the relative picker method is called. */ - on(callbackObject: CallbackObject): TimePickerObject; - - /** Trigger callbacks that have been queued up using the the on method. */ - trigger(event: string): TimePickerObject; -} +interface DatePickerObject extends PickerObject { } +interface TimePickerObject extends PickerObject { } interface JQuery { - pickadate(options?: pickadateOptions): HTMLInputElement; - pickatime(options?: pickatimeOptions): HTMLInputElement; + pickadate(methodName: "picker"): DatePickerObject; + pickadate(methodName: string): any; + pickadate(options?: pickadateOptions): JQuery; + + pickatime(methodName: "picker"): TimePickerObject; + pickatime(methodName: string): any; + pickatime(options?: pickatimeOptions): JQuery; } -interface HTMLInputElement { - pickadate(picker: string): DatePickerObject; - pickatime(picker: string): TimePickerObject; -} diff --git a/jquery.window/jquery.window-tests.ts b/jquery.window/jquery.window-tests.ts new file mode 100644 index 0000000000..0b5fa7e83f --- /dev/null +++ b/jquery.window/jquery.window-tests.ts @@ -0,0 +1,139 @@ +/// +/// + +function example_1() { + $.window({ + title: "Cyclops Studio", + url: "http://apps.fstoke.me/" + }); +} + +function example_2() { + $.window({ + showModal: true, + modalOpacity: 0.5, + icon: "http://www.fstoke.me/favicon.ico", + title: "Professional JavaScript for Web Developers", + content: $("#window_block2").html(), // load window_block2 html content + footerContent: " This is a nice plugin :^)" + }); +}; + +function example_3() { + // prepare customerized static attributes, see static attributes + // Note: you should call this method before starting to create window instances, or windows might display wrong. + $.window.prepare({ + dock: 'bottom', // change the dock direction: 'left', 'right', 'top', 'bottom' + animationSpeed: 200, // set animation speed + minWinLong: 180 // set minimized window long dimension width in pixel + }); + + // limit window within body + $.window({ + icon: 'http://www.fstoke.me/favicon.ico', + title: "This window only can be dragged within body boundary", + content: "
I only can be dragged within body element." + + "

Really? Really? You can try it... :)
", + checkBoundary: true, + x: 80, + y: 80 + }); + + // limit window within a element + $("#my_boundary_panel").window({ + icon: 'http://mail.google.com/favicon.ico', + title: "This window only can be dragged within its parent element", + content: "
I only can be dragged within my boss...@@
", + checkBoundary: true, + width: 200, + height: 160, + maxWidth: 400, + maxHeight: 300, + x: 80, + y: 80 + }); + + // assign the dock area + $.window.prepare({ + dock: 'bottom', // change the dock direction: 'left', 'right', 'top', 'bottom' + dockArea: $('#myDockArea'), // set the dock area + animationSpeed: 200, // set animation speed + minWinLong: 180 // set minimized window long dimension width in pixel + }); +} + +function example_4() { + $.window({ + title: "Un-draggable & Un-resizable Window", + content: "
I can't be dragged...
" + + "I can't be resized too...

Of course, maximize and minimize are also disabled...

" + + "So... What can I do? I only can be closed. @_@
", + draggable: false, + resizable: false, + maximizable: false, + minimizable: false, + showModal: true + }); +} + +function example_5() { + var log = console.log; + $.window({ + title: "complext window", + content: $("#window_block5").html(), // load window_block5 html content + x: 150, // the x-axis value on screen, if -1 means put on screen center + y: 100, // the y-axis value on screen, if -1 means put on screen center + width: 600, // window width + height: 300, // window height + minWidth: 200, // the minimum width, if -1 means no checking + minHeight: 100, // the minimum height, if -1 means no checking + maxWidth: 700, // the minimum width, if -1 means no checking + maxHeight: 400, // the minimum height, if -1 means no checking + scrollable: false, // a boolean flag to show scroll bar or not + onOpen: (wnd: JQueryWindow.Window) => { // a callback function while container is added into body + alert('open'); + }, + onShow: (wnd: JQueryWindow.Window) => { // a callback function while whole window display routine is finished + alert('show'); + }, + onClose: (wnd: JQueryWindow.Window) => { // a callback function while user click close button + alert('close'); + }, + onSelect: (wnd: JQueryWindow.Window) => { // a callback function while user select the window + log('select'); + }, + onUnselect: (wnd: JQueryWindow.Window) => { // a callback function while window unselected + log('unelect'); + }, + onDrag: (wnd: JQueryWindow.Window) => { // a callback function while window is going to drag + log('drag'); + }, + afterDrag: (wnd: JQueryWindow.Window) => { // a callback function after window dragged + log('after dragged'); + }, + onResize: (wnd: JQueryWindow.Window) => { // a callback function while window is going to resize + log('resize'); + }, + afterResize: (wnd: JQueryWindow.Window) => { // a callback function after window resized + log('after resized'); + }, + onMinimize: (wnd: JQueryWindow.Window) => { // a callback function while window is going to minimize + log('minimize'); + }, + afterMinimize: (wnd: JQueryWindow.Window) => { // a callback function after window minimized + log('after minimized'); + }, + onMaximize: (wnd: JQueryWindow.Window) => { // a callback function while window is going to maximize + log('maximize'); + }, + afterMaximize: (wnd: JQueryWindow.Window) => { // a callback function after window maximized + log('after maximized'); + }, + onCascade: (wnd: JQueryWindow.Window) => { // a callback function while window is going to cascade + log('cascade'); + }, + afterCascade: (wnd: JQueryWindow.Window) => { // a callback function after window cascaded + log('after cascaded'); + } + }); +} \ No newline at end of file diff --git a/jquery.window/jquery.window.d.ts b/jquery.window/jquery.window.d.ts new file mode 100644 index 0000000000..8fb4bbc818 --- /dev/null +++ b/jquery.window/jquery.window.d.ts @@ -0,0 +1,460 @@ +// Type definitions for Window plugin for jQuery 5.0.4 +// Project: http://fstoke.me/jquery/window/ +// Definitions by: Ryan Graham +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQueryWindow { + // Instance methods + interface Window { + /** + get window id + **/ + getWindowId(): string; + /** + get window container's parent panel, it's a jQuery object + **/ + getCaller(): JQuery; + /** + get window container panel, it's a jQuery object + **/ + getContainer(): JQuery; + /** + get window header panel, it's a jQuery object + **/ + getHeader(): JQuery; + /** + get window frame panel, it's a jQuery object + **/ + getFrame(): JQuery; + /** + get window footer panel, it's a jQuery object + **/ + getFooter(): JQuery; + /** + set current window as screen center + **/ + alignCenter(): void; + /** + set current window as horizontal center + **/ + alignHorizontalCenter(): void; + /** + set current window as vertical center + **/ + alignVerticalCenter(): void; + /** + select current window, it will increase the original z-index value with 2 + **/ + select(): void; + /** + unselect current window, it will set the z-index as original options.z + **/ + unselect(): void; + /** + move current window to target position or shift it by passed distance + **/ + move(x: number, y: number, bShift: boolean): void; + /** + resize current window to target width/height + **/ + resize(width: number, height: number): void; + /** + maximize current window + **/ + maximize(): void; + /** + minimize current window + **/ + minimize(): void; + /** + restore current window, it could be maximized or cascade status + **/ + restore(): void; + /** + close current window + **/ + close(quiet: boolean): void; + /** + hide current window + **/ + hide(): void; + /** + show current window + **/ + show(): void; + /** + change window title + **/ + setTitle(title: string): void; + /** + change iframe url + **/ + setUrl(url: string): void; + /** + change frame content + **/ + setContent(content: string|JQuery|HTMLElement): void; + /** + change footer content + **/ + setFooterContent(content: string|JQuery|HTMLElement): void; + /** + get window title text + **/ + getTitle(): string; + /** + get url string + **/ + getUrl(): string; + /** + get frame html content + **/ + getContent(): string; + /** + get footer html content + **/ + getFooterContent(): string; + /** + get window maximized status + **/ + isMaximized(): boolean; + /** + get window minmized status + **/ + isMinimized(): boolean; + /** + get window selected status + **/ + isSelected(): boolean; + /** + set window icon + **/ + setIcon(iconUrl: string): void; + /** + show window icon + **/ + showIcon(): void; + /** + hide window icon + **/ + hideIcon(): void; + } + + // Static methods + interface Static { + (options: WindowOptions): JQueryWindow.Window; + /** + initialize with customerized static setting attributes + **/ + prepare(options?: StaticOptions): void; + /** + close all created windows + **/ + closeAll(quiet?: boolean): void; + /** + hide all created windows + **/ + hideAll(): void; + /** + show all created windows + **/ + showAll(): void; + /** + return all created windows instance + **/ + getAll(): Array; + /** + get the window instance by passed window id + **/ + getWindow(windowId: string): JQueryWindow.Window; + /** + get the selected window instance + **/ + getSelectedWindow(): JQueryWindow.Window; + } + + // Static options + interface StaticOptions { + /** + the direction of minimized window dock at. the available values are [left, right, top, bottom] + **/ + dock?: string; + /** + the area which the windows will dock at + **/ + dockArea?: JQuery|HTMLElement; + /** + the speed of animations: maximize, minimize, restore, shift, in milliseconds + **/ + animationSpeed?: number; + /** + the narrow dimension of minimized window + **/ + minWinNarrow?: number; + /** + the long dimension of minimized window + **/ + minWinLong?: number; + /** + to handle browser scrollbar when window status changed(maximize, minimize, cascade) + **/ + handleScrollbar?: boolean; + /** + to decide show log in firebug, IE8, chrome console + **/ + showLog?: boolean; + } + + // Instance options + interface WindowOptions { + /** + an icon image url string. if this attribute is given, it will force to replace the original favicon of remote page on window. or you can set it as null to hide icon. + **/ + icon?: string; + /** + the title text of window + **/ + title: string; + /** + the target url of iframe ready to load. + **/ + url?: string; + /** + this attribute only works when url is null. when passing a jquery object or a element, it will clone the original one to append. + **/ + content?: string|JQuery|HTMLElement; + /** + same as content attribute, but it's put on footer panel. + **/ + footerContent?: string|JQuery|HTMLElement; + /** + container extra class + **/ + containerClass?: string; + /** + header extra class + **/ + headerClass?: string; + /** + frame extra class + **/ + frameClass?: string; + /** + footer extra class + **/ + footerClass?: string; + /** + selected header extra class + **/ + selectedHeaderClass?: string; + /** + the x-axis value on screen(or caller element), if -1 means put on screen(or caller element) center + **/ + x?: number; + /** + the y-axis value on screen(or caller element), if -1 means put on screen(or caller element) center + **/ + y?: number; + /** + the css z-index value + **/ + z?: number; + /** + window width + **/ + width?: number; + /** + window height + **/ + height?: number; + /** + the minimum width, if -1 means no checking + **/ + minWidth?: number; + /** + the minimum height, if -1 means no checking + **/ + minHeight?: number; + /** + the maximum width, if -1 means no checking + **/ + maxWidth?: number; + /** + the maximum height, if -1 means no checking + **/ + maxHeight?: number; + /** + to control show modal on background + **/ + showModal?: boolean; + /** + the opacity of modal dialog + **/ + modalOpacity?: number; + /** + to control show footer panel + **/ + showFooter?: boolean; + /** + to control display window as round corner + **/ + showRoundCorner?: boolean; + /** + to control window closable + **/ + closable?: boolean; + /** + to control window minimizable + **/ + minimizable?: boolean; + /** + to control window maximizable + **/ + maximizable?: boolean; + /** + to control window with remote url could be bookmarked + **/ + bookmarkable?: boolean; + /** + to control window draggable + **/ + draggable?: boolean; + /** + to control window resizable + **/ + resizable?: boolean; + /** + to show scroll bar or not + **/ + scrollable?: boolean; + /** + to check window dialog overflow html body or caller element + **/ + checkBoundary?: boolean; + /** + to limit window only can be dragged within browser window. this attribute only works when checkBoundary is true and caller is null. + **/ + withinBrowserWindow?: boolean; + /** + to describe the customized button display and callback function + **/ + custBtns?: Array; + /** + a callback function while container is added into body + **/ + onOpen?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while whole window display routine is finished + **/ + onShow?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while user click close button + **/ + onClose?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while user select the window + **/ + onSelect?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window unselected + **/ + onUnselect?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to drag + **/ + onDrag?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window dragged + **/ + afterDrag?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to resize + **/ + onResize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window resized + **/ + afterResize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to minimize + **/ + onMinimize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window minimized + **/ + afterMinimize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to maximize + **/ + onMaximize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window maximized + **/ + afterMaximize?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while window is going to cascade + **/ + onCascade?: (wnd: JQueryWindow.Window) => void; + /** + a callback function after window cascaded + **/ + afterCascade?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while iframe ready to connect remoting url. this attribute only works while url attribute is given + **/ + onIframeStart?: (wnd: JQueryWindow.Window) => void; + /** + a callback function while iframe load finished. this attribute only works while url attribute is given + **/ + onIframeEnd?: (wnd: JQueryWindow.Window) => void; + /** + if null means no check, or pass a string to show warning message while iframe is going to redirect current top page + **/ + iframeRedirectCheckMsg?: string; + /** + random the new created window position, it only works when options x,y value both are -1 + **/ + createRandomOffset?: { x: number; y: number }; + } + + // Button definition + interface Button { + /** + + **/ + id: string; + /** + + **/ + title?: string; + /** + + **/ + clazz?: string; + /** + + **/ + style?: string; + /** + + **/ + image: string; + /** + + **/ + callback: (btn: JQueryWindow.Button, wnd: JQueryWindow.Window) => void; + } + +} + +// Register with JQuery instance +interface JQuery { + window(options: JQueryWindow.WindowOptions): JQueryWindow.Window; +} + +// Register with JQuery static +interface JQueryStatic { + window: JQueryWindow.Static; +} \ No newline at end of file diff --git a/jsonpath/jsonpath-tests.ts b/jsonpath/jsonpath-tests.ts new file mode 100644 index 0000000000..d7fd50868a --- /dev/null +++ b/jsonpath/jsonpath-tests.ts @@ -0,0 +1,55 @@ +/// + +import jp = require('jsonpath'); + +var data: any; + +/** + * jp.query(obj, pathExpression) + * Find elements in obj matching pathExpression. Returns an array of elements that satisfy the provided JSONPath expression, or an empty array if none were matched. + */ +var authors = jp.query(data, '$..author'); + +/** + * jp.paths(obj, pathExpression) + * Find elements in obj matching pathExpression. Returns an array of element paths that satisfy the provided JSONPath expression. Each path is itself an array of keys representing the location within obj of the matching element. + */ +var paths = jp.paths(data, '$..author'); + +/** + * jp.nodes(obj, pathExpression) + * Find elements and their corresponding paths in obj matching pathExpression. Returns an array of node objects where each node has a path containing an array of keys representing the location within obj, and a value pointing to the matched element. + */ +var nodes = jp.nodes(data, '$..author'); + +/** + * jp.value(obj, pathExpression, [newValue]) + * Returns the value of the first element matching pathExpression. If newValue is provided, sets the value of the first matching element and returns the new value. + */ +var value = jp.value(data, '$.store..price'); +jp.value(data, '$.store..price', 12.5); + +/** + * jp.parent(obj, pathExpression) + * Returns the parent of the first matching element. + */ +var parent = jp.parent(data, '$.store..price'); + +/** + * jp.apply(obj, pathExpression, fn) + * Runs the supplied function fn on each matching element, and replaces each matching element with the return value from the function. The function accepts the value of the matching element as its only parameter. Returns matching nodes with their updated values. + */ +var nodes = jp.apply(data, '$..author', (value: string) => { return value.toUpperCase() }); + +/** + * jp.parse(pathExpression) + * Parse the provided JSONPath expression into path components and their associated operations. + */ +var path = jp.parse('$..author'); + +/** + * jp.stringify(path) + * Returns a path expression in string form, given a path. The supplied path may either be a flat array of keys, as returned by jp.nodes for example, or may alternatively be a fully parsed path expression in the form of an array of path components as returned by jp.parse. + */ +var pathExpression = jp.stringify(['$', 'store', 'book', 0, 'author']); + diff --git a/jsonpath/jsonpath.d.ts b/jsonpath/jsonpath.d.ts new file mode 100644 index 0000000000..db53220176 --- /dev/null +++ b/jsonpath/jsonpath.d.ts @@ -0,0 +1,21 @@ +// Type definitions for jsonpath 0.1.3 +// Project: https://www.npmjs.org/package/jsonpath +// Definitions by: Hiroki Horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "jsonpath" { + + type PathComponent = string|number; + + export function query(obj: any, pathExpression: string): any[]; + export function paths(obj: any, pathExpression: string): PathComponent[][]; + export function nodes(obj: any, pathExpression: string): { path: PathComponent[]; value: any; }[]; + export function value(obj: any, pathExpression: string): any; + export function value(obj: any, pathExpression: string, newValue: any): any; + export function parent(obj: any, pathExpression: string): any; + export function apply(obj: any, pathExpression: string, fn: (x: any) => any): { path: PathComponent[]; value: any; }[]; + export function parse(pathExpression: string): any[]; + export function stringify(path: PathComponent[]): string; + +} + diff --git a/knex/knex-test.ts b/knex/knex-test.ts new file mode 100644 index 0000000000..39b441d6b0 --- /dev/null +++ b/knex/knex-test.ts @@ -0,0 +1,569 @@ +/// +/// +import Knex = require('knex'); +import _ = require('lodash'); +'use strict'; +// Initializing the Library +var knex = Knex({ + client: 'sqlite3', + connection: { + filename: "./mydb.sqlite" + } +}); + +var knex = Knex({ + client: 'mysql', + connection: { + socketPath : '/path/to/socket.sock', + user : 'your_database_user', + password : 'your_database_password', + database : 'myapp_test' + } +}); + +// Pooling +var knex = Knex({ + client: 'mysql', + connection: { + host : '127.0.0.1', + user : 'your_database_user', + password : 'your_database_password', + database : 'myapp_test' + }, + pool: { + min: 0, + max: 7 + } +}); + +// Migrations +var knex = Knex({ + client: 'mysql', + connection: { + host : '127.0.0.1', + user : 'your_database_user', + password : 'your_database_password', + database : 'myapp_test' + }, + migrations: { + tableName: 'migrations' + } +}); + +// Knex Query Builder +knex.select('title', 'author', 'year').from('books'); +knex.select().table('books'); + +knex.avg('sum_column1').from(function() { + this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1') +}).as('ignored_alias'); + +knex.column('title', 'author', 'year').select().from('books'); +knex.column(['title', 'author', 'year']).select().from('books'); +knex.select('*').from('users'); + +knex('users').where({ + first_name: 'Test', + last_name: 'User' +}).select('id'); + +knex('users').where('id', 1); + +knex('users').where(() => { + this.where('id', 1).orWhere('id', '>', 10) +}).orWhere({name: 'Tester'}); + +knex('users').where('votes', '>', 100); + +var subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); +knex('accounts').where('id', 'in', subquery); + +knex.select('name').from('users') + .whereIn('id', [1, 2, 3]) + .orWhereIn('id', [4, 5, 6]); + +var subquery = knex.select('id').from('accounts'); +knex.select('name').from('users') + .whereIn('account_id', subquery); + +knex('users') + .where('name', '=', 'John') + .orWhere(function() { + this.where('votes', '>', 100).andWhere('title', '<>', 'Admin'); + }); + +knex('users').whereNotIn('id', [1, 2, 3]); + +knex('users').where('name', 'like', '%Test%').orWhereNotIn('id', [1, 2, 3]); + +knex('users').whereNull('updated_at'); + +knex('users').whereNotNull('created_at'); + +knex('users').whereExists(function() { + this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); +}); + +knex('users').whereExists(knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')); + +knex('users').whereNotExists(function() { + this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); +}); + +knex('users').whereBetween('votes', [1, 100]); + +knex('users').whereNotBetween('votes', [1, 100]); + +knex('users').whereRaw('id = ?', [1]); + +// Join methods +knex('users') + .join('contacts', 'users.id', '=', 'contacts.user_id') + .select('users.id', 'contacts.phone'); + +knex('users') + .join('contacts', 'users.id', 'contacts.user_id') + .select('users.id', 'contacts.phone'); + +knex.select('*').from('users').join('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin'])); + +knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); + +knex('users').innerJoin('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').leftJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.select('*').from('users').leftJoin('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').leftOuterJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.select('*').from('users').leftOuterJoin('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').rightJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.select('*').from('users').rightJoin('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').rightOuterJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.select('*').from('users').rightOuterJoin('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').outerJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.select('*').from('users').outerJoin('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').fullOuterJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.select('*').from('users').fullOuterJoin('accounts', function() { + this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') +}); + +knex.select('*').from('users').crossJoin('accounts', 'users.id', 'accounts.user_id'); + +knex.select('*').from('accounts').joinRaw('natural full join table1').where('id', 1); + +knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); + +knex('customers') + .distinct('first_name', 'last_name') + .select(); + +knex('users').groupBy('count'); + +knex.select('year', knex.raw('SUM(profit)')).from('sales').groupByRaw('year WITH ROLLUP'); + +knex('users').orderBy('name', 'desc'); + +knex.select('*').from('table').orderByRaw('col NULLS LAST DESC'); + +knex('books').insert({title: 'Slaughterhouse Five'}); + +knex('coords').insert([{x: 20}, {y: 30}, {x: 10, y: 20}]); + +knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 'id').into('books'); + +knex('books') + .returning('id') + .insert({title: 'Slaughterhouse Five'}); + +knex('books') + .returning('id') + .insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}]); + +knex('books') + .where('published_date', '<', 2000) + .update({ + status: 'archived' + }); + +knex('books').update('title', 'Slaughterhouse Five'); + +knex('accounts') + .where('activated', false) + .del(); + +var someExternalMethod: Function; + +knex.transaction(function(trx) { + knex('books').transacting(trx).insert({name: 'Old Books'}) + .then(function(resp) { + var id = resp[0]; + return someExternalMethod(id, trx); + }) + .then(trx.commit) + .catch(trx.rollback); + +}).then(function() { + console.log('Transaction complete.'); +}).catch(function(err) { + console.error(err); +}); + +knex.transaction(function(trx) { + knex('tableName') + .transacting(trx) + .forUpdate() + .select('*'); + + knex('tableName') + .transacting(trx) + .forShare() + .select('*') +}); + +knex('users').count('active'); + +knex('users').min('age'); + +knex('users').min('age as a'); + +knex('users').max('age'); + +knex('users').max('age as a'); + +knex('users').sum('products'); + +knex('users').sum('products as p'); + +knex('users').avg('age'); + +knex('users').avg('age as a'); + +knex('accounts') + .where('userid', '=', 1) + .increment('balance', 10); + +knex('accounts').where('userid', '=', 1).decrement('balance', 5); + +knex('accounts').truncate(); + +knex.table('users').pluck('id').then(function(ids) { + console.log(ids); +}); + +knex.table('users').first('id', 'name').then(function(row) { + console.log(row); +}); + +// Using trx as a query builder: +knex.transaction(function(trx) { + + var info: any; + var books: any[] = [ + {title: 'Canterbury Tales'}, + {title: 'Moby Dick'}, + {title: 'Hamlet'} + ]; + + return trx + .insert({name: 'Old Books'}, 'id') + .into('catalogues') + .then(function(ids) { + return Promise.map(books, function(book) { + book.catalogue_id = ids[0]; + // Some validation could take place here. + return trx.insert(info).into('books'); + }); + }); +}) +.then(function(inserts) { + console.log(inserts.length + ' new books saved.'); +}) +.catch(function(error) { + // If we get here, that means that neither the 'Old Books' catalogues insert, + // nor any of the books inserts will have taken place. + console.error(error); +}); + +// Using trx as a transaction object: +knex.transaction(function(trx) { + + var info: any; + var books: any[] = [ + {title: 'Canterbury Tales'}, + {title: 'Moby Dick'}, + {title: 'Hamlet'} + ]; + + knex.insert({name: 'Old Books'}, 'id') + .into('catalogues') + .transacting(trx) + .then(function(ids) { + return Promise.map(books, function(book) { + book.catalogue_id = ids[0]; + + // Some validation could take place here. + + return knex.insert(info).into('books').transacting(trx); + }); + }) + .then(trx.commit) + .catch(trx.rollback); +}) +.then(function(inserts) { + console.log(inserts.length + ' new books saved.'); +}) +.catch(function(error) { + // If we get here, that means that neither the 'Old Books' catalogues insert, + // nor any of the books inserts will have taken place. + console.error(error); +}); + +knex.schema.createTable('users', function (table) { + table.increments(); + table.string('name'); + table.timestamps(); +}); + +knex.schema.renameTable('users', 'old_users'); + +knex.schema.dropTable('users'); + +knex.schema.hasTable('users').then(function(exists) { + if (!exists) { + return knex.schema.createTable('users', function(t) { + t.increments('id').primary(); + t.string('first_name', 100); + t.string('last_name', 100); + t.text('bio'); + }); + } +}); + +var tableName: string; +var columnName: string; +knex.schema.hasColumn(tableName, columnName); + +knex.schema.dropTableIfExists('users'); + +knex.schema.table('users', function (table) { + table.dropColumn('name'); + table.string('first_name'); + table.string('last_name'); +}); + +knex.schema.raw("SET sql_mode='TRADITIONAL'") +.table('users', function (table) { + table.dropColumn('name'); + table.string('first_name'); + table.string('last_name'); +}); + +knex('users') + .select(knex.raw('count(*) as user_count, status')) + .where(knex.raw(1)) + .orWhere(knex.raw('status <> ?', [1])) + .groupBy('status'); + + knex.raw('select * from users where id = ?', [1]).then(function(resp) { + // ... + }); + +(() => { + var subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') + .wrap('(', ') avg_sal_dept'); + + knex.select('e.lastname', 'e.salary', subcolumn) + .from('employee as e') + .whereRaw('dept_no = e.dept_no'); +})(); + +(() => { + var subcolumn = knex.avg('salary') + .from('employee') + .whereRaw('dept_no = e.dept_no') + .as('avg_sal_dept'); + + knex.select('e.lastname', 'e.salary', subcolumn) + .from('employee as e') + .whereRaw('dept_no = e.dept_no'); +})(); + +var x: number; +knex.select('name').from('users') + .where('id', '>', 20) + .andWhere('id', '<', 200) + .limit(10) + .offset(x) + .then(function(rows: any) { + return _.pluck(rows, 'name'); + }) + .then(function(names: any) { + return knex.select('id').from('nicknames').whereIn('nickname', names); + }) + .then(function(rows) { + console.log(rows); + }) + .catch(function(error) { + console.error(error) + }); + +knex.select('*').from('users').where({name: 'Tim'}) + .then(function(rows) { + return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts'); + }).then(function(id) { + console.log('Inserted Account ' + id); + }).catch(function(error) { + console.error(error); + }); + +knex.insert({id: 1, name: 'Test'}, 'id').into('accounts') + .catch(function(error) { + console.error(error); + }).then(function() { + return knex.select('*').from('accounts').where('id', 1); + }).then(function(rows) { + console.log(rows[0]); + }).catch(function(error) { + console.error(error); + }); + +var query: any; +query.then(function(x: any) { + // doSideEffectsHere(x); + return x; +}); + +knex.select('name').from('users').limit(10).map(function(row: any) { + return row.name; +}).then(function(names) { + console.log(names); +}).catch(function(e) { + console.error(e); +}); + +knex.select('name').from('users').limit(10).reduce(function(memo: any, row: any) { + memo.names.push(row.name); + memo.count++; + return memo; +}, {count: 0, names: []}).then(function(obj) { + console.log(obj); +}).catch(function(e) { + console.error(e); +}); + +knex.select('name').from('users') + .limit(10) + .bind(console) + .then(console.log) + .catch(console.error); + +var values: any[]; +// Without return: +knex.insert(values).into('users') + .then(function() { + return {inserted: true}; + }); + +knex.insert(values).into('users').return({inserted: true}); + +knex.select('name').from('users') + .where('id', '>', 20) + .andWhere('id', '<', 200) + .limit(10) + .offset(x) + .exec(function(err: any, rows: any[]) { + if (err) return console.error(err); + knex.select('id').from('nicknames').whereIn('nickname', _.pluck(rows, 'name')) + .exec(function(err: any, rows: any[]) { + if (err) return console.error(err); + console.log(rows); + }); + }); + +// Retrieve the stream: +var stream = knex.select('*').from('users').stream(); +var writableStream: any; +stream.pipe(writableStream); + +// With options: +var stream = knex.select('*').from('users').stream({highWaterMark: 5}); +stream.pipe(writableStream); + +// Use as a promise: +(() => { + +var stream = knex.select('*').from('users').where(knex.raw('id = ?', [1])).stream(function(stream: any) { + stream.pipe(writableStream); +}).then(function() { + // ... +}).catch(function(e: Error) { + console.error(e); +}); + +})(); + +var stream = knex.select('*').from('users').pipe(writableStream); +var app: any; + +knex.select('*') + .from('users') + .on('query', function(data: any) { + app.log(data); + }) + .then(function() { + // ... + }); + + knex.select('*').from('users').where(knex.raw('id = ?', [1])).toString(); + + knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); + +// +// Migrations +// +var config = { }; +knex.migrate.make(name, config); +knex.migrate.make(name); + +knex.migrate.latest(config); +knex.migrate.latest(); + +knex.migrate.rollback(config); +knex.migrate.rollback(); + +knex.migrate.currentversion(config); +knex.migrate.currentversion(); + +knex.seed.make(name, config); +knex.seed.make(name); + +knex.seed.run(config); +knex.seed.run(); diff --git a/knex/knex.d.ts b/knex/knex.d.ts new file mode 100644 index 0000000000..c9a6ada4bc --- /dev/null +++ b/knex/knex.d.ts @@ -0,0 +1,457 @@ +// Type definitions for Knex.js +// Project: https://github.com/tgriesser/knex +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "knex" { + import Promise = require("bluebird"); + import events = require("events"); + + type Callback = Function; + type Client = Function; + type Value = string|number|boolean|Date; + type ColumnName = string|Raw|QueryBuilder; + + module KnexStatic { + interface ConfigStatic { } + } + + interface KnexStatic { + (config: Config): Knex; + } + + interface Knex extends QueryInterface { } + + interface Knex { + (tableName?: string): QueryBuilder; + VERSION: string; + __knex__: string; + + raw: RawBuilder; + transaction: (transactionScope: ((trx: Transaction) => void)) => Promise; + destroy(callback: Function): void; + destroy(): Promise; + + client: any; + migrate: any; + seed: any; + fn: any; + } + + // + // QueryInterface + // + + interface QueryInterface { + select: Select; + as: As; + columns: Select; + column: Select; + from: Table; + into: Table; + table: Table; + distinct: Distinct; + + // Joins + join: Join; + joinRaw: JoinRaw; + innerJoin: Join; + leftJoin: Join; + leftOuterJoin: Join; + rightJoin: Join; + rightOuterJoin: Join; + outerJoin: Join; + fullOuterJoin: Join; + crossJoin: Join; + + // Wheres + where: Where; + andWhere: Where; + orWhere: Where; + whereRaw: WhereRaw; + whereWrapped: WhereWrapped; + havingWrapped: WhereWrapped; + orWhereRaw: WhereRaw; + whereExists: WhereExists; + orWhereExists: WhereExists; + whereNotExists: WhereExists; + orWhereNotExists: WhereExists; + whereIn: WhereIn; + orWhereIn: WhereIn; + whereNotIn: WhereIn; + orWhereNotIn: WhereIn; + whereNull: WhereNull; + orWhereNull: WhereNull; + whereNotNull: WhereNull; + orWhereNotNull: WhereNull; + whereBetween: WhereBetween; + whereNotBetween: WhereBetween; + orWhereBetween: WhereBetween; + orWhereNotBetween: WhereBetween; + + // Group by + groupBy: GroupBy; + groupByRaw: RawQueryBuilder; + + // Order by + orderBy: OrderBy; + orderByRaw: RawQueryBuilder; + + // Union + union: Union; + unionAll(callback: Function): QueryBuilder; + + // Having + having: Having; + havingRaw: RawQueryBuilder; + orHaving: Having; + orHavingRaw: RawQueryBuilder; + + // Paging + offset(offset: number): QueryBuilder; + limit(limit: number): QueryBuilder; + + // Aggregation + count(columnName?: string): QueryBuilder; + min(columnName: string): QueryBuilder; + max(columnName: string): QueryBuilder; + sum(columnName: string): QueryBuilder; + avg(columnName: string): QueryBuilder; + increment(columnName: string, amount?: number): QueryBuilder; + decrement(columnName: string, amount?: number): QueryBuilder; + + // Others + first(...columns: string[]): QueryBuilder; + + debug(enabled?: boolean): QueryBuilder; + pluck(column: string): QueryBuilder; + + insert(data: any, returning?: string): QueryBuilder; + update(data: any, returning?: string): QueryBuilder; + update(columnName: string, value: Value, returning?: string): QueryBuilder; + returning(column: string): QueryBuilder; + + del(returning?: string): QueryBuilder; + delete(returning?: string): QueryBuilder; + truncate(): QueryBuilder; + + transacting(trx: Transaction): QueryBuilder; + connection(connection: any): QueryBuilder; + } + + interface As { + (columnName: string): QueryBuilder; + } + + interface Select extends ColumnNameQueryBuilder { + } + + interface Table { + (tableName: string): QueryBuilder; + (callback: Function): QueryBuilder; + } + + interface Distinct extends ColumnNameQueryBuilder { + } + + interface Join { + (raw: Raw): QueryBuilder; + (tableName: string, callback: Function): QueryBuilder; + (tableName: string, column1: string, column2: string): QueryBuilder; + (tableName: string, column1: string, raw: Raw): QueryBuilder; + (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; + } + + interface JoinRaw { + (tableName: string, binding?: Value): QueryBuilder; + } + + interface Where extends WhereRaw, WhereWrapped, WhereNull { + (object: Object): QueryBuilder; + (columnName: string, value: Value): QueryBuilder; + (columnName: string, operator: string, value: Value): QueryBuilder; + (columnName: string, operator: string, query: QueryBuilder): QueryBuilder; + } + + interface WhereRaw extends RawQueryBuilder { + (condition: boolean): QueryBuilder; + } + + interface WhereWrapped { + (callback: Function): QueryBuilder; + } + + interface WhereNull { + (columnName: string): QueryBuilder; + } + + interface WhereIn { + (columnName: string, values: Value[]): QueryBuilder; + (columnName: string, callback: Function): QueryBuilder; + (columnName: string, query: QueryBuilder): QueryBuilder; + } + + interface WhereBetween { + (columnName: string, range: [Value, Value]): QueryBuilder; + } + + interface WhereExists { + (callback: Function): QueryBuilder; + (query: QueryBuilder): QueryBuilder; + } + + interface WhereNull { + (columnName: string): QueryBuilder; + } + + interface WhereIn { + (columnName: string, values: Value[]): QueryBuilder; + } + + interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { + } + + interface OrderBy { + (columnName: string, direction?: string): QueryBuilder; + } + + interface Union { + (callback: Function, wrap?: boolean): QueryBuilder; + (callbacks: Function[], wrap?: boolean): QueryBuilder; + (...callbacks: Function[]): QueryBuilder; + // (...callbacks: Function[], wrap?: boolean): QueryInterface; + } + + interface Having extends RawQueryBuilder, WhereWrapped { + (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; + } + + // commons + + interface ColumnNameQueryBuilder { + (...columnNames: ColumnName[]): QueryBuilder; + (columnNames: ColumnName[]): QueryBuilder; + } + + interface RawQueryBuilder { + (sql: string, ...bindings: Value[]): QueryBuilder; + (sql: string, bindings: Value[]): QueryBuilder; + (raw: Raw): QueryBuilder; + } + + // Raw + + interface Raw extends events.EventEmitter, ChainableInterface { + wrap(before: string, after: string): Raw; + } + + interface RawBuilder { + (value: Value): Raw; + (sql: string, ...bindings: Value[]): Raw; + (sql: string, bindings: Value[]): Raw; + } + + // + // QueryBuilder + // + + interface QueryBuilder extends QueryInterface, ChainableInterface { + or: QueryBuilder; + and: QueryBuilder; + + //TODO: Promise? + columnInfo(column?: string): Promise; + + forUpdate(): QueryBuilder; + forShare(): QueryBuilder; + + toSQL(): Sql; + + on(event: string, callback: Function): QueryBuilder; + } + + interface Sql { + method: string; + options: any; + bindings: Value[]; + sql: string; + } + + // + // Chainable interface + // + + interface ChainableInterface extends Promise { + toQuery(): string; + options(options: any): QueryBuilder; + stream(options?: any, callback?: (builder: QueryBuilder) => any): QueryBuilder; + stream(callback?: (builder: QueryBuilder) => any): QueryBuilder; + pipe(writable: any): QueryBuilder; + exec(callback: Function): QueryBuilder; + } + + interface Transaction extends QueryBuilder { + commit: any; + rollback: any; + } + + // + // Schema builder + // + + interface Knex { + schema: SchemaBuilder; + } + + interface SchemaBuilder { + createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): Promise; + renameTable(oldTableName: string, newTableName: string): Promise; + dropTable(tableName: string): Promise; + hasTable(tableName: string): Promise; + hasColumn(tableName: string, columnName: string): Promise; + table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; + dropTableIfExists(tableName: string): Promise; + raw(statement: string): SchemaBuilder; + } + + interface TableBuilder { + increments(columnName?: string): ColumnBuilder; + dropColumn(columnName: string): TableBuilder; + dropColumns(...columnNames: string[]): TableBuilder; + renameColumn(from: string, to: string): ColumnBuilder; + integer(columnName: string): ColumnBuilder; + bigInteger(columnName: string): ColumnBuilder; + text(columnName: string, textType?: string): ColumnBuilder; + string(columnName: string, length?: number): ColumnBuilder; + float(columnName: string, precision?: number, scale?: number): ColumnBuilder; + decimal(columnName: string, precision?: number, scale?: number): ColumnBuilder; + boolean(columnName: string): ColumnBuilder; + date(columnName: string): ColumnBuilder; + dateTime(columnName: string): ColumnBuilder; + time(columnName: string): ColumnBuilder; + timestamp(columnName: string): ColumnBuilder; + timestamps(): ColumnBuilder; + binary(columnName: string): ColumnBuilder; + enum(columnName: string): ColumnBuilder; + enu(columnName: string): ColumnBuilder; + json(columnName: string): ColumnBuilder; + uuid(columnName: string): ColumnBuilder; + comment(val: string): TableBuilder; + specificType(columnName: string, type: string): ColumnBuilder; + } + + interface CreateTableBuilder extends TableBuilder { + } + + interface MySqlTableBuilder extends CreateTableBuilder { + engine(val: string): CreateTableBuilder; + charset(val: string): CreateTableBuilder; + collate(val: string): CreateTableBuilder; + } + + interface AlterTableBuilder extends TableBuilder { + } + + interface MySqlAlterTableBuilder extends AlterTableBuilder { + } + + interface ColumnBuilder { + index(indexName?: string): ColumnBuilder; + primary(): ColumnBuilder; + unique(): ColumnBuilder; + references(columnName: string): ReferencingColumnBuilder; + onDelete(command: string): ColumnBuilder; + onUpdate(command: string): ColumnBuilder; + defaultTo(value: Value): ColumnBuilder; + unsigned(): ColumnBuilder; + notNullable(): ColumnBuilder; + nullable(): ColumnBuilder; + comment(value: string): ColumnBuilder; + } + + interface PostgreSqlColumnBuilder extends ColumnBuilder { + index(indexName?: string, indexType?: string): ColumnBuilder; + } + + interface ReferencingColumnBuilder { + inTable(tableName: string): ColumnBuilder; + } + + interface AlterColumnBuilder extends ColumnBuilder { + } + + interface MySqlAlterColumnBuilder extends AlterColumnBuilder { + first(): AlterColumnBuilder; + after(columnName: string): AlterColumnBuilder; + } + + // + // Configurations + // + + interface ColumnInfo { + defaultValue: Value; + type: string; + maxLength: number; + nullable: boolean; + } + + interface Config { + client?: string; + dialect?: string; + connection: string|ConnectionConfig| + Sqlite3ConnectionConfig|SocketConnectionConfig; + pool?: PoolConfig; + migrations?: MigrationConfig; + } + + interface ConnectionConfig { + host: string; + user: string; + password: string; + database: string; + debug?: boolean; + } + + /** Used with SQLite3 adapter */ + interface Sqlite3ConnectionConfig { + filename: string; + debug?: boolean; + } + + interface SocketConnectionConfig { + socketPath: string; + user: string; + password: string; + database: string; + debug?: boolean; + } + + interface PoolConfig { + name?: string; + create?: Function; + destroy?: Function; + min?: number; + max?: number; + refreshIdle?: boolean; + idleTimeoutMillis?: number; + reapIntervalMillis?: number; + returnToHead?: boolean; + priorityRange?: number; + validate?: Function; + log?: boolean; + } + + interface MigrationConfig { + database?: string; + directory?: string; + extension?: string; + tableName?: string; + } + + var _: KnexStatic; + export = _; +} diff --git a/knockout.projections/knockout.projections-tests.ts b/knockout.projections/knockout.projections-tests.ts index 3d479e7ac3..138d369465 100644 --- a/knockout.projections/knockout.projections-tests.ts +++ b/knockout.projections/knockout.projections-tests.ts @@ -26,3 +26,39 @@ sourceItems.push(9); sourceItems.push(10); // evenSquares now contains [36, 16, 4, 100] + +// Testing mapping options + +interface IComplexItem { + value: string; + dispose(): void; +} + +var complexItems = sourceItems.map({ + mapping: x => { + var item: IComplexItem = { + value: (x * x).toString(), + dispose: () => { } + }; + + return item; + }, + disposeItem: (item: IComplexItem) => item.dispose() +}); + +var complexItems2 = sourceItems.map({ + mappingWithDisposeCallback: x => { + return { + mappedValue: (x * x).toString(), + dispose: () => { } + }; + } +}); + +// Test disposal + +evenSquares.dispose(); + +complexItems.dispose(); + +complexItems2.dispose(); diff --git a/knockout.projections/knockout.projections.d.ts b/knockout.projections/knockout.projections.d.ts index 77f3bf0ec8..e1443478ab 100644 --- a/knockout.projections/knockout.projections.d.ts +++ b/knockout.projections/knockout.projections.d.ts @@ -5,8 +5,21 @@ /// -interface KnockoutObservableArrayFunctions { - - map(mapping: (value: T) => TResult): KnockoutObservableArray; - filter(predicate: (value: T) => boolean): KnockoutObservableArray; +interface KnockoutMappedObservableArray extends KnockoutObservableArray, KnockoutSubscription { +} + +interface KnockoutObservableArrayFunctions { + map(mappingOptions: { + mappingWithDisposeCallback: (value: T) => { + mappedValue: TResult; + dispose: () => void; + }; + }): KnockoutMappedObservableArray; + map(mappingOptions: { + mapping: (value: T) => TResult; + disposeItem?: (mappedItem: TResult) => void; + }): KnockoutMappedObservableArray; + map(mappingOptions: (value: T) => TResult): KnockoutMappedObservableArray; + + filter(predicate: (value: T) => boolean): KnockoutMappedObservableArray; } diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index c20207199d..a906348a67 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -574,7 +574,7 @@ interface KnockoutComputedContext { declare module KnockoutComponentTypes { interface Config { - viewModel: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; + viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; template: string | Node[]| DocumentFragment | TemplateElement | AMDModule; } diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index ed6b2dbcf0..a1e92ef713 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -3,7 +3,7 @@ // Definitions by: Vladimir Zotov // Definitions: https://github.com/borisyankov/DefinitelyTyped - + declare module L { export interface AttributionOptions { @@ -13,16 +13,16 @@ declare module L { * Default value: 'bottomright'. */ position?: string; - + /** * The HTML text shown before the attributions. Pass false to disable. * Default value: 'Powered by Leaflet'. */ prefix?: string; - + } } - + declare module L { /** @@ -56,49 +56,49 @@ declare module L { * Extends the bounds to contain the given point. */ extend(point: Point): void; - + /** * Returns the center point of the bounds. */ getCenter(): Point; - + /** * Returns true if the rectangle contains the given one. */ contains(otherBounds: Bounds): boolean; - + /** * Returns true if the rectangle contains the given point. */ contains(point: Point): boolean; - + /** * Returns true if the rectangle intersects the given bounds. */ intersects(otherBounds: Bounds): boolean; - + /** * Returns true if the bounds are properly initialized. */ isValid(): boolean; - + /** * Returns the size of the given bounds. */ getSize(): Point; - + /** * The top left corner of the rectangle. */ min: Point; - + /** * The bottom right corner of the rectangle. */ max: Point; } } - + declare module L { module Browser { @@ -107,73 +107,73 @@ declare module L { * true for all Internet Explorer versions. */ export var ie: boolean; - + /** * true for Internet Explorer 6. */ export var ie6: boolean; - + /** * true for Internet Explorer 6. */ export var ie7: boolean; - + /** * true for webkit-based browsers like Chrome and Safari (including mobile * versions). */ export var webkit: boolean; - + /** * true for webkit-based browsers that support CSS 3D transformations. */ export var webkit3d: boolean; - + /** * true for Android mobile browser. */ export var android: boolean; - + /** * true for old Android stock browsers (2 and 3). */ export var android23: boolean; - + /** * true for modern mobile browsers (including iOS Safari and different Android * browsers). */ export var mobile: boolean; - + /** * true for mobile webkit-based browsers. */ export var mobileWebkit: boolean; - + /** * true for mobile Opera. */ export var mobileOpera: boolean; - + /** * true for all browsers on touch devices. */ export var touch: boolean; - + /** * true for browsers with Microsoft touch model (e.g. IE10). */ export var msTouch: boolean; - + /** * true for devices with Retina screens. */ export var retina: boolean; - + } } - - + + declare module L { /** @@ -196,17 +196,17 @@ declare module L { * Returns the current geographical position of the circle. */ getLatLng(): LatLng; - + /** * Returns the current radius of a circle. Units are in meters. */ getRadius(): number; - + /** * Sets the position of a circle to a new location. */ setLatLng(latlng: LatLng): Circle; - + /** * Sets the radius of a circle. Units are in meters. */ @@ -219,7 +219,7 @@ declare module L { } } - + declare module L { /** @@ -245,7 +245,7 @@ declare module L { * Sets the position of a circle marker to a new location. */ setLatLng(latlng: LatLng): CircleMarker; - + /** * Sets the radius of a circle marker. Units are in pixels. */ @@ -261,24 +261,24 @@ declare module L { declare module L { export interface ClassExtendOptions { /** - * options is a special property that unlike other objects that you pass - * to extend will be merged with the parent one instead of overriding it - * completely, which makes managing configuration of objects and default + * options is a special property that unlike other objects that you pass + * to extend will be merged with the parent one instead of overriding it + * completely, which makes managing configuration of objects and default * values convenient. */ options?: any; /** - * includes is a special class property that merges all specified objects + * includes is a special class property that merges all specified objects * into the class (such objects are called mixins). A good example of this - * is L.Mixin.Events that event-related methods like on, off and fire + * is L.Mixin.Events that event-related methods like on, off and fire * to the class. */ includes?: any; /** - * statics is just a convenience property that injects specified object - * properties as the static properties of the class, useful for defining + * statics is just a convenience property that injects specified object + * properties as the static properties of the class, useful for defining * constants. */ static?: any; @@ -491,7 +491,7 @@ declare module L { export function scale(options?: ScaleOptions): L.Control.Scale; } } - + declare module L { export interface ControlOptions { @@ -505,7 +505,7 @@ declare module L { } } - + declare module L { module CRS { @@ -516,28 +516,28 @@ declare module L { * Map's crs option. */ export var EPSG3857: ICRS; - + /** * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. */ export var EPSG4326: ICRS; - + /** * Rarely used by some commercial tile providers. Uses Elliptical Mercator * projection. */ export var EPSG3395: ICRS; - + /** * A simple CRS that maps longitude and latitude into x and y directly. May be * used for maps of flat surfaces (e.g. game maps). Note that the y axis should * still be inverted (going from bottom to top). */ export var Simple: ICRS; - + } } - + declare module L { /** @@ -556,7 +556,7 @@ declare module L { export interface DivIcon extends Icon { } } - + declare module L { export interface DivIconOptions { @@ -565,7 +565,7 @@ declare module L { * Size of the icon in pixels. Can be also set through CSS. */ iconSize?: Point; - + /** * The coordinates of the "tip" of the icon (relative to its top left corner). * The icon will be aligned so that this point is at the marker's geographical @@ -573,24 +573,24 @@ declare module L { * with negative margins. */ iconAnchor?: Point; - + /** * A custom class name to assign to the icon. * * Default value: 'leaflet-div-icon'. */ className?: string; - + /** * A custom HTML code to put inside the div element. * * Default value: ''. */ html?: string; - + } } - + declare module L { export interface DomEvent { @@ -601,13 +601,13 @@ declare module L { */ addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - + /** * Removes an event listener from the element. */ removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - + /** * Stop the given event from propagation to parent elements. Used inside the * listener functions: @@ -617,41 +617,41 @@ declare module L { * }); */ stopPropagation(e: Event): DomEvent; - + /** * Prevents the default action of the event from happening (such as following * a link in the href of the a element, or doing a POST request with page reload * when form is submitted). Use it inside listener functions. */ preventDefault(e: Event): DomEvent; - + /** * Does stopPropagation and preventDefault at the same time. */ stop(e: Event): DomEvent; - + /** * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' * and 'touchstart' events. */ disableClickPropagation(el: HTMLElement): DomEvent; - + /** * Gets normalized mouse position from a DOM event relative to the container * or to the whole page if not specified. */ getMousePosition(e: Event, container?: HTMLElement): Point; - + /** * Gets normalized wheel delta from a mousewheel DOM event. */ getWheelDelta(e: Event): number; - + } export var DomEvent: DomEvent; } - + declare module L { module DomUtil { @@ -661,74 +661,74 @@ declare module L { * the element if it was passed directly. */ export function get(id: string): HTMLElement; - + /** * Returns the value for a certain style attribute on an element, including * computed values or values set through CSS. */ export function getStyle(el: HTMLElement, style: string): string; - + /** * Returns the offset to the viewport for the requested element. */ export function getViewportOffset(el: HTMLElement): Point; - + /** * Creates an element with tagName, sets the className, and optionally appends * it to container element. */ export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; - + /** * Makes sure text cannot be selected, for example during dragging. */ export function disableTextSelection(): void; - + /** * Makes text selection possible again. */ export function enableTextSelection(): void; - + /** * Returns true if the element class attribute contains name. */ export function hasClass(el: HTMLElement, name: string): boolean; - + /** * Adds name to the element's class attribute. */ export function addClass(el: HTMLElement, name: string): void; - + /** * Removes name from the element's class attribute. */ export function removeClass(el: HTMLElement, name: string): void; - + /** * Set the opacity of an element (including old IE support). Value must be from * 0 to 1. */ export function setOpacity(el: HTMLElement, value: number): void; - + /** * Goes through the array of style names and returns the first name that is a valid * style name for an element. If no such name is found, it returns false. Useful * for vendor-prefixed styles like transform. */ export function testProp(props: string[]): any; - + /** * Returns a CSS transform string to move an element by the offset provided in * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms * and 2D on other browsers. */ export function getTranslateString(point: Point): string; - + /** * Returns a CSS transform string to scale an element (with the given scale origin). */ export function getScaleString(scale: number, origin: Point): string; - + /** * Sets the position of an element to coordinates specified by point, using * CSS translate or top/left positioning depending on the browser (used by @@ -736,25 +736,25 @@ declare module L { * if disable3D is true. */ export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; - + /** * Returns the coordinates of an element previously positioned with setPosition. */ export function getPosition(el: HTMLElement): Point; - + /** * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). */ export var TRANSITION: string; - + /** * Vendor-prefixed transform style name. */ export var TRANSFORM: string; - + } } - + declare module L { /** @@ -778,12 +778,12 @@ declare module L { * Enables the dragging ability. */ enable(): void; - + /** * Disables the dragging ability. */ disable(): void; - + //////////////// //////////////// addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; @@ -801,10 +801,10 @@ declare module L { on(eventMap: any, context?: any): Draggable; off(eventMap?: any, context?: any): Draggable; } -} - - - +} + + + declare module L { /** @@ -827,23 +827,23 @@ declare module L { * group that has a bindPopup method. */ bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; - + /** * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates * of its children). */ getBounds(): LatLngBounds; - + /** * Sets the given path options to each layer of the group that has a setStyle method. */ setStyle(style: PathOptions): FeatureGroup; - + /** * Brings the layer group to the top of all other layers. */ bringToFront(): FeatureGroup; - + /** * Brings the layer group to the bottom of all other layers. */ @@ -857,13 +857,13 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; - + //////////////// //////////////// addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; @@ -882,7 +882,7 @@ declare module L { off(eventMap?: any, context?: any): FeatureGroup; } } - + declare module L { export interface FitBoundsOptions extends ZoomPanOptions { @@ -899,14 +899,14 @@ declare module L { /** * The same for bottom right corner of the map. - * + * * Default value: [0, 0]. */ paddingBottomRight?: Point; /** * Equivalent of setting both top left and bottom right padding to the same value. - * + * * Default value: [0, 0]. */ padding?: Point; @@ -919,7 +919,7 @@ declare module L { maxZoom?: number; } } - + declare module L { /** @@ -947,7 +947,7 @@ declare module L { * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted * as (longitude, latitude). */ - coordsToLatlng(coords: number[], reverse?: boolean): LatLng; + coordsToLatLng(coords: number[], reverse?: boolean): LatLng; /** * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates @@ -955,26 +955,26 @@ declare module L { * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to * true, the numbers will be interpreted as (longitude, latitude). */ - coordsToLatlngs(coords: number[], levelsDeep?: number, reverse?: boolean): LatLng[]; + coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; } export var GeoJSON: GeoJSONStatic; export interface GeoJSON extends FeatureGroup { /** - * Adds a GeoJSON object to the layer. + * Adds a GeoJSON object to the layer. */ addData(data: any): boolean; - + /** * Changes styles of GeoJSON vector layers with the given style function. */ setStyle(style: (featureData: any) => any): GeoJSON; - + /** * Changes styles of GeoJSON vector layers with the given style options. */ setStyle(style: PathOptions): GeoJSON; - + /** * Resets the the given vector layer's style to the original GeoJSON style, * useful for resetting style after hover events. @@ -1017,9 +1017,9 @@ declare module L { } } - - - + + + declare module L { /** @@ -1056,7 +1056,7 @@ declare module L { } } } - + declare module L { export interface IconOptions { @@ -1066,18 +1066,18 @@ declare module L { * path). */ iconUrl?: string; - + /** * The URL to a retina sized version of the icon image (absolute or relative to * your script path). Used for Retina screen devices. */ iconRetinaUrl?: string; - + /** * Size of the icon image in pixels. */ iconSize?: Point; - + /** * The coordinates of the "tip" of the icon (relative to its top left corner). * The icon will be aligned so that this point is at the marker's geographical @@ -1085,43 +1085,43 @@ declare module L { * with negative margins. */ iconAnchor?: Point; - + /** * The URL to the icon shadow image. If not specified, no shadow image will be * created. */ shadowUrl?: string; - + /** * The URL to the retina sized version of the icon shadow image. If not specified, * no shadow image will be created. Used for Retina screen devices. */ shadowRetinaUrl?: string; - + /** * Size of the shadow image in pixels. */ shadowSize?: Point; - + /** * The coordinates of the "tip" of the shadow (relative to its top left corner) * (the same as iconAnchor if not specified). */ shadowAnchor?: Point; - + /** * The coordinates of the point from which popups will "open", relative to the * icon anchor. */ popupAnchor?: Point; - + /** * A custom class name to assign to both icon and shadow images. Empty by default. */ className?: string; } } - + declare module L { export interface IControl { @@ -1132,7 +1132,7 @@ declare module L { * containing the control. Called on map.addControl(control) or control.addTo(map). */ onAdd(map: Map): HTMLElement; - + /** * Optional, should contain all clean up code (e.g. removes control's event * listeners). Called on map.removeControl(control) or control.removeFrom(map). @@ -1141,7 +1141,7 @@ declare module L { onRemove(map: Map): void; } } - + declare module L { export interface ICRS { @@ -1150,35 +1150,35 @@ declare module L { * Projection that this CRS uses. */ projection: IProjection; - + /** * Transformation that this CRS uses to turn projected coordinates into screen * coordinates for a particular tile service. */ transformation: Transformation; - + /** * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). */ code: string; - + /** * Projects geographical coordinates on a given zoom into pixel coordinates. */ latLngToPoint(latlng: LatLng, zoom: number): Point; - + /** * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom * into geographical coordinates. */ pointToLatLng(point: Point, zoom: number): LatLng; - + /** * Projects geographical coordinates into coordinates in units accepted * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). */ project(latlng: LatLng): Point; - + /** * Returns the scale used when transforming projected coordinates into pixel * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for @@ -1190,10 +1190,10 @@ declare module L { * Returns the size of the world in pixels for a particular zoom. */ getSize(zoom: number): Point; - + } } - + declare module L { export interface IEventPowered { @@ -1205,7 +1205,7 @@ declare module L { * dblclick'). */ addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - + /** * The same as above except the listener will only get fired once and then removed. */ @@ -1214,29 +1214,29 @@ declare module L { * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} */ addEventListener(eventMap: any, context?: any): T; - + /** * Removes a previously added listener function. If no function is specified, * it will remove all the listeners of that particular event from the object. */ removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - + /** * Removes a set of type/listener pairs. */ removeEventListener(eventMap?: any, context?: any): T; - + /** * Returns true if a particular event type has some listeners attached to it. */ hasEventListeners(type: string): boolean; - + /** * Fires an event of the specified type. You can optionally provide an data object * — the first argument of the listener function will contain its properties. */ fireEvent(type: string, data?: any): T; - + /** * Removes all listeners to all events on the object. */ @@ -1266,14 +1266,14 @@ declare module L { * Alias to removeEventListener. */ off(eventMap?: any, context?: any): T; - + /** * Alias to fireEvent. */ fire(type: string, data?: any): T; } } - + declare module L { export interface IHandler { @@ -1282,12 +1282,12 @@ declare module L { * Enables the handler. */ enable(): void; - + /** * Disables the handler. */ disable(): void; - + /** * Returns true if the handler is enabled. */ @@ -1298,7 +1298,7 @@ declare module L { initialize(map: Map): void; } } - + declare module L { export interface ILayer { @@ -1309,7 +1309,7 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). @@ -1326,7 +1326,7 @@ declare module L { export var Events: LeafletMixinEvents; } } - + declare module L { /** @@ -1349,7 +1349,7 @@ declare module L { * Adds the overlay to the map. */ addTo(map: Map): ImageOverlay; - + /** * Sets the opacity of the overlay. */ @@ -1358,13 +1358,13 @@ declare module L { /** * Changes the URL of the image. */ - setUrl(imageUrl: string): ImageOverlay; - + setUrl(imageUrl: string): ImageOverlay; + /** * Brings the layer to the top of all overlays. */ bringToFront(): ImageOverlay; - + /** * Brings the layer to the bottom of all overlays. */ @@ -1378,7 +1378,7 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). @@ -1386,7 +1386,7 @@ declare module L { onRemove(map: Map): void; } } - + declare module L { export interface ImageOverlayOptions { @@ -1397,7 +1397,7 @@ declare module L { opacity?: number; } } - + declare module L { export interface IProjection { @@ -1406,14 +1406,14 @@ declare module L { * Projects geographical coordinates into a 2D point. */ project(latlng: LatLng): Point; - + /** * The inverse of project. Projects a 2D point into geographical location. */ unproject(point: Point): LatLng; } } - + declare module L { /** @@ -1427,7 +1427,7 @@ declare module L { */ export function noConflict(): typeof L; } - + declare module L { /** * Creates an object representing a geographical point with the given latitude @@ -1483,29 +1483,29 @@ declare module L { * Haversine formula. See description on wikipedia */ distanceTo(otherLatlng: LatLng): number; - + /** * Returns true if the given LatLng point is at the same position (within a small * margin of error). */ equals(otherLatlng: LatLng): boolean; - + /** * Returns a string representation of the point (for debugging purposes). */ toString(): string; - + /** * Returns a new LatLng object with the longitude wrapped around left and right * boundaries (-180 to 180 by default). */ wrap(left: number, right: number): LatLng; - + /** * Latitude in degrees. */ lat: number; - + /** * Longitude in degrees. */ @@ -1547,7 +1547,7 @@ declare module L { * Extends the bounds to contain the given point. */ extend(latlng: LatLng): LatLngBounds; - + /** * Extends the bounds to contain the given bounds. */ @@ -1557,68 +1557,88 @@ declare module L { * Returns the south-west point of the bounds. */ getSouthWest(): LatLng; - + /** * Returns the north-east point of the bounds. */ getNorthEast(): LatLng; - + /** * Returns the north-west point of the bounds. */ getNorthWest(): LatLng; - + /** * Returns the south-east point of the bounds. */ getSouthEast(): LatLng; - + + /** + * Returns the west longitude in degrees of the bounds. + */ + getWest(): number; + + /** + * Returns the east longitude in degrees of the bounds. + */ + getEast(): number; + + /** + * Returns the north latitude in degrees of the bounds. + */ + getNorth(): number; + + /** + * Returns the south latitude in degrees of the bounds. + */ + getSouth(): number; + /** * Returns the center point of the bounds. */ getCenter(): LatLng; - + /** * Returns true if the rectangle contains the given one. */ contains(otherBounds: LatLngBounds): boolean; - + /** * Returns true if the rectangle contains the given point. */ contains(latlng: LatLng): boolean; - + /** * Returns true if the rectangle intersects the given bounds. */ intersects(otherBounds: LatLngBounds): boolean; - + /** * Returns true if the rectangle is equivalent (within a small margin of error) * to the given bounds. */ equals(otherBounds: LatLngBounds): boolean; - + /** * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' * format. Useful for sending requests to web services that return geo data. */ toBBoxString(): string; - + /** * Returns bigger bounds created by extending the current bounds by a given * percentage in each direction. */ pad(bufferRatio: number): LatLngBounds; - + /** * Returns true if the bounds are properly initialized. */ isValid(): boolean; - + } } - + declare module L { /** @@ -1640,17 +1660,17 @@ declare module L { * Adds the group of layers to the map. */ addTo(map: Map): LayerGroup; - + /** * Adds a given layer to the group. */ addLayer(layer: T): LayerGroup; - + /** * Removes a given layer from the group. */ removeLayer(layer: T): LayerGroup; - + /** * Removes a given layer of the given id from the group. */ @@ -1675,7 +1695,7 @@ declare module L { * Removes all the layers from the group. */ clearLayers(): LayerGroup; - + /** * Iterates over the layers of the group, optionally specifying context of * the iterator function. @@ -1695,7 +1715,7 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). @@ -1703,8 +1723,8 @@ declare module L { onRemove(map: Map): void; } } - - + + declare module L { export interface LayersOptions { @@ -1715,7 +1735,7 @@ declare module L { * Default value: 'topright'. */ position?: string; - + /** * If true, the control will be collapsed into an icon and expanded on mouse hover * or touch. @@ -1723,7 +1743,7 @@ declare module L { * Default value: true. */ collapsed?: boolean; - + /** * If true, the control will assign zIndexes in increasing order to all of its * layers so that the order is preserved when switching them on/off. @@ -1731,10 +1751,10 @@ declare module L { * Default value: true. */ autoZIndex?: boolean; - + } } - + declare module L { export interface LeafletErrorEvent extends LeafletEvent { @@ -1743,14 +1763,14 @@ declare module L { * Error message. */ message: string; - + /** * Error code (if applicable). */ code: number; } } - + declare module L { export interface LeafletEvent { @@ -1766,7 +1786,7 @@ declare module L { target: any; } } - + declare module L { export interface LeafletGeoJSONEvent extends LeafletEvent { @@ -1775,24 +1795,24 @@ declare module L { * The layer for the GeoJSON feature that is being added to the map. */ layer: ILayer; - + /** * GeoJSON properties of the feature. */ properties: any; - + /** * GeoJSON geometry type of the feature. */ geometryType: string; - + /** * GeoJSON ID of the feature (if present). */ id: string; } } - + declare module L { export interface LeafletLayerEvent extends LeafletEvent { @@ -1803,7 +1823,7 @@ declare module L { layer: ILayer; } } - + declare module L { export interface LeafletLocationEvent extends LeafletEvent { @@ -1812,13 +1832,13 @@ declare module L { * Detected geographical location of the user. */ latlng: LatLng; - + /** * Geographical bounds of the area user is located in (with respect to the accuracy * of location). */ bounds: LatLngBounds; - + /** * Accuracy of location in meters. */ @@ -1848,10 +1868,10 @@ declare module L { * The time when the position was acquired. */ timestamp: number; - + } } - + declare module L { export interface LeafletMouseEvent extends LeafletEvent { @@ -1860,26 +1880,26 @@ declare module L { * The geographical point where the mouse event occured. */ latlng: LatLng; - + /** * Pixel coordinates of the point where the mouse event occured relative to * the map layer. */ layerPoint: Point; - + /** * Pixel coordinates of the point where the mouse event occured relative to * the map сontainer. */ containerPoint: Point; - + /** * The original DOM mouse event fired by the browser. */ originalEvent: MouseEvent; } } - + declare module L { export interface LeafletPopupEvent extends LeafletEvent { @@ -1901,7 +1921,7 @@ declare module L { distance: number; } } - + declare module L { export interface LeafletResizeEvent extends LeafletEvent { @@ -1910,14 +1930,14 @@ declare module L { * The old size before resize event. */ oldSize: Point; - + /** * The new size after the resize event. */ newSize: Point; } } - + declare module L { export interface LeafletTileEvent extends LeafletEvent { @@ -1926,14 +1946,14 @@ declare module L { * The tile element (image). */ tile: HTMLElement; - + /** * The source URL of the tile. */ url: string; } } - + declare module L { module LineUtil { @@ -1947,27 +1967,27 @@ declare module L { * released as a separated micro-library Simplify.js. */ export function simplify(points: Point[], tolerance: number): Point[]; - + /** * Returns the distance between point p and segment p1 to p2. */ export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; - + /** * Returns the closest point from a point p on a segment p1 to p2. */ export function closestPointOnSegment(p: Point, p1: Point, p2: Point): number; - + /** * Clips the segment a to b by rectangular bounds (modifying the segment points * directly!). Used by Leaflet to only show polyline points that are on the screen * or near, increasing performance. */ export function clipSegment(a: Point, b: Point, bounds: Bounds): void; - + } } - + declare module L { export interface LocateOptions { @@ -1980,7 +2000,7 @@ declare module L { * Default value: false. */ watch?: boolean; - + /** * If true, automatically sets the map view to the user location with respect * to detection accuracy, or to world view if geolocation failed. @@ -1988,14 +2008,14 @@ declare module L { * Default value: false. */ setView?: boolean; - + /** * The maximum zoom for automatic view setting when using `setView` option. * * Default value: Infinity. */ maxZoom?: number; - + /** * Number of millisecond to wait for a response from geolocation before firing * a locationerror event. @@ -2003,7 +2023,7 @@ declare module L { * Default value: 10000. */ timeout?: number; - + /** * Maximum age of detected location. If less than this amount of milliseconds * passed since last geolocation response, locate will return a cached location. @@ -2011,7 +2031,7 @@ declare module L { * Default value: 0. */ maximumAge?: number; - + /** * Enables high accuracy, see description in the W3C spec. * @@ -2020,7 +2040,7 @@ declare module L { enableHighAccuracy?: boolean; } } - + declare module L { /** @@ -2063,17 +2083,17 @@ declare module L { * animation options. */ setView(center: LatLng, zoom?: number, options?: ZoomPanOptions): Map; - + /** * Sets the zoom of the map. */ setZoom(zoom: number, options?: ZoomOptions): Map; - + /** * Increases the zoom of the map by delta (1 by default). */ zoomIn(delta?: number, options?: ZoomOptions): Map; - + /** * Decreases the zoom of the map by delta (1 by default). */ @@ -2084,43 +2104,43 @@ declare module L { * (e.g. used internally for scroll zoom and double-click zoom). */ setZoomAround(latlng: LatLng, zoom: number, options?: ZoomOptions): Map; - + /** * Sets a map view that contains the given geographical bounds with the maximum * zoom level possible. */ fitBounds(bounds: LatLngBounds, options?: FitBoundsOptions): Map; - + /** * Sets a map view that mostly contains the whole world with the maximum zoom * level possible. */ fitWorld(options?: FitBoundsOptions): Map; - + /** * Pans the map to a given center. Makes an animated pan if new center is not more * than one screen away from the current one. */ panTo(latlng: LatLng, options?: PanOptions): Map; - + /** * Pans the map to the closest view that would lie inside the given bounds (if * it's not already). */ panInsideBounds(bounds: LatLngBounds): Map; - + /** * Pans the map by a given number of pixels (animated). */ panBy(point: Point, options?: PanOptions): Map; - + /** * Checks if the map container size changed and updates the map if so — call it * after you've changed the map size dynamically, also animating pan by default. * If options.pan is false, panning will not occur. */ invalidateSize(options: ZoomPanOptions): Map; - + /** * Checks if the map container size changed and updates the map if so — call it * after you've changed the map size dynamically, also animating pan by default. @@ -2132,7 +2152,7 @@ declare module L { * passing the given animation options through to `setView`, if required. */ setMaxBounds(bounds: LatLngBounds, options?: ZoomPanOptions): Map; - + /** * Tries to locate the user using Geolocation API, firing locationfound event * with location data on success or locationerror event on failure, and optionally @@ -2141,7 +2161,7 @@ declare module L { * details. */ locate(options?: LocateOptions): Map; - + /** * Stops watching location previously initiated by map.locate({watch: true}) * and aborts resetting the map view if map.locate was called with {setView: true}. @@ -2152,34 +2172,34 @@ declare module L { * Destroys the map and clears all related event listeners. */ remove(): Map; - + // Methods for Getting Map State /** * Returns the geographical center of the map view. */ getCenter(): LatLng; - + /** * Returns the current zoom of the map view. */ getZoom(): number; - + /** * Returns the minimum zoom level of the map. */ getMinZoom(): number; - + /** * Returns the maximum zoom level of the map. */ getMaxZoom(): number; - + /** * Returns the LatLngBounds of the current map view. */ getBounds(): LatLngBounds; - + /** * Returns the maximum zoom level on which the given bounds fit to the map view * in its entirety. If inside (optional) is set to true, the method instead returns @@ -2187,24 +2207,24 @@ declare module L { * entirety. */ getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; - + /** * Returns the current size of the map container. */ getSize(): Point; - + /** * Returns the bounds of the current map view in projected pixel coordinates * (sometimes useful in layer and overlay implementations). */ getPixelBounds(): Bounds; - + /** * Returns the projected pixel coordinates of the top left point of the map layer * (useful in custom layer and overlay implementations). */ getPixelOrigin(): Point; - + // Methods for Layers and Controls /** @@ -2212,31 +2232,31 @@ declare module L { * the layer is inserted under all others (useful when switching base tile layers). */ addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; - + /** * Removes the given layer from the map. */ removeLayer(layer: ILayer): Map; - + /** * Returns true if the given layer is currently added to the map. */ hasLayer(layer: ILayer): boolean; - + /** * Opens the specified popup while closing the previously opened (to make sure * only one is opened at one time for usability). */ openPopup(popup: Popup): Map; - + /** - * Creates a popup with the specified options and opens it in the given point + * Creates a popup with the specified options and opens it in the given point * on a map. */ openPopup(html: string, latlng: LatLng, options?: PopupOptions): Map; - + /** - * Creates a popup with the specified options and opens it in the given point + * Creates a popup with the specified options and opens it in the given point * on a map. */ openPopup(el: HTMLElement, latlng: LatLng, options?: PopupOptions): Map; @@ -2245,17 +2265,17 @@ declare module L { * Closes the popup previously opened with openPopup (or the given one). */ closePopup(popup?: Popup): Map; - + /** * Adds the given control to the map. */ addControl(control: IControl): Map; - + /** * Removes the given control from the map. */ removeControl(control: IControl): Map; - + // Conversion Methods /** @@ -2263,116 +2283,116 @@ declare module L { * (useful for placing overlays on the map). */ latLngToLayerPoint(latlng: LatLng): Point; - + /** * Returns the geographical coordinates of a given map layer point. */ layerPointToLatLng(point: Point): LatLng; - + /** * Converts the point relative to the map container to a point relative to the * map layer. */ containerPointToLayerPoint(point: Point): Point; - + /** * Converts the point relative to the map layer to a point relative to the map * container. */ layerPointToContainerPoint(point: Point): Point; - + /** * Returns the map container point that corresponds to the given geographical * coordinates. */ latLngToContainerPoint(latlng: LatLng): Point; - + /** * Returns the geographical coordinates of a given map container point. */ containerPointToLatLng(point: Point): LatLng; - + /** * Projects the given geographical coordinates to absolute pixel coordinates * for the given zoom level (current zoom level by default). */ project(latlng: LatLng, zoom?: number): Point; - + /** * Projects the given absolute pixel coordinates to geographical coordinates * for the given zoom level (current zoom level by default). */ unproject(point: Point, zoom?: number): LatLng; - + /** * Returns the pixel coordinates of a mouse click (relative to the top left corner * of the map) given its event object. */ mouseEventToContainerPoint(event: LeafletMouseEvent): Point; - + /** * Returns the pixel coordinates of a mouse click relative to the map layer given * its event object. */ mouseEventToLayerPoint(event: LeafletMouseEvent): Point; - + /** * Returns the geographical coordinates of the point the mouse clicked on given * the click's event object. */ mouseEventToLatLng(event: LeafletMouseEvent): LatLng; - + // Other Methods /** * Returns the container element of the map. */ getContainer(): HTMLElement; - + /** * Returns an object with different map panes (to render overlays in). */ getPanes(): MapPanes; - + // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? /** * Runs the given callback when the map gets initialized with a place and zoom, * or immediately if it happened already, optionally passing a function context. */ whenReady(fn: (map: Map) => void, context?: any): Map; - + // Properties /** * Map dragging handler (by both mouse and touch). */ dragging: IHandler; - + /** * Touch zoom handler. */ touchZoom: IHandler; - + /** * Double click zoom handler. */ doubleClickZoom: IHandler; - + /** * Scroll wheel zoom handler. */ scrollWheelZoom: IHandler; - + /** * Box (shift-drag with mouse) zoom handler. */ boxZoom: IHandler; - + /** * Keyboard navigation handler. */ keyboard: IHandler; - + /** * Mobile touch hacks (quick tap and touch hold) handler. */ @@ -2421,27 +2441,27 @@ declare module L { * Initial geographical center of the map. */ center?: LatLng; - + /** * Initial map zoom. */ zoom?: number; - + /** * Layers that will be added to the map initially. */ layers?: ILayer[]; - + /** * Minimum zoom level of the map. Overrides any minZoom set on map layers. */ minZoom?: number; - + /** * Maximum zoom level of the map. This overrides any maxZoom set on map layers. */ maxZoom?: number; - + /** * When this option is set, the map restricts the view to the given geographical * bounds, bouncing the user back when he tries to pan outside the view, and also @@ -2449,7 +2469,7 @@ declare module L { * on the map size). To set the restriction dynamically, use setMaxBounds method */ maxBounds?: LatLngBounds; - + /** * Coordinate Reference System to use. Don't change this if you're not sure * what it means. @@ -2457,7 +2477,7 @@ declare module L { * Default value: L.CRS.EPSG3857. */ crs?: ICRS; - + // Interaction Options /** @@ -2466,14 +2486,14 @@ declare module L { * Default value: true. */ dragging?: boolean; - + /** * Whether the map can be zoomed by touch-dragging with two fingers. * * Default value: true. */ touchZoom?: boolean; - + /** * Whether the map can be zoomed by using the mouse wheel. * If passed 'center', it will zoom to the center of the view regardless of @@ -2482,7 +2502,7 @@ declare module L { * Default value: true. */ scrollWheelZoom?: boolean; - + /** * Whether the map can be zoomed in by double clicking on it and zoomed out * by double clicking while holding shift. @@ -2523,7 +2543,7 @@ declare module L { * Default value: true. */ trackResize?: boolean; - + /** * With this option enabled, the map tracks when you pan to another "copy" of * the world and seamlessly jumps to the original one so that all overlays like @@ -2532,14 +2552,14 @@ declare module L { * Default value: false. */ worldCopyJump?: boolean; - + /** * Set it to false if you don't want popups to close when user clicks the map. * * Default value: true. */ closePopupOnClick?: boolean; - + // Keyboard Navigation Options /** @@ -2549,21 +2569,21 @@ declare module L { * Default value: true. */ keyboard?: boolean; - + /** * Amount of pixels to pan when pressing an arrow key. * * Default value: 80. */ keyboardPanOffset?: number; - + /** * Number of zoom levels to change when pressing + or - key. * * Default value: 1. */ keyboardZoomOffset?: number; - + // Panning Inertia Options /** @@ -2574,21 +2594,21 @@ declare module L { * Default value: true. */ inertia?: boolean; - + /** * The rate with which the inertial movement slows down, in pixels/second2. * * Default value: 3000. */ inertiaDeceleration?: number; - + /** * Max speed of the inertial movement, in pixels/second. * * Default value: 1500. */ inertiaMaxSpeed?: number; - + /** * Amount of milliseconds that should pass between stopping the movement and * releasing the mouse or touch to prevent inertial movement. @@ -2596,7 +2616,7 @@ declare module L { * Default value: 32 for touch devices and 14 for the rest. */ inertiaThreshold?: number; - + // Control options /** @@ -2605,14 +2625,14 @@ declare module L { * Default value: true. */ zoomControl?: boolean; - + /** * Whether the attribution control is added to the map by default. * * Default value: true. */ attributionControl?: boolean; - + // Animation options /** @@ -2620,7 +2640,7 @@ declare module L { * browsers that support CSS3 Transitions except Android. */ fadeAnimation?: boolean; - + /** * Whether the tile zoom animation is enabled. By default it's enabled in all * browsers that support CSS3 Transitions except Android. @@ -2650,7 +2670,7 @@ declare module L { bounceAtZoomLimits?: boolean; } } - + declare module L { export interface MapPanes { @@ -2691,7 +2711,7 @@ declare module L { popupPane: HTMLElement; } } - + declare module L { /** @@ -2713,44 +2733,44 @@ declare module L { * Adds the marker to the map. */ addTo(map: Map): Marker; - + /** * Returns the current geographical position of the marker. */ getLatLng(): LatLng; - + /** * Changes the marker position to the given point. */ setLatLng(latlng: LatLng): Marker; - + /** * Changes the marker icon. */ setIcon(icon: Icon): Marker; - + /** * Changes the zIndex offset of the marker. */ setZIndexOffset(offset: number): Marker; - + /** * Changes the opacity of the marker. */ setOpacity(opacity: number): Marker; - + /** * Updates the marker position, useful if coordinates of its latLng object * were changed directly. */ update(): Marker; - + /** * Binds a popup with a particular HTML content to a click on this marker. You * can also open the bound popup with the Marker openPopup method. */ bindPopup(html: string, options?: PopupOptions): Marker; - + /** * Binds a popup with a particular HTML content to a click on this marker. You * can also open the bound popup with the Marker openPopup method. @@ -2767,7 +2787,7 @@ declare module L { * Unbinds the popup previously bound to the marker with bindPopup. */ unbindPopup(): Marker; - + /** * Opens the popup previously bound by the bindPopup method. */ @@ -2776,8 +2796,8 @@ declare module L { /** * Returns the popup previously bound by the bindPopup method. */ - getPopup(): Popup; - + getPopup(): Popup; + /** * Closes the bound popup of the marker if it's opened. */ @@ -2816,13 +2836,13 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; - + //////////////// //////////////// addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; @@ -2841,7 +2861,7 @@ declare module L { off(eventMap?: any, context?: any): Marker; } } - + declare module L { export interface MarkerOptions { @@ -2853,7 +2873,7 @@ declare module L { * Default value: new L.Icon.Default(). */ icon?: Icon; - + /** * If false, the marker will not emit mouse events and will act as a part of the * underlying map. @@ -2861,7 +2881,7 @@ declare module L { * Default value: true. */ clickable?: boolean; - + /** * Whether the marker is draggable with mouse/touch or not. * @@ -2875,7 +2895,7 @@ declare module L { * Default value: true. */ keyboard?: boolean; - + /** * Text for the browser tooltip that appear on marker hover (no tooltip by default). * @@ -2889,7 +2909,7 @@ declare module L { * Default value: ''. */ alt?: string; - + /** * By default, marker images zIndex is set automatically based on its latitude. * You this option if you want to put the marker on top of all others (or below), @@ -2898,21 +2918,21 @@ declare module L { * Default value: 0. */ zIndexOffset?: number; - + /** * The opacity of the marker. * * Default value: 1.0. */ opacity?: number; - + /** * If true, the marker will get on top of others when you hover the mouse over it. * * Default value: false. */ riseOnHover?: boolean; - + /** * The z-index offset used for the riseOnHover feature. * @@ -2921,7 +2941,7 @@ declare module L { riseOffset?: number; } } - + declare module L { /** @@ -2964,7 +2984,7 @@ declare module L { toGeoJSON(): any; } } - + declare module L { /** @@ -3005,7 +3025,7 @@ declare module L { toGeoJSON(): any; } } - + declare module L { export interface PanOptions { @@ -3013,14 +3033,14 @@ declare module L { /** * If true, panning will always be animated if possible. If false, it will not * animate panning, either resetting the map view if panning more than a screen - * away, or just setting a new offset for the map pane (except for `panBy` + * away, or just setting a new offset for the map pane (except for `panBy` * which always does the latter). */ animate?: boolean; /** * Duration of animated panning. - * + * * Default value: 0.25. */ duration?: number; @@ -3035,13 +3055,13 @@ declare module L { /** * If true, panning won't fire movestart event on start (used internally for panning inertia). - * + * * Default value: false. */ noMoveStart?: boolean; } } - + declare module L { export interface Path extends ILayer, IEventPowered { @@ -3050,12 +3070,12 @@ declare module L { * Adds the layer to the map. */ addTo(map: Map): Path; - + /** * Binds a popup with a particular HTML content to a click on this path. */ bindPopup(html: string, options?: PopupOptions): Path; - + /** * Binds a popup with a particular HTML content to a click on this path. */ @@ -3070,38 +3090,38 @@ declare module L { * Unbinds the popup previously bound to the path with bindPopup. */ unbindPopup(): Path; - + /** * Opens the popup previously bound by the bindPopup method in the given point, * or in one of the path's points if not specified. */ openPopup(latlng?: LatLng): Path; - + /** * Closes the path's bound popup if it is opened. */ closePopup(): Path; - + /** * Changes the appearance of a Path based on the options in the Path options object. */ setStyle(object: PathOptions): Path; - + /** * Returns the LatLngBounds of the path. */ getBounds(): LatLngBounds; - + /** * Brings the layer to the top of all path layers. */ bringToFront(): Path; - + /** * Brings the layer to the bottom of all path layers. */ bringToBack(): Path; - + /** * Redraws the layer. Sometimes useful after you changed the coordinates that * the path uses. @@ -3115,13 +3135,13 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; - + //////////////// //////////////// addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; @@ -3181,48 +3201,48 @@ declare module L { * Default value: true. */ stroke?: boolean; - + /** * Stroke color. * * Default value: '#03f'. */ color?: string; - + /** * Stroke width in pixels. * * Default value: 5. */ weight?: number; - + /** * Stroke opacity. * * Default value: 0.5. */ opacity?: number; - + /** * Whether to fill the path with color. Set it to false to disable filling on polygons * or circles. */ fill?: boolean; - + /** * Fill color. * * Default value: same as color. */ fillColor?: string; - + /** * Fill opacity. * * Default value: 0.2. */ fillOpacity?: number; - + /** * A string that defines the stroke dash pattern. Doesn't work on canvas-powered * layers (e.g. Android 2). @@ -3242,7 +3262,7 @@ declare module L { * Default: null. */ lineJoin?: string; - + /** * If false, the vector will not emit mouse events and will act as a part of the * underlying map. @@ -3262,10 +3282,10 @@ declare module L { * Default value: ''. */ className?: string; - + } } - + declare module L { /** @@ -3288,48 +3308,48 @@ declare module L { * Returns the result of addition of the current and the given points. */ add(otherPoint: Point): Point; - + /** * Returns the result of subtraction of the given point from the current. */ subtract(otherPoint: Point): Point; - + /** * Returns the result of multiplication of the current point by the given number. */ multiplyBy(number: number): Point; - + /** * Returns the result of division of the current point by the given number. If * optional round is set to true, returns a rounded result. */ divideBy(number: number, round?: boolean): Point; - + /** * Returns the distance between the current and the given points. */ distanceTo(otherPoint: Point): number; - + /** * Returns a copy of the current point. */ clone(): Point; - + /** * Returns a copy of the current point with rounded coordinates. */ round(): Point; - + /** * Returns true if the given point has the same coordinates. */ equals(otherPoint: Point): boolean; - + /** * Returns a string representation of the point for debugging purposes. */ toString(): string; - + /** * The x coordinate. */ @@ -3341,7 +3361,7 @@ declare module L { y: number; } } - + declare module L { /** @@ -3369,7 +3389,7 @@ declare module L { export interface Polygon extends Polyline { } } - + declare module L { /** @@ -3392,24 +3412,24 @@ declare module L { * Adds a given point to the polyline. */ addLatLng(latlng: LatLng): Polyline; - + /** * Replaces all the points in the polyline with the given array of geographical * points. */ setLatLngs(latlngs: LatLng[]): Polyline; - + /** * Returns an array of the points in the path. */ getLatLngs(): LatLng[]; - + /** * Allows adding, removing or replacing points in the polyline. Syntax is the * same as in Array#splice. Returns the array of removed points (if any). */ spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; - + /** * Returns the LatLngBounds of the polyline. */ @@ -3421,7 +3441,7 @@ declare module L { toGeoJSON(): any; } } - + declare module L { export interface PolylineOptions { @@ -3433,7 +3453,7 @@ declare module L { * Default value: 1.0. */ smoothFactor?: number; - + /** * Disabled polyline clipping. * @@ -3442,7 +3462,7 @@ declare module L { noClip?: boolean; } } - + declare module L { module PolyUtil { @@ -3456,7 +3476,7 @@ declare module L { export function clipPolygon(points: Point[], bounds: Bounds): Point[]; } } - + declare module L { /** @@ -3481,17 +3501,17 @@ declare module L { * Adds the popup to the map. */ addTo(map: Map): Popup; - + /** * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). */ openOn(map: Map): Popup; - + /** * Sets the geographical point where the popup will open. */ setLatLng(latlng: LatLng): Popup; - + /** * Returns the geographical point of popup. */ @@ -3521,7 +3541,7 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). @@ -3535,7 +3555,7 @@ declare module L { update(): Popup; } } - + declare module L { export interface PopupOptions { @@ -3546,20 +3566,20 @@ declare module L { * Default value: 300. */ maxWidth?: number; - + /** * Min width of the popup. * * Default value: 50. */ minWidth?: number; - + /** * If set, creates a scrollable container of the given height inside a popup * if its content exceeds it. */ maxHeight?: number; - + /** * Set it to false if you don't want the map to do panning animation to fit the opened * popup. @@ -3567,14 +3587,14 @@ declare module L { * Default value: true. */ autoPan?: boolean; - + /** * Controls the presense of a close button in the popup. * * Default value: true. */ closeButton?: boolean; - + /** * The offset of the popup position. Useful to control the anchor of the popup * when opening it on some overlays. @@ -3598,7 +3618,7 @@ declare module L { * Default value: null. */ autoPanPaddingBottomRight?: Point; - + /** * The margin between the popup and the edges of the map view after autopanning * was performed. @@ -3606,7 +3626,7 @@ declare module L { * Default value: new Point(5, 5). */ autoPanPadding?: Point; - + /** * Whether to animate the popup on zoom. Disable it if you have problems with * Flash content inside popups. @@ -3616,14 +3636,14 @@ declare module L { zoomAnimation?: boolean; /** - * Set it to false if you want to override the default behavior of the popup + * Set it to false if you want to override the default behavior of the popup * closing when user clicks the map (set globally by the Map closePopupOnClick * option). */ closeOnClick?: boolean; } } - + declare module L { export interface PosAnimationStatic extends ClassStatic { @@ -3641,7 +3661,7 @@ declare module L { * of the cubic bezier curve, 0.5 by default) */ run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; - + //////////////// //////////////// addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; @@ -3660,7 +3680,7 @@ declare module L { off(eventMap?: any, context?: any): PosAnimation; } } - + declare module L { module Projection { @@ -3671,14 +3691,14 @@ declare module L { * is a sphere. Used by the EPSG:3857 CRS. */ export var SphericalMercator: IProjection; - + /** * Elliptical Mercator projection — more complex than Spherical Mercator. * Takes into account that Earth is a geoid, not a perfect sphere. Used by the * EPSG:3395 CRS. */ export var Mercator: IProjection; - + /** * Equirectangular, or Plate Carree projection — the most simple projection, * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. @@ -3688,7 +3708,7 @@ declare module L { export var LonLat: IProjection; } } - + declare module L { /** @@ -3713,8 +3733,8 @@ declare module L { setBounds(bounds: LatLngBounds): Rectangle; } } - - + + declare module L { export interface ScaleOptions { @@ -3724,26 +3744,26 @@ declare module L { * Default value: 'bottomleft'. */ position?: string; - + /** * Maximum width of the control in pixels. The width is set dynamically to show * round values (e.g. 100, 200, 500). * Default value: 100. */ maxWidth?: number; - + /** * Whether to show the metric scale line (m/km). * Default value: true. */ metric?: boolean; - + /** * Whether to show the imperial scale line (mi/ft). * Default value: true. */ imperial?: boolean; - + /** * If true, the control is updated on moveend, otherwise it's always up-to-date * (updated on move). @@ -3752,7 +3772,7 @@ declare module L { updateWhenIdle?: boolean; } } - + declare module L { export interface TileLayerStatic extends ClassStatic { @@ -3784,32 +3804,32 @@ declare module L { * Adds the layer to the map. */ addTo(map: Map): TileLayer; - + /** * Brings the tile layer to the top of all tile layers. */ bringToFront(): TileLayer; - + /** * Brings the tile layer to the bottom of all tile layers. */ bringToBack(): TileLayer; - + /** * Changes the opacity of the tile layer. */ setOpacity(opacity: number): TileLayer; - + /** * Sets the zIndex of the tile layer. */ setZIndex(zIndex: number): TileLayer; - + /** * Causes the layer to clear all the tiles and request them again. */ redraw(): TileLayer; - + /** * Updates the layer's URL template and redraws it. */ @@ -3828,13 +3848,13 @@ declare module L { * Called on map.addLayer(layer). */ onAdd(map: Map): void; - + /** * Should contain all clean up code that removes the overlay's elements from * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). */ onRemove(map: Map): void; - + //////////////// //////////////// addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; @@ -3879,7 +3899,7 @@ declare module L { } export interface TileLayerFactory { - + /** * Instantiates a tile layer object given a URL template and optionally an options * object. @@ -3900,7 +3920,7 @@ declare module L { export var tileLayer: TileLayerFactory; } - + declare module L { export interface TileLayerOptions { @@ -3911,7 +3931,7 @@ declare module L { * Default value: 0. */ minZoom?: number; - + /** * Maximum zoom number. * @@ -3927,14 +3947,14 @@ declare module L { * Default value: null. */ maxNativeZoom?: number; - + /** * Tile size (width and height in pixels, assuming tiles are square). * * Default value: 256. */ tileSize?: number; - + /** * Subdomains of the tile service. Can be passed in the form of one string (where * each letter is a subdomain name) or an array of strings. @@ -3942,14 +3962,14 @@ declare module L { * Default value: 'abc'. */ subdomains?: string[]; - + /** * URL to the tile image to show in place of the tile that failed to load. * * Default value: ''. */ errorTileUrl?: string; - + /** * e.g. "© CloudMade" — the string used by the attribution control, describes * the layer data. @@ -3957,14 +3977,14 @@ declare module L { * Default value: ''. */ attribution?: string; - + /** * If true, inverses Y axis numbering for tiles (turn this on for TMS services). * * Default value: false. */ tms?: boolean; - + /** * If set to true, the tile coordinates won't be wrapped by world width (-180 * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this @@ -3974,7 +3994,7 @@ declare module L { * Default value: false. */ continuousWorld?: boolean; - + /** * If set to true, the tiles just won't load outside the world width (-180 to 180 * longitude) instead of repeating. @@ -3982,14 +4002,14 @@ declare module L { * Default value: false. */ noWrap?: boolean; - + /** * The zoom number used in tile URLs will be offset with this value. * * Default value: 0. */ zoomOffset?: number; - + /** * If set to true, the zoom number used in tile URLs will be reversed (maxZoom * - zoom instead of zoom) @@ -3997,31 +4017,31 @@ declare module L { * Default value: false. */ zoomReverse?: boolean; - + /** * The opacity of the tile layer. * * Default value: 1.0. */ opacity?: number; - + /** * The explicit zIndex of the tile layer. Not set by default. */ zIndex?: number; - + /** * If true, all the tiles that are not visible after panning are removed (for * better performance). true by default on mobile WebKit, otherwise false. */ unloadInvisibleTiles?: boolean; - + /** * If false, new tiles are loaded during panning, otherwise only after it (for * better performance). true by default on mobile WebKit, otherwise false. */ updateWhenIdle?: boolean; - + /** * If true and user is on a retina display, it will request four tiles of half the * specified size and a bigger zoom level in place of one to utilize the high resolution. @@ -4029,7 +4049,7 @@ declare module L { * Default value: false. */ detectRetina?: boolean; - + /** * If true, all the tiles that are not visible after panning are placed in a reuse * queue from which they will be fetched when new tiles become visible (as opposed @@ -4058,7 +4078,7 @@ declare module L { * Only accepts real L.Point instances, not arrays. */ transform(point: Point, scale?: number): Point; - + /** * Returns the reverse transformation of the given point, optionally divided * by the given scale. Only accepts real L.Point instances, not arrays. @@ -4066,7 +4086,7 @@ declare module L { untransform(point: Point, scale?: number): Point; } } - + declare module L { module Util { @@ -4076,18 +4096,18 @@ declare module L { * and returns the latter. Has an L.extend shortcut. */ export function extend(dest: any, ...sources: any[]): any; - + /** * Returns a function which executes function fn with the given scope obj (so * that this keyword refers to obj inside the function code). Has an L.bind shortcut. */ export function bind(fn: T, obj: any): T; - + /** * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. */ export function stamp(obj: any): string; - + /** * Returns a wrapper around the function fn that makes sure it's called not more * often than a certain time interval time, but as fast as possible otherwise @@ -4096,46 +4116,46 @@ declare module L { * be called. */ export function limitExecByInterval(fn: T, time: number, context?: any): T; - + /** * Returns a function which always returns false. */ export function falseFn(): () => boolean; - + /** * Returns the number num rounded to digits decimals. */ export function formatNum(num: number, digits: number): number; - + /** * Trims and splits the string on whitespace and returns the array of parts. */ export function splitWords(str: string): string[]; - + /** * Merges the given properties to the options of the obj object, returning the * resulting options. See Class options. Has an L.setOptions shortcut. */ export function setOptions(obj: any, options: any): any; - + /** * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} * translates to '?a=foo&b=bar'. */ export function getParamString(obj: any): string; - + /** * Simple templating facility, creates a string by applying the values of the * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. */ export function template(str: string, data: any): string; - + /** * Returns true if the given object is an array. */ export function isArray(obj: any): boolean; - + /** * Trims the whitespace from both ends of the string and returns the result. */ @@ -4149,8 +4169,8 @@ declare module L { export var emptyImageUrl: string; } } - - + + declare module L { export interface WMSOptions { @@ -4161,37 +4181,37 @@ declare module L { * Default value: ''. */ layers?: string; - + /** * Comma-separated list of WMS styles. * * Default value: 'image/jpeg'. */ styles?: string; - + /** * WMS image format (use 'image/png' for layers with transparency). * * Default value: false. */ format?: string; - + /** * If true, the WMS service will return images with transparency. * * Default value: '1.1.1'. */ transparent?: boolean; - + /** * Version of the WMS service to use. */ version?: string; - + } } - - + + declare module L { export interface ZoomOptions { @@ -4204,7 +4224,7 @@ declare module L { position?: string; } } - + declare module L { export interface ZoomPanOptions { @@ -4237,10 +4257,10 @@ declare module L { debounceMoveend?: boolean; } } - + /** - * Forces Leaflet to use the Canvas back-end (if available) for vector layers - * instead of SVG. This can increase performance considerably in some cases + * Forces Leaflet to use the Canvas back-end (if available) for vector layers + * instead of SVG. This can increase performance considerably in some cases * (e.g. many thousands of circle markers on the map). */ declare var L_PREFER_CANVAS: boolean; @@ -4251,11 +4271,11 @@ declare var L_PREFER_CANVAS: boolean; declare var L_NO_TOUCH: boolean; /** - * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning + * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning * (which may cause glitches in some rare environments) even if they're supported. */ declare var L_DISABLE_3D: boolean; - + declare module "leaflet" { export = L; } diff --git a/less-middleware/less-middleware-tests.ts b/less-middleware/less-middleware-tests.ts new file mode 100644 index 0000000000..0a84203b60 --- /dev/null +++ b/less-middleware/less-middleware-tests.ts @@ -0,0 +1,28 @@ +/// + +import express = require('express'); +import lessMiddleware = require('less-middleware'); +var app = express(); + +app.use(lessMiddleware('public', { + cacheFile: null, + debug: false, + dest: 'dest', + force: false, + once: false, + pathRoot: 'root', + postprocess: { + css: function(css, req) { return css; }, + }, + preprocess: { + less: function(src, req) { return src; }, + path: function(pathname, req) { return pathname; }, + importPaths: function(paths, req) { return paths; } + }, + render: { + compress: 'auto', + yuicompress: false, + paths: ['foo', 'bar'] + }, + storeCss: function(css, req, next) {}, +})); diff --git a/less-middleware/less-middleware.d.ts b/less-middleware/less-middleware.d.ts new file mode 100644 index 0000000000..ee0e0069d5 --- /dev/null +++ b/less-middleware/less-middleware.d.ts @@ -0,0 +1,108 @@ +// Type definitions for less-middleware 2.0.1 +// Project: https://github.com/emberfeather/less.js-middleware +// Definitions by: Federico Bond +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* =================== USAGE =================== + + import lessMiddleware = require('less-middleware'); + app.use(lessMiddleware(source, options)); + + =============================================== */ + +/// + +declare module "less-middleware" { + import express = require('express'); + + /** + * Middleware created to allow processing of Less files for Connect JS framework + * and by extension the Express JS framework + */ + function lessMiddleware(source: string, options?: { + /** + * Show more verbose logging? + */ + debug?: boolean; + + /** + * Destination directory to output the compiled .css files. + */ + dest?: string; + + /** + * Always re-compile less files on each request. + */ + force?: boolean; + + /** + * Only recompile once after each server restart. + * Useful for reducing disk i/o on production. + */ + once?: boolean; + + /** + * Common root of the source and destination. + * It is prepended to both the source and destination before being used. + */ + pathRoot?: string; + + /** + * Object containing functions relevant to preprocessing data. + */ + postprocess?: { + + /** + * Function that modifies the compiled css output before being stored. + */ + css?(css: string, req: express.Request): string; + }; + + /** + * Object containing functions relevant to preprocessing data. + */ + preprocess?: { + + /** + * Function that modifies the raw less output before being parsed and compiled. + */ + less?(css: string, req: express.Request): string; + + /** + * Function that modifies the less pathname before being loaded from the filesystem. + */ + path?(pathname: string, req: express.Request): string; + + /** + * Function that modifies the import paths used by the less parser per request. + */ + importPaths?(paths: string[], req: express.Request): string[]; + }; + + /** + * Options for the less render. + */ + render?: { + + compress?: string; + yuicompress?: boolean; + paths?: string[]; + }; + + /** + * Function that is in charge of storing the css in the filesystem. + */ + storeCss?(pathname: string, css: string, req: express.Request, next: Function): void; + + /** + * Path to a JSON file that will be used to cache less data across server restarts. + * This can greatly speed up initial load time after a server restart - if the less + * files haven't changed and the css files still exist, specifying this option will + * mean that the less files don't need to be recompiled after a server restart. + */ + cacheFile?: string; + + }): express.RequestHandler; + + export = lessMiddleware; +} diff --git a/less/less-tests.ts b/less/less-tests.ts index a984306ee1..71dfbae762 100644 --- a/less/less-tests.ts +++ b/less/less-tests.ts @@ -2,33 +2,12 @@ import less = require("less"); -declare var __dirname: string; - -less.render('.class { width: (1 + 1) }', (e, css) => console.log(css)); - -var parser: less.Parser = new less.Parser; - -parser.parse('.class { width: (1 + 1) }', function (err, tree) { - if (err) return console.error(err); - tree.toCSS(); +less.render(".class { width: (1 + 1) }").then((output) => { + console.log(output.css); }); -var parser2 = new less.Parser({ - paths: ['.', './lib'], - filename: 'style.less' +less.render("fail").then((output) => { + throw new Error("promise should have been rejected"); +}, () => { + console.log("rejected as expected"); }); - -parser2.parse('.class { width: (1 + 1) }', (e, tree) => tree.toCSS({ compress: true })); - -var lessParser = new less.Parser({ - paths: [__dirname], - filename: "out.less" -}); - -lessParser.parse('.class { width: (1 + 1) }', function (err, tree) { - tree.rules.forEach(function (rule) { - if (rule.path) { - console.log(rule.path); - } - }); -}); \ No newline at end of file diff --git a/less/less.d.ts b/less/less.d.ts index 4c096525d3..2c10ce50e1 100644 --- a/less/less.d.ts +++ b/less/less.d.ts @@ -1,556 +1,75 @@ // Type definitions for LESS // Project: http://lesscss.org/ -// Definitions by: AndrewGaspar +// Definitions by: Tom Hasner // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module less { - class LessError { - constructor(e: Error, env); +declare module Less { + // Promise definitions from ../es6-promise/es6-promise.d.ts + interface Thenable { + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + } - type: any; - message: string; + class Promise implements Thenable { + constructor(callback: (resolve : (value?: R | Thenable) => void, reject: (error?: any) => void) => void); + + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise; + + catch(onRejected?: (error: any) => U | Thenable): Promise; + + finally(finallyCallback: () => any): Promise; + } + + interface RootFileInfo { filename: string; - index; - line: number; - callLine: number; - callExtract; - stack; - column; - extract: any[]; + relativeUrls: boolean; + rootpath: string; + currentDirectory: string; + entryPath: string; + rootFilename: string; + } + + class PluginManager { + constructor(less: LessStatic); + } + + interface Plugin { + install: (less: LessStatic, pluginManager: PluginManager) => void; + } + + interface SourceMapOption { + sourceMapURL: string; + sourceMapBasepath: string; + sourceMapRootpath: string; + outputSourceFiles: boolean; + sourceMapFileInline: boolean; } interface Options { - contents?; - rootpath?: string; - files?; - paths?: string[]; - mime?: string; + sourceMap?: SourceMapOption; filename?: string; - optimization?: number; - dumpLineNumbers?: boolean; - strictImports?; - entryPath?: string; - relativeUrls?; - errback? (path: string, paths: string[], callback: Function, env: Options); - frames?; - compress?: boolean; + plugins: Plugin[]; + rootFileInfo?: RootFileInfo; } - export module tree { - export module mixin { // TODO - export class Call { - - } - - export class Definition extends Ruleset { - - } - } - - export module functions { - export function rgb(r: number, g: number, b: number): Color; - export function rgba(r: number, g: number, b: number, a: number): Color; - export function hsl(h: number, s?: number, l?: number): Color; - export function hsla(h: number, s?: number, l?: number, a?: number): Color; - export function hsv(h: number, s: number, v: number): Color; - export function hsva(h: number, s: number, v: number, a: number): Color; - export function hue(color: Color): Dimension; - export function saturation(color: Color): Dimension; - export function lightness(color: Color): Dimension; - export function red(color: Color): Dimension; - export function green(color: Color): Dimension; - export function blue(color: Color): Dimension; - export function alpha(color: Color): Dimension; - export function luma(color: Color): Dimension; - export function saturate(color: Color, amount: IValuableNumber): Color; - export function desaturate(color: Color, amount: IValuableNumber): Color; - export function lighten(color: Color, amount: IValuableNumber): Color; - export function darken(color: Color, amount: IValuableNumber): Color; - export function fadein(color: Color, amount: IValuableNumber): Color; - export function fadeout(color: Color, amount: IValuableNumber): Color; - export function fade(color: Color, amount: IValuableNumber): Color; - export function spin(color: Color, amount: IValuableNumber): Color; - export function mix(color1: Color, color2: Color, weight: Dimension): Color; - export function greyscale(color: Color): Color; - export function contrast(color: Color, dark?: Color, light?: Color, threshold?: IValuableNumber): Color; - export function contrast(color: Color, dark?: Color, light?: Color, threshold?: number): Color; - export function e(str: string): Anonymous; - export function e(str: JavaScript): Anonymous; - export function escape(str: IValuableString): Anonymous; - export function unit(val: IValuableNumber, unit?: ICSSable): Dimension; - export function round(n: Dimension, f?: IValuableNumber): Dimension; - export function round(n: number, f?: IValuableNumber): number; - export function ceil(n: number): number; - export function ceil(n: Dimension): Dimension; - export function floor(n: number): number; - export function floor(n: Dimension): Dimension; - export function argb(color: Color): Anonymous; - export function percentage(n: IValuableNumber): Dimension; - export function color(n: Quoted): Color; - export function iscolor(n): Keyword; - export function isnumber(n): Keyword; - export function isstring(n): Keyword; - export function iskeyword(n): Keyword; - export function isurl(n): Keyword; - export function ispixel(n): Keyword; - export function ispercentage(n): Keyword; - export function isem(n): Keyword; - export function multiply(color1: Color, color2: Color): Color; - export function screen(color1: Color, color2: Color): Color; - export function overlay(color1: Color, color2: Color): Color; - export function softlight(color1: Color, color2: Color): Color; - export function hardlight(color1: Color, color2: Color): Color; - export function difference(color1: Color, color2: Color): Color; - export function exclusion(color1: Color, color2: Color): Color; - export function average(color1: Color, color2: Color): Color; - export function negation(color1: Color, color2: Color): Color; - export function tint(color: Color, amount: Dimension): Color; - export function shade(color: Color, amount: Dimension): Color; - } - - export var colors: any; // Could be module - got lazy - - interface HasDebugInfo { - debugInfo: DebugInfo; - } - - interface DebugInfo { - lineNumber; - fileName: string; - } - - interface HSL { - h: number; - s: number; - l: number; - a: number; - } - - interface DebugInfoFunction { - (env: Options, ctx: HasDebugInfo): string; - asComment(ctx: HasDebugInfo): string; - asMediaQuery(ctx: HasDebugInfo): string; - } - - interface RuleContainer { - [name: string]: Rule; - } - - interface ICSSable { - toCSS(ctx?, env?: Options): string; - } - - interface IEvalable { - eval(env: Options): IEvalable; - } - - interface IInjectable extends ICSSable, IEvalable {} - - interface IOperable { - operate(op: Operation, other: IOperable): IOperable; - } - - interface IComparable { - compare(x: IComparable): number; - } - - interface IColorable { - toColor(): Color; - } - - interface IValuableNumber { - value: number; - } - - interface IValuableString { - value: string; - } - - export class Color implements IOperable, IInjectable, IComparable { - constructor(rgb: string, a: number); - constructor(rgb: number[], a: number); - - rgb: number[]; - alpha: number; - eval(): Color; - toCSS(): string; - operate(op: Operation, other: Color): Color; - operate(op: Operation, other: IColorable): Color; - toHSL(): HSL; - toARGB(): string; - compare(x: Color): number; - } - - export class Directive implements IInjectable { - constructor(name, value); - - name; - value: ICSSable; - ruleset: Ruleset; - - toCSS(ctx?, env?: Options): string; - eval(env: Options): Directive; - - variable(name); - find(); - rulesets(); - } - - export class Operation implements IEvalable { - constructor(op, operands); - - op: string; - operands: IEvalable; - - eval(env: Options): IEvalable; - - operate(op: string, a: number, b: number): number; - } - - export class Dimension implements IColorable, IInjectable, IOperable, IComparable { - constructor(value: number, unit: string); - - value: number; - unit: string; - - eval(): Dimension; - toColor(): Color; - toCSS(): string; - operate(op: Operation, other: Dimension): Dimension; - compare(other: IComparable): number; - } - - export class Keyword implements IInjectable, IComparable { - constructor(value: string); - - value: string; - - eval(): Keyword; - toCSS(): string; - compare(other: IComparable): number; - - static True: Keyword; - static False: Keyword; - } - - export class Variable implements IEvalable { - constructor(name: string, index, file: string); - - name: string; - index; - file: string; - - eval(env: Options): IEvalable; - } - - export class AbstractRuleset implements IEvalable { - selectors: Selector[]; - rules: any[]; - strictImports; - - eval(env: Options): Ruleset; - evalImports(env: Options): void; - makeImportant(): Ruleset; - matchArgs(args: any): boolean; - resetCache(): void; - variables(): RuleContainer; - variable(): Rule; - rulesets(): Ruleset[]; - find(selector: Selector, self: Rule): Rule[]; - joinSelectors(paths: string[], context: any[][], selectors: Selector[]): void; - joinSelector(paths: string[], context: any[][], selector: Selector): void; - mergeElementsOnToSelectors(elements: Element[], selectors: Selector[]): void; - } - - export class Ruleset extends AbstractRuleset { - constructor(selectors: Selector[], rules: Rule[], strictImports); - - toCSS(context?: any[][], env?: Options): string; - } - - export class Element implements IInjectable { - constructor(combinator: Combinator, value, index); - - combinator: Combinator; - value; - index; - - eval(env: Options): Element; - toCSS(env?: Options): string; - } - - export class Combinator implements ICSSable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - } - - export class Selector implements IInjectable { - constructor(elements: Element[]); - - match(other: Selector): boolean; - eval(env: Options): Selector; - toCSS(env?: Options): string; - } - - export class Quoted implements IInjectable, IComparable { - constructor(str: string, content: string, escaped: boolean, i); - - escaped: boolean; - value: string; - quote: string; - index; - - toCSS(): string; - eval(env: Options): Quoted; - compare(x: IComparable): number; - } - - export class Expression implements IInjectable { - constructor(value: IEvalable[]); - - value: IEvalable[]; - - eval(env: Options): IEvalable; - toCSS(env?: Options): string; - } - - export class Rule implements IInjectable { - constructor(name: string, value?: Value, important?: string, index?, inline?: boolean); - - name: string; - value: Value; - important: string; - index; - inline: boolean; - - toCSS(env?: Options): string; - eval(context): Rule; - - makeImportant(): Rule; - } - - export class Shorthand implements IInjectable { - constructor(a: ICSSable, b: ICSSable); - - a: ICSSable; - b: ICSSable; - - toCSS(env?: Options): string; - eval(): Shorthand; - } - - export class Call implements IInjectable { - constructor(name: string, args: IEvalable[], index, filename: string); - - name: string; - args: IEvalable[]; - index; - filename: string; - - eval(env: Options): IEvalable; - toCSS(env?: Options): string; - } - - export class URL implements IInjectable { - constructor(val, rootpath: string); - - value; - rootpath: string; - - toCSS(): string; - eval(ctx): URL; - } - - export class Alpha implements IInjectable { - constructor(val); - - value; - - toCSS(): string; - eval(env: Options): Alpha; - } - - export class Import implements IInjectable { - constructor(path, imports, features: ICSSable, once: boolean, index, rootpath); - - once: boolean; - index; - features: ICSSable; - rootpath; - path: string; - css: boolean; - - toCSS(env?: Options): string; - eval(env: Options): IEvalable; - } - - export class Comment implements IInjectable { - constructor(value: string, silent); - - value: string; - silent: boolean; - - toCSS(env?: Options): string; - eval(): Comment; - } - - export class Anonymous implements IInjectable, IComparable { - constructor(value: string); - - value: string; - - toCSS(): string; - eval(): Anonymous; - compare(x): number; - } - - export class Value implements IInjectable { - constructor(value: IEvalable[]); - - value: IEvalable[]; - is: string; - - eval(env: Options): IEvalable; - toCSS(env?: Options): string; - } - - export class JavaScript implements IEvalable { - constructor(expression: string, index, escaped: boolean); - - escaped: boolean; - expression: string; - index; - - eval(env: Options): IEvalable; - } - - export class Assignment implements IInjectable { - constructor(key: string, val); - constructor(key: string, val: ICSSable); - constructor(key: string, val: IEvalable); - - key: string; - value; - - toCSS(): string; - eval(env: Options): Assignment; - } - - export class Condition { - constructor(op: string, l, r, i, negate: boolean); - - op: string; - lvalue; - rvalue; - index; - negate: boolean; - - eval(env: Options): boolean; - } - - export class Paren implements IInjectable { - constructor(node: IInjectable); - value: IInjectable; - - toCSS(env?: Options): string; - eval(env: Options): Paren; - } - - export class Media implements IInjectable { - constructor(value, features); - - selectors: Selector[]; - features: Value; - ruleset: Ruleset; - - toCSS(ctx?, env?: Options): string; - eval(env: Options): IEvalable; - - variable(name): Rule; - rulesets(): Ruleset[]; - find(selector: Selector, self: Rule): Rule[]; - - emptySelectors(): Selector[]; - evalTop(env: Options): IEvalable; - evalNested(env: Options): Ruleset; - permute(arr: any[]): any[]; - bubbleSelectors(selectors: Selector[]): void; - } - - export class Ratio implements IInjectable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - eval(): Ratio; - } - - export class UnicodeDescriptor implements IInjectable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - eval(): UnicodeDescriptor; - } - - export class Attribute implements IInjectable { - constructor(value: string); - - value: string; - - toCSS(env?: Options): string; - genCSS(env: Options, output): string; - eval(): Attribute; - } - - export var debugInfo: DebugInfoFunction; - export function find(obj: any[], fun: Function): any; - export function jsify(obj: any): string; - export function operate(op: string, a: number, b: number): number; - - export var True: Keyword; - export var False: Keyword; + interface RenderOutput { + css: string; + map: string; + imports: string[]; } +} - class ParserNode extends tree.AbstractRuleset { - toCSS(): string; - toCSS(options: { compress: boolean; }, variables?): string; - } +interface LessStatic { + render(input: string, callback: (output: Less.RenderOutput) => void): void; + render(input: string, options: Less.Options, callback: (output: Less.RenderOutput) => void): void; - export class Parser { - constructor(env?: Options); + render(input: string): Less.Promise; + render(input: string, options: Less.Options): Less.Promise; - imports: { - paths: string[]; - queue: string[]; - files; - contents; - mime: string; - error; - push(path: string, callback: (e, root, imported) => void); - }; // TODO - - parse: (str: string, callback: (error: LessError, root: ParserNode) => void ) => void; - - parsers: { // Major TODO - }; - } - - export function render(input: string, callback: (e, css: string) => void): void; - export function render(input: string, options: Options, - callback: (e, css: string) => void): void; - - export function formatError(ctx, options: { color: boolean; }): string; - export function writeError(ctx, options: { color: boolean; }): void; - - export var version: number[]; + version: number[]; } declare module "less" { - export = less; + export = less; } + +declare var less: LessStatic; diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 6f24b75dcd..46c11ebf6f 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -565,6 +565,8 @@ result = _.sample([1, 2, 3, 4]); result = _.sample([1, 2, 3, 4], 2); result = _.shuffle([1, 2, 3, 4, 5, 6]); +result = <_.LoDashArrayWrapper>_([1, 2, 3]).shuffle(); +result = <_.LoDashArrayWrapper<_.Dictionary>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).shuffle(); result = _.size([1, 2]); result = _.size({ 'one': 1, 'two': 2, 'three': 3 }); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c43f27c5c1..55d35707fb 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -4398,6 +4398,20 @@ declare module _ { shuffle(collection: Dictionary): T[]; } + interface LoDashArrayWrapper { + /** + * @see _.shuffle + **/ + shuffle(): LoDashArrayWrapper; + } + + interface LoDashObjectWrapper { + /** + * @see _.shuffle + **/ + shuffle(): LoDashArrayWrapper; + } + //_.size interface LoDashStatic { /** @@ -5731,6 +5745,18 @@ declare module _ { **/ isEmpty(value: any): boolean; } + + //_.isError + interface LoDashStatic { + /** + * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, + * or URIError object. + * @param value The value to check. + * @return True if value is an error object, else false. + */ + isError(value: any): boolean; + } + //_.isEqual interface LoDashStatic { diff --git a/loggly/loggly-tests.ts b/loggly/loggly-tests.ts new file mode 100644 index 0000000000..bf022999fb --- /dev/null +++ b/loggly/loggly-tests.ts @@ -0,0 +1,12 @@ +/// +import loggly = require("loggly"); + +var options: loggly.LogglyOptions = { + token: "YOUR_TOKEN", + subdomain: "YOUR_DOMAIN", + tags: ["NodeJS"], + json: true +}; + +var client: loggly.Loggly = loggly.createClient(options) +client.log('hello world'); diff --git a/loggly/loggly-tests.ts.tscparams b/loggly/loggly-tests.ts.tscparams new file mode 100644 index 0000000000..5f84b97777 --- /dev/null +++ b/loggly/loggly-tests.ts.tscparams @@ -0,0 +1 @@ +--noImplicitAny --module commonjs --target es5 diff --git a/loggly/loggly.d.ts b/loggly/loggly.d.ts new file mode 100644 index 0000000000..40724f8558 --- /dev/null +++ b/loggly/loggly.d.ts @@ -0,0 +1,25 @@ +// Type definitions for loggly 1.0.8 +// Project: https://github.com/nodejitsu/node-loggly +// Definitions by: Ray Martone +// Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module "loggly" { + + interface LogglyOptions { + token: string; + subdomain: string; + tags?: string[]; + json?: boolean; + host?: string; + auth?: { + username: string; + password: string; + } + } + + interface Loggly { + log(message: any, tags?: string[], callback?: (err: any, results: any) => void): void; + log(message: any, callback?: (err: any, results: any) => void): void; + } + + function createClient(options: LogglyOptions): Loggly; +} diff --git a/mariasql/mariasql-tests.ts b/mariasql/mariasql-tests.ts index 554d3d4a76..c9173058ca 100644 --- a/mariasql/mariasql-tests.ts +++ b/mariasql/mariasql-tests.ts @@ -7,7 +7,7 @@ import util = require('util'); import Client = require('mariasql'); -var c:Client = new Client(), +var c:mariasql.MariaClient = new Client(), inspect = util.inspect; c.connect({ diff --git a/mariasql/mariasql.d.ts b/mariasql/mariasql.d.ts index 2c375a1731..05d7fa0621 100644 --- a/mariasql/mariasql.d.ts +++ b/mariasql/mariasql.d.ts @@ -3,95 +3,100 @@ // Definitions by: MichaelBennett // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module mariasql { + export interface MariaCallBackError { + (error:Error):void + } -/** - */ -interface MariaCallBackError { - (error:Error):void -} - -interface MariaCallBackResult { - (result:MariaResult):void -} - -interface MariaCallBackRow { - (result:Array):void -} - -interface MariaCallBackBoolean { - (result:boolean):void -} - -interface MariaCallBackObject { - (result:Object):void -} - -interface MariaCallBackVoid { - ():void -} - -interface Dictionary { - [index: string]: any; -} - -interface MariaPreparedQuery { - (values:Dictionary):string; - (values:Array):string; -} - -interface ClientConfig { - host: string; - user: string; - password: string; - db?: string; - port?: number; - unixSocket?: string; - keepQueries?: boolean; - multiStatements?: boolean; - connTimeout?: number; - pingInterval?: number; - secureAuth?: boolean; - compress?: boolean; - ssl?:any; - local_infile?: boolean; - read_default_group?: string; - charset?: string; -} - -declare class MariaResult { - on(signal:string, cb:MariaCallBackObject):MariaResult; // signal 'end' - on(signal:string, cb:MariaCallBackError):MariaResult; // signal 'error' - on(signal:string, cb:MariaCallBackRow):MariaResult; // signal 'row' - on(signal:string, cb:MariaCallBackVoid):MariaResult; // signal 'abort' - abort():void; -} - -declare class MariaQuery { - on(signal:string, cb:MariaCallBackResult):MariaQuery; // signal 'result' - on(signal:string, cb:MariaCallBackVoid):MariaQuery; // signal 'end' - on(signal:string, cb:MariaCallBackVoid):MariaQuery; // signal 'abort' - on(signal:string, cb:MariaCallBackError):MariaQuery; // signal 'error' - abort():void; -} - -declare class MariaClient { - connect(config:ClientConfig):void; - end():void; - destroy():void; - escape(query:string):string; - query(q:string, placeHolders?:Dictionary, useArray?:boolean):MariaQuery; - query(q:string, placeHolders?:Array, useArray?:boolean):MariaQuery; - query(q:string, useArray?:boolean):MariaQuery; - prepare(query:string): MariaPreparedQuery; - isMariaDB():boolean; - on(signal:string, cb:MariaCallBackError): MariaClient; // signal 'error' - on(signal:string, cb:MariaCallBackObject): MariaClient; // signal 'close' - on(signal:string, cb:MariaCallBackVoid): MariaClient; // signal 'connect' - connected: boolean; - threadId: string; -} - -declare module 'mariasql' { - export = MariaClient; + export interface MariaCallBackResult { + (result:MariaResult):void + } + + export interface MariaCallBackRow { + (result:Array):void + } + + export interface MariaCallBackBoolean { + (result:boolean):void + } + + export interface MariaCallBackObject { + (result:Object):void + } + + export interface MariaCallBackVoid { + ():void + } + + export interface Dictionary { + [index: string]: any; + } + + export interface MariaPreparedQuery { + (values:Dictionary):string; + (values:Array):string; + } + + export interface ClientConfig { + host: string; + user: string; + password: string; + db?: string; + port?: number; + unixSocket?: string; + keepQueries?: boolean; + multiStatements?: boolean; + connTimeout?: number; + pingInterval?: number; + secureAuth?: boolean; + compress?: boolean; + ssl?:any; + local_infile?: boolean; + read_default_group?: string; + charset?: string; + } + + export interface MariaResult { + on(signal:string, cb:MariaCallBackObject):MariaResult; // signal 'end' + on(signal:string, cb:MariaCallBackError):MariaResult; // signal 'error' + on(signal:string, cb:MariaCallBackRow):MariaResult; // signal 'row' + on(signal:string, cb:MariaCallBackVoid):MariaResult; // signal 'abort' + abort():void; + } + + export interface MariaQuery { + on(signal:string, cb:MariaCallBackResult):MariaQuery; // signal 'result' + on(signal:string, cb:MariaCallBackVoid):MariaQuery; // signal 'end' + on(signal:string, cb:MariaCallBackVoid):MariaQuery; // signal 'abort' + on(signal:string, cb:MariaCallBackError):MariaQuery; // signal 'error' + abort():void; + } + + export interface MariaClient { + connect(config:ClientConfig):void; + end():void; + destroy():void; + escape(query:string):string; + query(q:string, placeHolders?:Dictionary, useArray?:boolean):MariaQuery; + query(q:string, placeHolders?:Array, useArray?:boolean):MariaQuery; + query(q:string, useArray?:boolean):MariaQuery; + prepare(query:string): MariaPreparedQuery; + isMariaDB():boolean; + on(signal:string, cb:MariaCallBackError): MariaClient; // signal 'error' + on(signal:string, cb:MariaCallBackObject): MariaClient; // signal 'close' + on(signal:string, cb:MariaCallBackVoid): MariaClient; // signal 'connect' + connected: boolean; + threadId: string; + } + + export interface Client { + new ():MariaClient; + ():MariaClient; + prototype: MariaClient; + } } +declare module "mariasql" { + var Client:mariasql.Client; + export = Client; +} \ No newline at end of file diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index ee528b6666..2b9b25635f 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -38,7 +38,7 @@ declare module Backbone { include(value: any): boolean; initial(): View; initial(n: number): View[]; - invoke(methodName: string, arguments?: any[]): any; + invoke(methodName: string, args?: any[]): any; isEmpty(object: any): boolean; last(): View; last(n: number): View[]; @@ -533,7 +533,7 @@ declare module Marionette { * Calls the method named by methodName on each value in the collection. Any extra * arguments passed to invoke will be forwarded on to the method invocation. */ - invoke(methodName: string, arguments?: any[]): any; + invoke(methodName: string, args?: any[]): any; /** * Returns true if the RegionManager contains no regions. diff --git a/meteor/README.md b/meteor/README.md index ae8178f2ce..8f93e1816e 100644 --- a/meteor/README.md +++ b/meteor/README.md @@ -1,6 +1,6 @@ # Meteor Type Definitions -These are the definitions for version 1.0.3.1 of Meteor. +These are the definitions for version 1.1.0.1 of Meteor. Although these definitions can be downloaded separately for use, the recommended way to use these definitions in a Meteor application is by installing the [typescript-libs](https://atmospherejs.com/meteortypescript/typescript-libs) Meteor smart package from atmosphere. The smart package contains TypeScript @@ -16,25 +16,21 @@ to generate the official [Meteor docs] (http://docs.meteor.com/). ## Usage -1. If you are using the smart package, add a symbolic link to the definitions from within some directory within your project (e.g. ".typescript" or "lib"). The -definitions can be found somewhere deep within `/.meteor/...`. The following will probably work: +1. Add a symbolic link to the definitions from within some directory within your project (e.g. ".typescript" or "lib"). The definitions can be found somewhere +deep within `/.meteor/...`. The following will probably work: $ ln -s ../.meteor/local/build/programs/server/assets/packages/meteortypescript_typescript-libs/definitions package_defs - If the definitions can't be found within the .meteor directory, you will have to manually pull down the definitions from github and add them to your project: - If you are just using the *meteor.d.ts* file from this source, you can just add the file to any directory in your project (e.g. ".typescript" or "lib"). - 2. Install the [Typescript compiler for Meteor](https://github.com/meteor-typescript/meteor-typescript-compiler) or an [IDE which can transpile TypeScript to JavaScript](#transpiling-typescript). 3. From the typescript files, add references. Reference the definition files with a single line: /// (substitute path in your project) - Or you can reference definition files individually: - + /// (substitue path in your project) /// /// @@ -46,26 +42,28 @@ definitions can be found somewhere deep within `/.meteor/...`. ### References -Try to stay away from referencing *file.ts*, rather generate a *file.d.ts* using `tsc --reference file.ts`, and reference it in your file. Compilation will -be much faster and code cleaner - it's always better to split definition from implemention. +Meteor code can run on the client and the server, for this reason you should try to stay away from referencing *file.ts* directly: you may get unexpected results. +Rather generate a *file.d.ts* using `tsc --reference file.ts`, and reference it in your file. + +Compilation will be much faster and code cleaner - it's always better to split definition from implementation anyways. ### Templates -When specifying template *helpers*, *events*, and functions for *created*, *rendered*, and *destroyed*, you will need to use a "bracket notation" instead of the "dot notation": +With the exception of the **body** and **head** templates, Meteor's Template dot notation cannot be used (ie. *Template.mytemplate*). Thanks to Typescript static typing checks, you will need to used the *bracket notation* to access the Template. - Template['myTemplateName']['helpers']({ + + Template['myTemplateName'].helpers({ foo: function () { return Session.get("foo"); } }); - Template['myTemplateName']['rendered'] = function ( ) { ... } + Template['myTemplateName'].rendered = function ( ) { ... } + -This is because TypeScript enforces typing and it will throw an error saying "myTemplateName" does not exist when using the dot notation. +### Form fields -### Accessing a Form field - -Trying to read a form field value? use `(evt.target).value`. +Form fields typically need to be casted to . For instance to read a form field value, use `(evt.target).value`. ### Global variables @@ -77,7 +75,7 @@ Preface any global variable declarations with a TypeScript "declare var" stateme ### Collections -The majority of extra work required to use TypeScript with Meteor is creating and maintaining the collection interfaces. However, doing so also provides the +The majority of extra work required to use TypeScript with Meteor is creating and maintaining the collection interfaces. However, doing so also provides the additional benefit of succinctly documenting collection schema definitions (that are actually enforced). To define collections, you will need to create an interface representing the collection and then declare a Collection type variable with that interface type (as a generic): @@ -113,7 +111,7 @@ for all of you custom definitions. e.g. contents of ".typescript/custom_defs/cu /// /// /// - + ## Transpiling TypeScript @@ -132,4 +130,4 @@ Then, within WebStorm, go to Preferences -> File Watchers -> "+" symbol and add Last option, is to compile code from the command line. With node and the typescript compiler installed: - $ tsc *.ts \ No newline at end of file + $ tsc *.ts diff --git a/meteor/meteor-tests.ts b/meteor/meteor-tests.ts index e4c5b90667..ec2ad3b817 100644 --- a/meteor/meteor-tests.ts +++ b/meteor/meteor-tests.ts @@ -8,21 +8,15 @@ /*********************************** Begin setup for tests ******************************/ - -// A developer must declare a var Template like this in a separate file to use this TypeScript type definition file -//interface ITemplate { -// adminDashboard: Meteor.Template; -// chat: Meteor.Template; -//} -//declare var Template: ITemplate; - var Rooms = new Mongo.Collection('rooms'); var Messages = new Mongo.Collection('messages'); -var Monkeys = new Mongo.Collection('monkeys'); -var x = new Mongo.Collection('x'); -var y = new Mongo.Collection('y'); - -var check = function(str1, str2) {}; +interface MonkeyDAO { + _id: string; + name: string; +} +var Monkeys = new Mongo.Collection('monkeys'); +//var x = new Mongo.Collection('x'); +//var y = new Mongo.Collection('y'); /********************************** End setup for tests *********************************/ @@ -98,8 +92,8 @@ Tracker.autorun(function () { }); console.log("Current room has " + - Counts.find(Session.get("roomId")).count + - " messages."); +Counts.find(Session.get("roomId")).count + +" messages."); /** * From Publish and Subscribe, Meteor.subscribe section @@ -124,7 +118,7 @@ Meteor.methods({ var you_want_to_throw_an_error = true; if (you_want_to_throw_an_error) - throw new Meteor.Error("404", "Can't find my pants"); + throw new Meteor.Error("404", "Can't find my pants"); return "some return value"; }, @@ -146,15 +140,15 @@ var result = Meteor.call('foo', 1, 2); // DA: I added the "var" keyword in there interface ChatroomsDAO { - _id?: string; + _id?: string; } interface MessagesDAO { - _id?: string; + _id?: string; } var Chatrooms = new Mongo.Collection("chatrooms"); Messages = new Mongo.Collection("messages"); -var myMessages = Messages.find({userId: Session.get('myUserId')}).fetch(); +var myMessages = Messages.find({userId: Session.get('myUserId')}).fetch(); Messages.insert({text: "Hello, world!"}); @@ -171,10 +165,10 @@ Posts.insert({title: "Hello world", body: "First post"}); * since there is already a Collection constructor with a different signature * var Scratchpad = new Mongo.Collection; -for (var i = 0; i < 10; i++) - Scratchpad.insert({number: i * 2}); -assert(Scratchpad.find({number: {$lt: 9}}).count() === 5); -**/ + for (var i = 0; i < 10; i++) + Scratchpad.insert({number: i * 2}); + assert(Scratchpad.find({number: {$lt: 9}}).count() === 5); + **/ var Animal = function (doc) { // _.extend(this, doc); @@ -185,11 +179,16 @@ Animal.prototype = { makeNoise: function () { console.log(this.sound); } +}; + + +interface AnimalDAO { + _id: string; + makeNoise: () => void; } - // Define a Collection that uses Animal as its document -var Animals = new Mongo.Collection("Animals", { +var Animals = new Mongo.Collection("Animals", { transform: function (doc) { return new Animal(doc); } }); @@ -225,8 +224,8 @@ Template['adminDashboard'].events({ Meteor.methods({ declareWinners: function () { Players.update({score: {$gt: 10}}, - {$addToSet: {badges: "Winner"}}, - {multi: true}); + {$addToSet: {badges: "Winner"}}, + {multi: true}); } }); @@ -348,7 +347,7 @@ Session.equals("key", value); */ Meteor.publish("userData", function () { return Meteor.users.find({_id: this.userId}, - {fields: {'other': 1, 'things': 1}}); + {fields: {'other': 1, 'things': 1}}); }); Meteor.users.deny({update: function () { return true; }}); @@ -412,8 +411,8 @@ Accounts.emailTemplates.enrollAccount.subject = function (user) { }; Accounts.emailTemplates.enrollAccount.text = function (user, url) { return "You have been selected to participate in building a better future!" - + " To activate your account, simply click the link below:\n\n" - + url; + + " To activate your account, simply click the link below:\n\n" + + url; }; /** @@ -424,6 +423,36 @@ Template['adminDashboard'].helpers({ return Session.get("foo"); } }); +Template['newTemplate'].helpers({ + helperName: function () { + } +}); + +Template['newTemplate'].created = function () { + +}; + +Template['newTemplate'].rendered = function () { + +}; + +Template['newTemplate'].destroyed = function () { + +}; + +Template['newTemplate'].events({ + 'click .something': function (event) { + } +}); + +Template.registerHelper('testHelper', function() { + return 'tester'; +}); + +var instance = Template.instance(); +var data = Template.currentData(); +var data = Template.parentData(1); +var body = Template.body; /** * From Match section @@ -481,10 +510,9 @@ Tracker.autorun(function (c) { * From Deps, Deps.Computation */ if (Tracker.active) { - Tracker.onInvalidate(function () { - x.destroy(); - y.finalize(); - }); + Tracker.onInvalidate(function () { + console.log('invalidated'); + }); } /** @@ -494,15 +522,15 @@ var weather = "sunny"; var weatherDep = new Tracker.Dependency; var getWeather = function () { - weatherDep.depend(); - return weather; + weatherDep.depend(); + return weather; }; var setWeather = function (w) { - weather = w; - // (could add logic here to only call changed() - // if the new value is different from the old) - weatherDep.changed(); + weather = w; + // (could add logic here to only call changed() + // if the new value is different from the old) + weatherDep.changed(); }; /** @@ -512,7 +540,7 @@ Meteor.methods({checkTwitter: function (userId) { check(userId, String); this.unblock(); var result = HTTP.call("GET", "http://api.twitter.com/xyz", - {params: {user: userId}}); + {params: {user: userId}}); if (result.statusCode === 200) return true return false; @@ -520,12 +548,12 @@ Meteor.methods({checkTwitter: function (userId) { HTTP.call("POST", "http://api.twitter.com/xyz", - {data: {some: "json", stuff: 1}}, - function (error, result) { - if (result.statusCode === 200) { - Session.set("twizzled", true); - } - }); + {data: {some: "json", stuff: 1}}, + function (error, result) { + if (result.statusCode === 200) { + Session.set("twizzled", true); + } + }); /** * From Email, Email.send section @@ -542,9 +570,9 @@ Meteor.methods({ // In your client code: asynchronously send an email Meteor.call('sendEmail', - 'alice@example.com', - 'Hello from Meteor!', - 'This is a test of Email.send.'); + 'alice@example.com', + 'Hello from Meteor!', + 'This is a test of Email.send.'); var testTemplate = new Blaze.Template(); var testView = new Blaze.View(); @@ -562,8 +590,8 @@ Blaze.toHTMLWithData(testTemplate, function() {}); Blaze.toHTMLWithData(testView, {test: 1}); Blaze.toHTMLWithData(testView, function() {}); -var reactiveVar1 = new ReactiveVar('test value'); -var reactiveVar2 = new ReactiveVar('test value', function(oldVal) { return true; }); +var reactiveVar1 = new ReactiveVar('test value'); +var reactiveVar2 = new ReactiveVar('test value', function(oldVal) { return true; }); var varValue: string = reactiveVar1.get(); reactiveVar1.set('new value'); \ No newline at end of file diff --git a/meteor/meteor.d.ts b/meteor/meteor.d.ts index e645470966..4118fbe062 100644 --- a/meteor/meteor.d.ts +++ b/meteor/meteor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Meteor 1.0.3.1 +// Type definitions for Meteor 1.1.0.1 // Project: http://www.meteor.com/ // Definitions by: Dave Allen // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,344 +7,419 @@ * These are the modules and interfaces that can't be automatically generated from the Meteor data.js file */ -interface EJSON extends JSON {} -interface TemplateStatic { - new(): Template; - [templateName: string]: Meteor.TemplatePage; +interface EJSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSON.CustomType; } +interface JSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; +} +interface EJSON extends EJSONable {} declare module Match { - var Any; - var String; - var Integer; - var Boolean; - var undefined; - //function null(); // not allowed in TypeScript - var Object; - function Optional(pattern):boolean; - function ObjectIncluding(dico):boolean; - function OneOf(...patterns); - function Where(condition); + var Any; + var String; + var Integer; + var Boolean; + var undefined; + //function null(); // not allowed in TypeScript + var Object; + function Optional(pattern):boolean; + function ObjectIncluding(dico):boolean; + function OneOf(...patterns); + function Where(condition); } declare module Meteor { - //interface EJSONObject extends Object {} + /** Start definitions for Template **/ + interface Event { + type:string; + target:HTMLElement; + currentTarget:HTMLElement; + which: number; + stopPropagation():void; + stopImmediatePropagation():void; + preventDefault():void; + isPropagationStopped():boolean; + isImmediatePropagationStopped():boolean; + isDefaultPrevented():boolean; + } - /** Start definitions for Template **/ - // DA: "Template" needs to support these functions: - // Template..rendered - // Template..created - // Template..destroyed - // Template..helpers - // Template..events - // and - // Template.currentData - // Template.parentData, etc. + interface EventHandlerFunction extends Function { + (event?:Meteor.Event):void; + } - interface Event { - type:string; - target:HTMLElement; - currentTarget:HTMLElement; - which: number; - stopPropagation():void; - stopImmediatePropagation():void; - preventDefault():void; - isPropagationStopped():boolean; - isImmediatePropagationStopped():boolean; - isDefaultPrevented():boolean; - } + interface EventMap { + [id:string]:Meteor.EventHandlerFunction; + } + /** End definitions for Template **/ - interface EventHandlerFunction extends Function { - (event?:Meteor.Event):any; - } + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + userEmail?: string; + loginStyle?: string; + } - interface EventMap { - [id:string]:Meteor.EventHandlerFunction; - } + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - interface TemplatePage { - rendered: Function; - created: Function; - destroyed: Function; - events(eventMap:Meteor.EventMap): void; - helpers(helpers:{[id:string]: any}): void; - } - /** End definitions for Template **/ + interface UserEmail { + address:string; + verified:boolean; + } - interface LoginWithExternalServiceOptions { - requestPermissions?: string[]; - requestOfflineToken?: Boolean; - forceApprovalPrompt?: Boolean; - userEmail?: string; - loginStyle?: string; - } + interface User { + _id?:string; + username?:string; + emails?:Meteor.UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } - function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } - interface UserEmail { - address:string; - verified:boolean; - } + interface Tinytest { + add(name:string, func:Function); + addAsync(name:string, func:Function); + } - interface User { - _id?:string; - username?:string; - emails?:Meteor.UserEmail[]; - createdAt?: number; - profile?: any; - services?: any; - } + enum StatusEnum { + connected, + connecting, + failed, + waiting, + offline + } - interface SubscriptionHandle { - stop(): void; - ready(): boolean; - } + interface LiveQueryHandle { + stop(): void; + } - interface Tinytest { - add(name:string, func:Function); - addAsync(name:string, func:Function); - } + interface EmailFields { + subject?: Function; + text?: Function; + } - enum StatusEnum { - connected, - connecting, - failed, - waiting, - offline - } + interface EmailTemplates { + from: string; + siteName: string; + resetPassword: Meteor.EmailFields; + enrollAccount: Meteor.EmailFields; + verifyEmail: Meteor.EmailFields; + } - interface LiveQueryHandle { - stop(): void; - } + interface Error { + error: number; + reason?: string; + details?: string; + } - interface EmailFields { - subject?: Function; - text?: Function; - } - - interface EmailTemplates { - from: string; - siteName: string; - resetPassword: Meteor.EmailFields; - enrollAccount: Meteor.EmailFields; - verifyEmail: Meteor.EmailFields; - } - - interface Error { - error: number; - reason?: string; - details?: string; - } - - interface Connection { - id: string; - close: Function; - onClose: Function; - clientAddress: string; - httpHeaders: Object; - } + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } } declare module Mongo { - interface Selector extends Object {} - interface Modifier {} - interface SortSpecifier {} - interface FieldSpecifier { - [id: string]: Number; - } - enum IdGenerationEnum { - STRING, - MONGO - } - interface AllowDenyOptions { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; - fetch?: string[]; - transform?: Function; - } + interface Selector extends Object {} + interface Modifier {} + interface SortSpecifier {} + interface FieldSpecifier { + [id: string]: Number; + } + enum IdGenerationEnum { + STRING, + MONGO + } + interface AllowDenyOptions { + insert?: (userId:string, doc) => boolean; + update?: (userId, doc, fieldNames, modifier) => boolean; + remove?: (userId, doc) => boolean; + fetch?: string[]; + transform?: Function; + } } declare module HTTP { - interface HTTPRequest { - content?:string; - data?:any; - query?:string; - params?:{[id:string]:string}; - auth?:string; - headers?:{[id:string]:string}; - timeout?:number; - followRedirects?:boolean; - } - interface HTTPResponse { - statusCode:number; - content:string; - // response is not always json - data:any; - headers:{[id:string]:string}; - } + interface HTTPRequest { + content?:string; + data?:any; + query?:string; + params?:{[id:string]:string}; + auth?:string; + headers?:{[id:string]:string}; + timeout?:number; + followRedirects?:boolean; + } + + interface HTTPResponse { + statusCode?:number; + headers?:{[id:string]: string}; + content?:string; + data?:any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?:Function):HTTP.HTTPResponse; + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + } 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[] - subject: string; - text?: string; - html?: string; - headers?: {[id: string]: string}; - } + interface EmailMessage { + from: string; + to: any; // string or string[] + cc?: any; // string or string[] + bcc?: any; // string or string[] + replyTo?: any; // string or string[] + subject: string; + text?: string; + html?: string; + headers?: {[id: string]: string}; + } } declare module DDP { - interface DDPStatic { - subscribe(name, ...rest); - call(method:string, ...parameters):void; - apply(method:string, ...parameters):void; - methods(IMeteorMethodsDictionary); - status():DDPStatus; - reconnect(); - disconnect(); - onReconnect(); - } + interface DDPStatic { + subscribe(name, ...rest); + call(method:string, ...parameters):void; + apply(method:string, ...parameters):void; + methods(IMeteorMethodsDictionary); + status():DDPStatus; + reconnect(); + disconnect(); + onReconnect(); + } - interface DDPStatus { - connected: boolean; - status: Meteor.StatusEnum; - retryCount: number; - //To turn this into an interval until the next reconnection, use retryTime - (new Date()).getTime() - retryTime?: number; - reason?: string; - } + interface DDPStatus { + connected: boolean; + status: Meteor.StatusEnum; + retryCount: number; + //To turn this into an interval until the next reconnection, use retryTime - (new Date()).getTime() + retryTime?: number; + reason?: string; + } } declare module Random { - function id(numberOfChars?: number): string; - function secret(numberOfChars?: number): string; - function fraction():number; - function hexString(numberOfDigits:number):string; // @param numberOfDigits, @returns a random hex string of the given length - function choice(array:any[]):string; // @param array, @return a random element in array - function choice(str:string):string; // @param str, @return a random char in str + function id(numberOfChars?: number): string; + function secret(numberOfChars?: number): string; + function fraction():number; + function hexString(numberOfDigits:number):string; // @param numberOfDigits, @returns a random hex string of the given length + function choice(array:any[]):string; // @param array, @return a random element in array + function choice(str:string):string; // @param str, @return a random char in str } declare module Blaze { - interface View { - name: string; - parentView: Blaze.View; - isCreated: boolean; - isRendered: boolean; - isDestroyed: boolean; - renderCount: number; - autorun(runFunc: Function): void; - onViewCreated(func: Function): void; - onViewReady(func: Function): void; - onViewDestroyed(func: Function): void; - firstNode(): Node; - lastNode(): Node; - template: Blaze.Template; - templateInstance(): any; - } - interface Template { - viewName: string; - renderFunction: Function; - constructView(): Blaze.View; - } + interface View { + name: string; + parentView: Blaze.View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: Function): void; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Blaze.Template; + templateInstance(): any; + } + interface Template { + viewName: string; + renderFunction: Function; + constructView(): Blaze.View; + } } +declare module BrowserPolicy { + + interface framing { + disallow():void; + restrictToOrigin(origin:string):void; + allowAll():void; + } + interface content { + allowEval():void; + allowInlineStyles():void; + allowInlineScripts():void; + allowSameOriginForAll():void; + allowDataUrlForAll():void; + allowOriginForAll(origin:string):void; + allowImageOrigin(origin:string):void; + allowFrameOrigin(origin:string):void; + allowContentTypeSniffing():void; + allowAllContentOrigin():void; + allowAllContentDataUrl():void; + allowAllContentSameOrigin():void; + + disallowAll():void; + disallowInlineStyles():void; + disallowEval():void; + disallowInlineScripts():void; + disallowFont():void; + disallowObject():void; + disallowAllContent():void; + //TODO: add the basic content types + // allowOrigin(origin) + // allowDataUrl() + // allowSameOrigin() + // disallow() + } +} + +declare module Tracker { + export var ComputationFunction: (computation: Tracker.Computation) => void; + +} + +declare var IterationCallback: (doc: T, index: number, cursor: Mongo.Cursor) => void; + /** * These modules and interfaces are automatically generated from the Meteor api.js file */ declare module Accounts { - var ui: { - config(options: { - requestPermissions?: Object; - requestOfflineToken?: Object; - forceApprovalPrompt?: Object; - passwordSignupFields?: string; - }): void; - }; - var emailTemplates: Meteor.EmailTemplates; + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; function config(options: { - sendVerificationEmail?: boolean; - forbidClientAccountCreation?: Boolean; - restrictCreationByEmailDomain?: string | Function; - loginExpirationInDays?: number; - oauthSecretKey?: string; - }): void; - function validateLoginAttempt(func: Function): {stop: Function}; - function onLogin(func: Function): {stop: Function}; - function onLoginFailure(func: Function): {stop: Function}; + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + }): void; + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + var emailTemplates: Meteor.EmailTemplates; + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; function onCreateUser(func: Function): void; - function validateNewUser(func: Function): void; - function onResetPasswordLink(callback: Function): void; function onEmailVerificationLink(callback: Function): void; function onEnrollmentLink(callback: Function): void; - function createUser(options: { - username?: string; - email?: string; - password?: string; - profile?: Object; - }, callback?: Function): string; - function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; - function forgotPassword(options: { - email?: string; - }, callback?: Function): void; + function onLogin(func: Function): {stop: Function}; + function onLoginFailure(func: Function): {stop: Function}; + function onResetPasswordLink(callback: Function): void; function resetPassword(token: string, newPassword: string, callback?: Function): void; - function verifyEmail(token: string, callback?: Function): void; - function setPassword(userId: string, newPassword: string): void; - function sendResetPasswordEmail(userId: string, email?: string): void; function sendEnrollmentEmail(userId: string, email?: string): void; + function sendResetPasswordEmail(userId: string, email?: string): void; function sendVerificationEmail(userId: string, email?: string): void; + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; + function validateLoginAttempt(func: Function): {stop: Function}; + function validateNewUser(func: Function): void; + function verifyEmail(token: string, callback?: Function): void; +} + +declare module App { + function accessRule(domainRule: string, options?: { + launchExternal?: boolean; + }); /** TODO: add return value **/ +function configurePlugin(pluginName: string, config: Object): void; + function icons(icons: Object): void; + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + function launchScreens(launchScreens: Object): void; + function setPreference(name: string, value: string): void; +} + +declare module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + function getText(assetPath: string, asyncCallback?: Function): string; } declare module Blaze { - var currentView: Blaze.View; - function With(data: Object | Function, contentFunc: Function): Blaze.View; - function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function isTemplate(value: any): boolean; - function render(templateOrView: Template | Blaze.View, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function renderWithData(templateOrView: Template | Blaze.View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function remove(renderedView: Blaze.View): void; - function toHTML(templateOrView: Template | Blaze.View): string; - function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string; - function getData(elementOrView?: HTMLElement | Blaze.View): Object; - function getView(element?: HTMLElement): Blaze.View; - function Template(viewName?: string, renderFunction?: Function): void; - interface Template{ + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; + var Template: TemplateStatic; + interface TemplateStatic { + new(viewName?: string, renderFunction?: Function): Template; + // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance + [templateName: string]: any | Template; // added "any" to make it work + head: Template; + find(selector:string):Blaze.Template; + findAll(selector:string):Blaze.Template[]; + $:any; + } + interface Template { } - function TemplateInstance(view: Blaze.View): void; - interface TemplateInstance{ + var TemplateInstance: TemplateInstanceStatic; + interface TemplateInstanceStatic { + new(view: Blaze.View): TemplateInstance; + } + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: Function): Object; data: Object; - view: Object; + find(selector?: string): Blaze.TemplateInstance; + findAll(selector: string): Blaze.TemplateInstance[]; firstNode: Object; lastNode: Object; - $(selector: string): Node[]; - findAll(selector: string): HTMLElement[]; - find(selector?: string): HTMLElement; - autorun(runFunc: Function): Object; + subscribe(name: string, ...args): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; } - function View(name?: string, renderFunction?: Function): void; - interface View{ + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; + var View: ViewStatic; + interface ViewStatic { + new(name?: string, renderFunction?: Function): View; + } + interface View { } + function With(data: Object | Function, contentFunc: Function): Blaze.View; + var currentView: Blaze.View; + function getData(elementOrView?: HTMLElement | Blaze.View): Object; + function getView(element?: HTMLElement): Blaze.View; + function isTemplate(value: any): boolean; + function remove(renderedView: Blaze.View): void; + function render(templateOrView: Template | Blaze.View, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; + function renderWithData(templateOrView: Template | Blaze.View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; + function toHTML(templateOrView: Template | Blaze.View): string; + function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string; } -declare module Match { - function test(value: any, pattern: any): boolean; +declare module Cordova { + function depends(dependencies:{[id:string]:string}): void; } declare module DDP { @@ -352,330 +427,355 @@ declare module DDP { } declare module EJSON { - var newBinary: any; - function addType(name: string, factory: Function): void; - function toJSONValue(val: EJSON): JSON; - function fromJSONValue(val: JSON): any; - function stringify(val: EJSON, options?: { - indent?: boolean | number | string; - canonical?: Boolean; - }): string; - function parse(str: string): EJSON; - function isBinary(x: Object): boolean; - function equals(a: EJSON, b: EJSON, options?: { - keyOrderSensitive?: boolean; - }): boolean; - function clone(val:T): T; - function CustomType(): void; - interface CustomType{ - typeName(): string; - toJSONValue(): JSON; + var CustomType: CustomTypeStatic; + interface CustomTypeStatic { + new(): CustomType; + } + interface CustomType { clone(): EJSON.CustomType; equals(other: Object): boolean; + toJSONValue(): JSON; + typeName(): string; } + function addType(name: string, factory: (val: EJSONable) => JSONable): void; + function clone(val:T): T; + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + function fromJSONValue(val: JSON): any; + function isBinary(x: Object): boolean; + var newBinary: any; + function parse(str: string): EJSON; + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + function toJSONValue(val: EJSON): JSON; +} + +declare module Match { + function test(value: any, pattern: any): boolean; } declare module Meteor { - var users: Mongo.Collection; - var isClient: boolean; - var isServer: boolean; - var settings: {[id:string]: any}; - var isCordova: boolean; - var release: string; - function userId(): string; - function loggingIn(): boolean; - function user(): Meteor.User; - function logout(callback?: Function): void; - function logoutOtherClients(callback?: Function): void; - function loginWith(options?: { - requestPermissions?: string[]; - requestOfflineToken?: boolean; - forceApprovalPrompt?: Boolean; - userEmail?: string; - loginStyle?: string; - }, callback?: Function): void; - function loginWithPassword(user: Object | string, password: string, callback?: Function): void; - function subscribe(name: string, ...args): SubscriptionHandle; - function call(name: string, ...args): void; - function apply(name: string, args: EJSON[], options?: { - wait?: boolean; - onResultReceived?: Function; - }, asyncCallback?: Function): void; - function status(): Meteor.StatusEnum; - function reconnect(): void; - function disconnect(): void; - function onConnection(callback: Function): void; - function publish(name: string, func: Function): void; - function methods(methods: Object): void; - function wrapAsync(func: Function, context?: Object): any; - function startup(func: Function): void; - function setTimeout(func: Function, delay: number): number; - function setInterval(func: Function, delay: number): number; - function clearInterval(id: number): void; - function clearTimeout(id: number): void; - function absoluteUrl(path?: string, options?: { - secure?: boolean; - replaceLocalhost?: Boolean; - rootUrl?: string; - }): string; - function Error(error: string, reason?: string, details?: string): void; - interface Error{ + var Error: ErrorStatic; + interface ErrorStatic { + new(error: string, reason?: string, details?: string): Error; + } + interface Error { } + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + }, asyncCallback?: Function): any; + function call(name: string, ...args): any; + function clearInterval(id: number): void; + function clearTimeout(id: number): void; + function disconnect(): void; + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + function loggingIn(): boolean; + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + forceApprovalPrompt?: boolean; + userEmail?: string; + loginStyle?: string; + }, callback?: Function): void; + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + function logout(callback?: Function): void; + function logoutOtherClients(callback?: Function): void; + function methods(methods: Object): void; + function onConnection(callback: Function): void; + function publish(name: string, func: Function): void; + function reconnect(): void; + var release: string; + function setInterval(func: Function, delay: number): number; + function setTimeout(func: Function, delay: number): number; + var settings: {[id:string]: any}; + function startup(func: Function): void; + function status(): Meteor.StatusEnum; + function subscribe(name: string, ...args): Meteor.SubscriptionHandle; + function user(): Meteor.User; + function userId(): string; + var users: Mongo.Collection; + function wrapAsync(func: Function, context?: Object): any; } declare module Mongo { - function Collection(name: string, options?: { - connection?: Object; - idGeneration?: string; - transform?: Function; - }): void; - interface Collection{ - insert(doc: Object, callback?: Function): string; - update(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { - multi?: boolean; - upsert?: Boolean; - }, callback?: Function): number; - find(selector?: Mongo.Selector, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - limit?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - }): Mongo.Cursor; - findOne(selector?: Mongo.Selector, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - }): T; - remove(selector: Mongo.Selector, callback?: Function): void; - upsert(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { - multi?: boolean; - }, callback?: Function): {numberAffected?: number; insertedId?: string;}; + var Collection: CollectionStatic; + interface CollectionStatic { + new(name: string, options?: { + connection?: Object; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { allow(options: { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; + insert?: (userId:string, doc) => boolean; + update?: (userId, doc, fieldNames, modifier) => boolean; + remove?: (userId, doc) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; deny(options: { - insert?: (userId:string, doc) => boolean; - update?: (userId, doc, fieldNames, modifier) => boolean; - remove?: (userId, doc) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; + insert?: (userId:string, doc) => boolean; + update?: (userId, doc, fieldNames, modifier) => boolean; + remove?: (userId, doc) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Mongo.Selector, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + limit?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Mongo.Cursor; + findOne(selector?: Mongo.Selector, options?: { + sort?: Mongo.SortSpecifier; + skip?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: Object, callback?: Function): string; + remove(selector: Mongo.Selector, callback?: Function): void; + update(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Mongo.Selector, modifier: Mongo.Modifier, options?: { + multi?: boolean; + }, callback?: Function): {numberAffected?: number; insertedId?: string;}; + _ensureIndex(indexName: string, options?: {[key: string]: any}): void; } - function ObjectID(hexString: string): void; - interface ObjectID{ + var Cursor: CursorStatic; + interface CursorStatic { + new(): Cursor; } - - function Cursor(): void; - interface Cursor{ - forEach(callback: Function, thisArg?: any): void; - map(callback: Function, thisArg?: any): void; - fetch(): Array; + interface Cursor { count(): number; + fetch(): Array; + forEach(callback: (doc: T, index: number, cursor: Mongo.Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Mongo.Cursor) => void, thisArg?: any): Array; observe(callbacks: Object): Meteor.LiveQueryHandle; observeChanges(callbacks: Object): Meteor.LiveQueryHandle; } -} - -declare module Tracker { - var active: boolean; - var currentComputation: Tracker.Computation; - function Computation(): void; - interface Computation{ - stopped: boolean; - invalidated: boolean; - firstRun: boolean; - onInvalidate(callback: Function): void; - invalidate(): void; - stop(): void; + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new(hexString: string): ObjectID; + } + interface ObjectID { } - function flush(): void; - function autorun(runFunc: Function): Tracker.Computation; - function nonreactive(func: Function): void; - function onInvalidate(callback: Function): void; - function afterFlush(callback: Function): void; - function Dependency(): void; - interface Dependency{ - depend(fromComputation?: Tracker.Computation): boolean - changed(): void; - hasDependents(): boolean - } - -} - -declare module Assets { - function getText(assetPath: string, asyncCallback?: Function): string; - function getBinary(assetPath: string, asyncCallback?: Function): EJSON; -} - -declare module App { - function info(options: { - id?: string; - version?: string; - name?: string; - description?: string; - author?: string; - email?: string; - website?: string; - }): void; - function setPreference(name: string, value: string): void; - function configurePlugin(pluginName: string, config: Object): void; - function icons(icons: Object): void; - function launchScreens(launchScreens: Object): void; -} - -declare module Package { - function describe(options: { - summary?: string; - version?: string; - name?: string; - git?: string; - documentation?: string; - }): void; - function onUse(func: Function): void; - function onTest(func: Function): void; - function registerBuildPlugin(options?: { - name?: string; - use?: string | string[]; - sources?: string[]; - npmDependencies?: Object; - }): void; } declare module Npm { function depends(dependencies:{[id:string]:string}): void; - function require(name: string): void; + function require(name: string): any; } -declare module Cordova { - function depends(dependencies:{[id:string]:string}): void; +declare module Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + }): void; + function onTest(func: Function): void; + function onUse(func: Function): void; + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; +} + +declare module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + stop(): void; + stopped: boolean; + } + + var Dependency: DependencyStatic; + interface DependencyStatic { + new(): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Tracker.Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + function afterFlush(callback: Function): void; + function autorun(runFunc: (computation: Tracker.Computation) => void, options?: { + onError?: Function; + }): Tracker.Computation; + var currentComputation: Tracker.Computation; + function flush(): void; + function nonreactive(func: Function): void; + function onInvalidate(callback: Function): void; } declare module Session { - function set(key: string, value: EJSON | any /** Undefined **/): void; - function setDefault(key: string, value: EJSON | any /** Undefined **/): void; - function get(key: string): any; function equals(key: string, value: string | number | boolean | any /** Null **/ | any /** Undefined **/): boolean; + function get(key: string): any; + function set(key: string, value: EJSONable | any /** Undefined **/): void; + function setDefault(key: string, value: EJSONable | any /** Undefined **/): void; } declare module HTTP { function call(method: string, url: string, options?: { - content?: string; - data?: Object; - query?: string; - params?: Object; - auth?: string; - headers?: Object; - timeout?: number; - followRedirects?: boolean; - }, asyncCallback?: Function): HTTP.HTTPResponse; + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + }, asyncCallback?: Function): HTTP.HTTPResponse; + function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; function get(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; function post(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; function put(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; } declare module Email { function send(options: { - from?: string; - to?: string | string[]; - cc?: string | string[]; - bcc?: string | string[]; - replyTo?: string | string[]; - subject?: string; - text?: string; - html?: string; - headers?: Object; - }): void; + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + }): void; } -declare function Subscription(): void; -interface Subscription{ - connection: Meteor.Connection; - userId: string; - error(error: Error): void; - stop(): void; - onStop(func: Function): void; - added(collection: string, id: string, fields: Object): void; - changed(collection: string, id: string, fields: Object): void; - removed(collection: string, id: string): void; - ready(): void; +declare var CompileStep: CompileStepStatic; +interface CompileStepStatic { + new(): CompileStep; +} +interface CompileStep { + addAsset(options: { + }, path: string, data: any /** Buffer **/ | string); /** TODO: add return value **/ + addHtml(options: { + section?: string; + data?: string; + }); /** TODO: add return value **/ + addJavaScript(options: { + path?: string; + data?: string; + sourcePath?: string; + }); /** 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 **/ + 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 **/ + read(n?: number): any; + rootOutputPath; /** TODO: add return value **/ } -declare function ReactiveVar(initialValue: T, equalsFunc?: Function): void; -interface ReactiveVar{ +declare var PackageAPI: PackageAPIStatic; +interface PackageAPIStatic { + new(): PackageAPI; +} +interface PackageAPI { + addFiles(filename: string | string[], architecture?: string): void; + export(exportedObject: string, architecture?: string): void; + imply(packageSpecs: string | string[]): void; + use(packageNames: string | string[], architecture?: string, options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; +} + +declare var ReactiveVar: ReactiveVarStatic; +interface ReactiveVarStatic { + new(initialValue: T, equalsFunc?: Function): ReactiveVar; +} +interface ReactiveVar { get(): T; set(newValue: T): void; } +declare var Subscription: SubscriptionStatic; +interface SubscriptionStatic { + new(): Subscription; +} +interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; +} + declare var Template: TemplateStatic; -// TemplateStatic interface should be defined separately at top with static methods -interface Template{ - onCreated: Function; - onRendered: Function; - onDestroyed: Function; - created: Function; - rendered: Function; - destroyed: Function; - body: TemplateStatic; - helpers(helpers:{[id:string]: any}): void; - events(eventMap: {[actions: string]: Function}): void; - instance(): Blaze.TemplateInstance; +interface TemplateStatic { + new(): Template; + // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance + [templateName: string]: any | Template; // added "any" to make it work + head: Template; + find(selector:string):Blaze.Template; + findAll(selector:string):Blaze.Template[]; + $:any; + body: Template; currentData(): {}; + instance(): Blaze.TemplateInstance; parentData(numLevels?: number): {}; registerHelper(name: string, helperFunction: Function): void; } - -declare function CompileStep(): void; -interface CompileStep{ - inputSize; /** TODO: add return value **/ - inputPath; /** TODO: add return value **/ - fullInputPath; /** TODO: add return value **/ - pathForSourceMap; /** TODO: add return value **/ - packageName; /** TODO: add return value **/ - rootOutputPath; /** TODO: add return value **/ - arch; /** TODO: add return value **/ - fileOptions; /** TODO: add return value **/ - declaredExports; /** TODO: add return value **/ - read(n?: number); /** TODO: add return value **/ - addHtml(options: { - section?: string; - data?: string; - }); /** TODO: add return value **/ - addStylesheet(options: { - }, path: string, data: string, sourceMap: string); /** TODO: add return value **/ - addJavaScript(options: { - path?: string; - data?: string; - sourcePath?: string; - }); /** TODO: add return value **/ - addAsset(options: { - }, path: string, data: any /** Buffer **/ | string); /** TODO: add return value **/ - error(options: { - }, message: string, sourcePath?: string, line?: number, func?: string); /** TODO: add return value **/ -} - -declare function PackageAPI(): void; -interface PackageAPI{ - use(packageNames: string | string[], architecture?: string, options?: { - weak?: boolean; - unordered?: Boolean; - }): void; - imply(packageSpecs: string | string[]): void; - addFiles(filename: string | string[], architecture?: string): void; - versionsFrom(meteorRelease: string | string[]): void; - export(exportedObject: string, architecture?: string): void; +interface Template { + created: Function; + destroyed: Function; + events(eventMap: {[actions: string]: Function}): void; + helpers(helpers:{[id:string]: any}): void; + onCreated: Function; + onDestroyed: Function; + onRendered: Function; + rendered: Function; } +declare function MethodInvocation(options: { +}); /** TODO: add return value **/ +declare function check(value: any, pattern: any): void; diff --git a/mocha/mocha.d.ts b/mocha/mocha.d.ts index 6a2a539593..3f5d3e5710 100644 --- a/mocha/mocha.d.ts +++ b/mocha/mocha.d.ts @@ -37,10 +37,10 @@ interface MochaSetupOptions { reporter?: any; // bail on the first test failure - bail?: Boolean; + bail?: boolean; // ignore global leaks - ignoreLeaks?: Boolean; + ignoreLeaks?: boolean; // grep string or regexp to filter tests with grep?: any; diff --git a/moment-timezone/moment-timezone-tests.ts b/moment-timezone/moment-timezone-tests.ts index f6a754c6e7..6e818c7424 100644 --- a/moment-timezone/moment-timezone-tests.ts +++ b/moment-timezone/moment-timezone-tests.ts @@ -8,11 +8,16 @@ june.tz('America/Los_Angeles').format('ha z'); var a = moment.tz("2013-11-18 11:55", "America/Toronto"); var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto"); var c = moment.tz(1403454068850, "America/Toronto"); +var d = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", true, "America/Toronto"); + +a.tz(); var arr = [2013, 5, 1], str = "2013-12-01", obj = { year : 2013, month : 5, day : 1 }; +moment.tz("America/Los_Angeles"); + moment.tz(arr, "America/Los_Angeles"); moment.tz(str, "America/Los_Angeles"); moment.tz(obj, "America/Los_Angeles"); diff --git a/moment-timezone/moment-timezone.d.ts b/moment-timezone/moment-timezone.d.ts index 1e908ace10..02d72ac2ed 100644 --- a/moment-timezone/moment-timezone.d.ts +++ b/moment-timezone/moment-timezone.d.ts @@ -7,6 +7,7 @@ declare module moment { interface Moment { + tz(): string; tz(timezone: string): Moment; } @@ -27,9 +28,11 @@ interface MomentZone { } interface MomentTimezone { + (timezone: string): moment.Moment; (date: number, timezone: string): moment.Moment; (date: number[], timezone: string): moment.Moment; (date: string, format: string, timezone: string): moment.Moment; + (date: string, format: string, useStrict: boolean, timezone: string): moment.Moment; (date: Date, timezone: string): moment.Moment; (date: moment.Moment, timezone: string): moment.Moment; (date: Object, timezone: string): moment.Moment; diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 8c60b638fc..fedd8fec65 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -128,7 +128,7 @@ declare module "mongoose" { versionKey?: boolean; } - export interface Model { + export interface Model extends NodeJS.EventEmitter { new(doc: Object): T; aggregate(...aggregations: Object[]): Aggregate; diff --git a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api-tests.ts b/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api-tests.ts deleted file mode 100644 index 76dba72a52..0000000000 --- a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api-tests.ts +++ /dev/null @@ -1,127 +0,0 @@ -/// - -import Syntax = spiderMonkeyParserAPI.Syntax; - -var literal:Syntax.Literal = { - loc: { - source: null, - start: { - line: 1, - column: 10 - }, - end: { - line: 1, - column: 12 - } - }, - type: "Literal", - value: 42 -}; - -// generated by http://esprima.org/demo/parse.html?code=%22use%20strict%22%3B%0A%0Afunction%20Test%20()%20%7B%0A%7D%0A%0ATest.prototype.hello%20%3D%20function(word)%20%7B%0A%09word%20%3D%20word%20%7C%7C%20%22TypeScript%22%3B%0A%09return%20word%3B%0A%7D%3B%0A -var program:Syntax.Program = { - "type": "Program", - "body": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "Literal", - "value": "use strict", - "raw": "\"use strict\"" - } - }, - { - "type": "FunctionDeclaration", - "id": { - "type": "Identifier", - "name": "Test" - }, - "params": [], - "defaults": [], - "body": { - "type": "BlockStatement", - "body": [] - }, - "rest": null, - "generator": false, - "expression": false - }, - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "MemberExpression", - "computed": false, - "object": { - "type": "MemberExpression", - "computed": false, - "object": { - "type": "Identifier", - "name": "Test" - }, - "property": { - "type": "Identifier", - "name": "prototype" - } - }, - "property": { - "type": "Identifier", - "name": "hello" - } - }, - "right": { - "type": "FunctionExpression", - "id": null, - "params": [ - { - "type": "Identifier", - "name": "word" - } - ], - "defaults": [], - "body": { - "type": "BlockStatement", - "body": [ - { - "type": "ExpressionStatement", - "expression": { - "type": "AssignmentExpression", - "operator": "=", - "left": { - "type": "Identifier", - "name": "word" - }, - "right": { - "type": "LogicalExpression", - "operator": "||", - "left": { - "type": "Identifier", - "name": "word" - }, - "right": { - "type": "Literal", - "value": "TypeScript", - "raw": "\"TypeScript\"" - } - } - } - }, - { - "type": "ReturnStatement", - "argument": { - "type": "Identifier", - "name": "word" - } - } - ] - }, - "rest": null, - "generator": false, - "expression": false - } - } - } - ] -}; diff --git a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api.d.ts b/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api.d.ts deleted file mode 100644 index e91029137e..0000000000 --- a/mozilla-spidermonkey-parser-api/mozilla-spidermonkey-parser-api.d.ts +++ /dev/null @@ -1,614 +0,0 @@ -// Type definitions for Mozilla SpiderMonkey Parser API 1.8.5 -// Project: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API -// Definitions by: vvakame -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare module spiderMonkeyParserAPI { - - // NOTE if property can hold null, that property to be optional. - - module Syntax { - /** - * By default, Reflect.parse() produces Node objects, which are plain JavaScript objects (i.e., their prototype derives from the standard Object prototype). - * All node types implement the following interface: - */ - interface Node { - /** - * The type field is a string representing the AST variant type. - * Each subtype of Node is documented below with the specific string of its type field. - * You can use this field to determine which interface a node implements. - */ - type: string; - /** - * The loc field represents the source location information of the node. - * If the parser produced no information about the node's source location, the field is null; otherwise it is an object consisting of a start position (the position of the first character of the parsed source region) and an end position (the position of the first character after the parsed source region): - */ - loc?: SourceLocation; - } - - interface SourceLocation { - source?: string; - start: Position; - end: Position; - } - - /** - * Each Position object consists of a line number (1-indexed) and a column number (0-indexed): - */ - interface Position { - line: number; // uint32 >= 1; - column: number; // uint32 >= 0; - } - - /** - * A complete program source tree. - */ - interface Program extends Node { - type: string; // "Program" - body: Statement[]; - } - - /** - * A function declaration or expression. - * The body of the function may be a block statement, or in the case of an expression closure, an expression. - * If the generator flag is true, the function is a generator function, i.e., contains a yield expression in its body (other than in a nested function). - * If the expression flag is true, the function is an expression closure and the body field is an expression. - */ - interface Function extends Node { - id?: Identifier; - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body?: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * Any statement. - */ - interface Statement extends Node { - } - - /** - * An empty statement, i.e., a solitary semicolon. - */ - interface EmptyStatement extends Statement { - type: string; // "EmptyStatement"; - } - - /** - * A block statement, i.e., a sequence of statements surrounded by braces. - */ - interface BlockStatement extends Statement { - type: string; // "BlockStatement"; - body: Statement[]; - } - - /** - * An if statement. - */ - interface IfStatement extends Statement { - type: string; // "IfStatement"; - test: Expression; - consequent: Statement; - alternate?: Statement; - } - - /** - * A labeled statement, i.e., a statement prefixed by a break/continue label. - */ - interface LabeledStatement extends Statement { - type: string; // "LabeledStatement"; - label: Identifier; - body: Statement; - } - - /** - * A break statement. - */ - interface BreakStatement extends Statement { - type: string; // "BreakStatement"; - label?: Identifier; - } - - /** - * A continue statement. - */ - interface ContinueStatement extends Statement { - type: string; // "ContinueStatement"; - label?: Identifier; - } - - /** - * A with statement. - */ - interface WithStatement extends Statement { - type: string; // "WithStatement"; - object: Expression; - body: Statement; - } - - /** - * A switch statement. - * The lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope). - */ - interface SwitchStatement extends Statement { - type: string; // "SwitchStatement"; - discriminant: Expression; - cases: SwitchCase[]; - lexical: boolean; - } - - /** - * A return statement. - */ - interface ReturnStatement extends Statement { - type: string; // "ReturnStatement"; - argument?: Expression; - } - - /** - * A throw statement. - */ - interface ThrowStatement extends Statement { - type: string; // "ThrowStatement"; - argument: Expression; - } - - /** - * A try statement. - */ - interface TryStatement extends Statement { - type: string; //"TryStatement"; - block: BlockStatement; - handler?: CatchClause; - guardedHandlers: CatchClause[]; - finalizer?: BlockStatement; - } - - /** - * A while statement. - */ - interface WhileStatement extends Statement { - type: string; // "WhileStatement"; - test: Expression; - body: Statement; - } - - /** - * A do/while statement. - */ - interface DoWhileStatement extends Statement { - type: string; // "DoWhileStatement"; - body: Statement; - test: Expression; - } - - /** - * A for statement. - */ - interface ForStatement extends Statement { - type: string; // "ForStatement"; - init?: VariableDeclaration | Expression; - test?: Expression; - update?: Expression; - body: Statement; - } - - /** - * A for/in statement, or, if each is true, a for each/in statement. - */ - interface ForInStatement extends Statement { - type: string; // "ForInStatement"; - left: VariableDeclaration | Expression; - right: Expression; - body: Statement; - each: boolean; - } - - /** - * A for/of statement. - */ - interface ForOfStatement extends Statement { - type: string; // "ForOfStatement"; - left: VariableDeclaration | Expression; - right: Expression; - body: Statement; - } - - /** - * A let statement. - */ - interface LetStatement extends Statement { - type: string; // "LetStatement"; - head: VariableDeclarator[]; - body: Statement; - } - - /** - * A debugger statement. - */ - interface DebuggerStatement extends Statement { - type: string; // "DebuggerStatement"; - } - - /** - * Any declaration node. Note that declarations are considered statements; this is because declarations can appear in any statement context in the language recognized by the SpiderMonkey parser. - */ - interface Declaration extends Statement { - } - - /** - * A function declaration. - */ - interface FunctionDeclaration extends Function, Declaration { - type: string; // "FunctionDeclaration"; - id: Identifier; // Note: The id field cannot be null. - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * A variable declaration, via one of var, let, or const. - */ - interface VariableDeclaration extends Declaration { - type: string; // "VariableDeclaration"; - declarations: VariableDeclarator[]; - kind: string; // "var" | "let" | "const"; - } - - /** - * A variable declarator. - */ - interface VariableDeclarator extends Node { - type: string; // "VariableDeclarator"; - id: Pattern; // Note: The id field cannot be null. - init?: Expression; - } - - /** - * Any expression node. - * Since the left-hand side of an assignment may be any expression in general, an expression can also be a pattern. - */ - interface Expression extends Node, Pattern { - } - - /** - * A this expression. - */ - interface ThisExpression extends Expression { - type: string; // "ThisExpression"; - } - - /** - * An array expression. - */ - interface ArrayExpression extends Expression { - type: string; // "ArrayExpression"; - elements: Expression[]; // [ Expression | null ]; - } - - /** - * An object expression. - */ - interface ObjectExpression extends Expression { - type: string; // "ObjectExpression"; - properties: Property[]; - } - - /** - * A literal property in an object expression can have either a string or number as its value. - * Ordinary property initializers have a kind value "init"; getters and setters have the kind values "get" and "set", respectively. - */ - interface Property extends Node { - type: string; // "Property"; - key: Literal | Identifier; - value: Expression; - kind: string; // "init" | "get" | "set"; - } - - /** - * A function expression. - */ - interface FunctionExpression extends Function, Expression { - type: string; // "FunctionExpression"; - id?: Identifier; - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * A fat arrow function expression, i.e., `let foo = (bar) => { ... body ... }`. - */ - interface ArrowExpression extends Function, Expression { - type: string; // "ArrowExpression"; - params: Pattern[]; - defaults: Expression[]; - rest?: Identifier; - body: BlockStatement | Expression; - generator: boolean; - expression: boolean; - } - - /** - * A sequence expression, i.e., a comma-separated sequence of expressions. - */ - interface SequenceExpression extends Expression { - type: string; // "SequenceExpression"; - expressions: Expression[]; - } - - /** - * A unary operator expression. - */ - interface UnaryExpression extends Expression { - type: string; // "UnaryExpression"; - operator: UnaryOperator; - prefix: boolean; - argument: Expression; - } - - /** - * A binary operator expression. - */ - interface BinaryExpression extends Expression { - type: string; // "BinaryExpression"; - operator: BinaryOperator; - left: Expression; - right: Expression; - } - - /** - * An assignment operator expression. - */ - interface AssignmentExpression extends Expression { - type: string; // "AssignmentExpression"; - operator: AssignmentOperator; - left: Expression; - right: Expression; - } - - /** - * An update (increment or decrement) operator expression. - */ - interface UpdateExpression extends Expression { - type: string; // "UpdateExpression"; - operator: UpdateOperator; - argument: Expression; - prefix: boolean; - } - - /** - * A logical operator expression. - */ - interface LogicalExpression extends Expression { - type: string; // "LogicalExpression"; - operator: LogicalOperator; - left: Expression; - right: Expression; - } - - /** - * A conditional expression, i.e., a ternary ?/: expression. - */ - interface ConditionalExpression extends Expression { - type: string; // "ConditionalExpression"; - test: Expression; - alternate: Expression; - consequent: Expression; - } - - /** - * A new expression. - */ - interface NewExpression extends Expression { - type: string; // "NewExpression"; - callee: Expression; - arguments: Expression[]; - } - - /** - * A function or method call expression. - */ - interface CallExpression extends Expression { - type: string; // "CallExpression"; - callee: Expression; - arguments: Expression[]; - } - - /** - * A member expression. - * If computed === true, the node corresponds to a computed e1[e2] expression and property is an Expression. - * If computed === false, the node corresponds to a static e1.x expression and property is an Identifier. - */ - interface MemberExpression extends Expression { - type: string; // "MemberExpression"; - object: Expression; - property: Identifier | Expression; - computed: boolean; - } - - /** - * A yield expression. - */ - interface YieldExpression extends Expression { - type: string; // "YieldExpression"; - argument?: Expression; - } - - /** - * An array comprehension. - * The blocks array corresponds to the sequence of for and for each blocks. - * The optional filter expression corresponds to the final if clause, if present. - */ - interface ComprehensionExpression extends Expression { - type: string; // "ComprehensionExpression"; - body: Expression; - blocks: ComprehensionBlock[]; - filter?: Expression; - } - - /** - * A generator expression. - * As with array comprehensions, the blocks array corresponds to the sequence of for and for each blocks, and the optional filter expression corresponds to the final if clause, if present. - */ - interface GeneratorExpression extends Expression { - type: string; // "GeneratorExpression"; - body: Expression; - blocks: ComprehensionBlock[]; - filter?: Expression; - } - - /** - * A graph expression, aka "sharp literal," such as #1={ self: #1# }. - */ - interface GraphExpression extends Expression { - type: string; // "GraphExpression"; - index: number; // uint32; - expression: Literal; - } - - /** - * A graph index expression, aka "sharp variable," such as #1#. - */ - interface GraphIndexExpression extends Expression { - type: string; // "GraphIndexExpression"; - index: number; // uint32; - } - - /** - * A let expression. - */ - interface LetExpression extends Expression { - type: string; // "LetExpression"; - head: VariableDeclarator[]; - body: Expression; - } - - /** - * JavaScript 1.7 introduced destructuring assignment and binding forms. - * All binding forms (such as function parameters, variable declarations, and catch block headers) accept array and object destructuring patterns in addition to plain identifiers. - * The left-hand sides of assignment expressions can be arbitrary expressions, but in the case where the expression is an object or array literal, it is interpreted by SpiderMonkey as a destructuring pattern. - * - * Since the left-hand side of an assignment can in general be any expression, in an assignment context, a pattern can be any expression. - * In binding positions (such as function parameters, variable declarations, and catch headers), patterns can only be identifiers in the base case, not arbitrary expressions. - */ - interface Pattern extends Node { - } - - /** - * An object-destructuring pattern. A literal property in an object pattern can have either a string or number as its value. - */ - interface ObjectPattern extends Pattern { - type: string; // "ObjectPattern"; - properties: {key: Literal | Identifier; value: Pattern;}[]; // [ { key: Literal | Identifier, value: Pattern } ]; - } - - /** - * An array-destructuring pattern. - */ - interface ArrayPattern extends Pattern { - type: string; // "ArrayPattern"; - elements: Pattern[]; // [ Pattern | null ]; - } - - /** - * A case (if test is an Expression) or default (if test === null) clause in the body of a switch statement. - */ - interface SwitchCase extends Node { - type: string; // "SwitchCase"; - test?: Expression; - consequent: Statement[]; - } - - /** - * A catch clause following a try block. - * The optional guard property corresponds to the optional expression guard on the bound variable. - */ - interface CatchClause extends Node { - type: string; // "CatchClause"; - param: Pattern; - guard?: Expression; - body: BlockStatement; - } - - /** - * A for or for each block in an array comprehension or generator expression. - */ - interface ComprehensionBlock extends Node { - type: string; // "ComprehensionBlock"; - left: Pattern; - right: Expression; - each: boolean; - } - - /** - * An identifier. - * Note that an identifier may be an expression or a destructuring pattern. - */ - interface Identifier extends Node, Expression, Pattern { - type: string; // "Identifier"; - name: string; - } - - /** - * A literal token. Note that a literal can be an expression. - */ - interface Literal extends Node, Expression { - type: string; // "Literal"; - value?: string | boolean | number | RegExp; - } - - /** - * A unary operator token. - */ - interface UnaryOperator extends String { - // "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" - } - - /** - * A binary operator token. - */ - interface BinaryOperator extends String { - // "==" | "!=" | "===" | "!==" - // | "<" | "<=" | ">" | ">=" - // | "<<" | ">>" | ">>>" - // | "+" | "-" | "*" | "/" | "%" - // | "|" | "^" | "&" | "in" - // | "instanceof" | ".." - // Note: The .. operator is E4X-specific. - } - - /** - * A logical operator token. - */ - interface LogicalOperator extends String { - // "||" | "&&" - } - - /** - * An assignment operator token. - */ - interface AssignmentOperator extends String { - // "=" | "+=" | "-=" | "*=" | "/=" | "%=" - // | "<<=" | ">>=" | ">>>=" - // | "|=" | "^=" | "&=" - } - - /** - * An update (increment or decrement) operator token. - */ - interface UpdateOperator extends String { - // "++" | "--" - } - } -} diff --git a/ng-grid/ng-grid-tests.ts b/ng-grid/ng-grid-tests.ts index 82105ea5b7..d8d153f289 100644 --- a/ng-grid/ng-grid-tests.ts +++ b/ng-grid/ng-grid-tests.ts @@ -63,7 +63,7 @@ selectionProvider.selectedItems = []; selectionProvider.selectedIndex = 1; selectionProvider.lastClickedRow = {}; selectionProvider.ignoreSelectedItemChanges = false; -selectionProvider.pKeyParser = {}; +selectionProvider.pKeyParser = {}; selectionProvider.ChangeSelection({}, {}); nr = selectionProvider.getSelection({}); nr = selectionProvider.getSelectionIndex({}); @@ -256,15 +256,15 @@ nr = gridScope.totalRowWidth(); a = gridScope.headerScrollerDim(); var gridInstance: ngGrid.IGridInstance = {}; -gridInstance.$canvas = {}; -gridInstance.$viewport = {}; -gridInstance.$groupPanel = {}; -gridInstance.$footerPanel = {}; -gridInstance.$headerScroller = {}; -gridInstance.$headerContainer = {}; -gridInstance.$headers = {}; -gridInstance.$topPanel = {}; -gridInstance.$root = {}; +gridInstance.$canvas = {}; +gridInstance.$viewport = {}; +gridInstance.$groupPanel = {}; +gridInstance.$footerPanel = {}; +gridInstance.$headerScroller = {}; +gridInstance.$headerContainer = {}; +gridInstance.$headers = {}; +gridInstance.$topPanel = {}; +gridInstance.$root = {}; gridInstance.config = {}; gridInstance.data = {}; gridInstance.elementDims = {}; @@ -290,7 +290,7 @@ gridInstance.clearSortingData(); gridInstance.configureColumnWidths(); gridInstance.fixColumnIndexes(); gridInstance.fixGroupIndexes(); -var p:ng.IPromise = gridInstance.getTemplate(''); +var p:angular.IPromise = gridInstance.getTemplate(''); p = gridInstance.init(); p = gridInstance.initTemplates(); gridInstance.minRowsToRender(); @@ -302,12 +302,12 @@ gridInstance.sortColumnsInit(); gridInstance.sortData({}, {}); var test_styleProvider:ngGrid.IStyleProvider = new ngStyleProvider({}, {}); -var test_searchProvider:ngGrid.ISearchProvider = new ngSearchProvider({}, {}, {}); -var test_selectionProvider:ngGrid.ISelectionProvider = new ngSelectionProvider({}, {}, {}); -var test_eventProvider:ngGrid.IEventProvider = new ngEventProvider({}, {}, {}, {}); +var test_searchProvider:ngGrid.ISearchProvider = new ngSearchProvider({}, {}, {}); +var test_selectionProvider:ngGrid.ISelectionProvider = new ngSelectionProvider({}, {}, {}); +var test_eventProvider:ngGrid.IEventProvider = new ngEventProvider({}, {}, {}, {}); var test_aggregate:ngGrid.IAggregate = new ngAggregate({}, {}, 10, true); var test_renderedRange:ngGrid.IRenderedRange = new ngRenderedRange(1, 2); var test_dimension:ngGrid.IDimension = new ngDimension({}); var test_row:ngGrid.IRow = new ngRow({}, {}, {}, 0, {}); -var test_column:ngGrid.IColumn = new ngColumn({}, {}, {}, {}, {}, {}); +var test_column:ngGrid.IColumn = new ngColumn({}, {}, {}, {}, {}, {}); var test_footer:ngGrid.IFooter = new ngFooter({}, {}); diff --git a/ng-grid/ng-grid.d.ts b/ng-grid/ng-grid.d.ts index 3bb3b2daab..0fb267faac 100644 --- a/ng-grid/ng-grid.d.ts +++ b/ng-grid/ng-grid.d.ts @@ -30,9 +30,9 @@ declare module ngGrid { export interface IDomAccessProvider { previousColumn:IColumn; grid:IGridInstance; - changeUserSelect(elm:ng.IAugmentedJQuery, value:string):void; + changeUserSelect(elm:angular.IAugmentedJQuery, value:string):void; focusCellElement($scope:IGridScope, index:number):void; - selectionHandlers($scope:IGridScope, elm:ng.IAugmentedJQuery):void; + selectionHandlers($scope:IGridScope, elm:angular.IAugmentedJQuery):void; } export interface IStyleProviderStatic { @@ -43,7 +43,7 @@ declare module ngGrid { } export interface ISearchProviderStatic { - new($scope:IGridScope, grid:IGridInstance, $filter:ng.IFilterService):ISearchProvider; + new($scope:IGridScope, grid:IGridInstance, $filter:angular.IFilterService):ISearchProvider; } export interface ISearchProvider { @@ -53,7 +53,7 @@ declare module ngGrid { } export interface ISelectionProviderStatic { - new(grid:IGridInstance, $scope:IGridScope, $parse:ng.IParseService):ISelectionProvider; + new(grid:IGridInstance, $scope:IGridScope, $parse:angular.IParseService):ISelectionProvider; } export interface ISelectionProvider { @@ -62,7 +62,7 @@ declare module ngGrid { selectedIndex:number; lastClickedRow:any; ignoreSelectedItemChanges:boolean; - pKeyParser:ng.ICompiledExpression; + pKeyParser:angular.ICompiledExpression; ChangeSelection(rowItem:any, event:any):void; getSelection(entity:any):number; getSelectionIndex(entity:any):number; @@ -71,7 +71,7 @@ declare module ngGrid { } export interface IEventProviderStatic { - new(grid:IGridInstance, $scope:IGridScope, domUtilityService:service.IDomUtilityService, $timeout:ng.ITimeoutService):IEventProvider; + new(grid:IGridInstance, $scope:IGridScope, domUtilityService:service.IDomUtilityService, $timeout:angular.ITimeoutService):IEventProvider; } export interface IEventProvider { @@ -203,7 +203,7 @@ declare module ngGrid { } export interface IColumnStatic { - new(config:IGridOptions, $scope:IGridScope, grid:IGridInstance, domUtilityService:service.IDomUtilityService, $templateCache:ng.ITemplateCacheService, $utils:any):IColumn; + new(config:IGridOptions, $scope:IGridScope, grid:IGridInstance, domUtilityService:service.IDomUtilityService, $templateCache:angular.ITemplateCacheService, $utils:any):IColumn; } export interface IColumn { @@ -251,7 +251,7 @@ declare module ngGrid { setVars(fromCol:IColumn):void; } - export interface IGridScope extends ng.IScope { + export interface IGridScope extends angular.IScope { elementsNeedMeasuring:boolean; columns:any[]; renderedRows:any[]; @@ -292,15 +292,15 @@ declare module ngGrid { } export interface IGridInstance { - $canvas:ng.IAugmentedJQuery; - $viewport:ng.IAugmentedJQuery; - $groupPanel:ng.IAugmentedJQuery; - $footerPanel:ng.IAugmentedJQuery; - $headerScroller:ng.IAugmentedJQuery; - $headerContainer:ng.IAugmentedJQuery; - $headers:ng.IAugmentedJQuery; - $topPanel:ng.IAugmentedJQuery; - $root:ng.IAugmentedJQuery; + $canvas:angular.IAugmentedJQuery; + $viewport:angular.IAugmentedJQuery; + $groupPanel:angular.IAugmentedJQuery; + $footerPanel:angular.IAugmentedJQuery; + $headerScroller:angular.IAugmentedJQuery; + $headerContainer:angular.IAugmentedJQuery; + $headers:angular.IAugmentedJQuery; + $topPanel:angular.IAugmentedJQuery; + $root:angular.IAugmentedJQuery; config:IGridOptions; data:any; elementDims:IElementDimension; @@ -327,9 +327,9 @@ declare module ngGrid { configureColumnWidths():void; fixColumnIndexes():void; fixGroupIndexes():void; - getTemplate(key:string):ng.IPromise; - init():ng.IPromise; - initTemplates():ng.IPromise; + getTemplate(key:string):angular.IPromise; + init():angular.IPromise; + initTemplates():angular.IPromise; minRowsToRender():void; refreshDomSizes():void; resizeOnData(col:IColumn):void; @@ -602,7 +602,7 @@ declare module ngGrid { eventStorage:any; numberOfGrids:number; immediate:number; - AssignGridContainers($scope:IGridScope, rootel:ng.IAugmentedJQuery, grid:IGridInstance):void; + AssignGridContainers($scope:IGridScope, rootel:angular.IAugmentedJQuery, grid:IGridInstance):void; getRealWidth(obj:IDimension):number; UpdateGridLayout($scope:IGridScope, grid:IGridInstance):void; setStyleText(grid:IGridInstance, css:string):void; diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index 91c5c0bf0b..7e52a8be3a 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -832,8 +832,8 @@ declare module "azure" { whereKeys(partitionKey: string, rowKey: string): TableQuery; whereNextKeys(partitionKey: string, rowKey: string): TableQuery; where(condition: string, ...values: string[]): TableQuery; - and(condition: string, ...arguments: string[]): TableQuery; - or(condition: string, ...arguments: string[]): TableQuery; + and(condition: string, ...args: string[]): TableQuery; + or(condition: string, ...args: string[]): TableQuery; top(integer: number): TableQuery; toQueryObject(): any; toPath(): string; diff --git a/node/node.d.ts b/node/node.d.ts index 3838a29528..95ea4d8fdc 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -282,15 +282,10 @@ declare module "http" { address(): { port: number; family: string; address: string; }; maxHeadersCount: number; } - export interface ServerRequest extends events.EventEmitter, stream.Readable { - method: string; - url: string; - headers: any; - trailers: string; - httpVersion: string; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; + /** + * @deprecated Use IncomingMessage + */ + export interface ServerRequest extends IncomingMessage { connection: net.Socket; } export interface ServerResponse extends events.EventEmitter, stream.Writable { @@ -340,15 +335,35 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientResponse extends events.EventEmitter, stream.Readable { - statusCode: number; + export interface IncomingMessage extends events.EventEmitter, stream.Readable { httpVersion: string; headers: any; + rawHeaders: string[]; trailers: any; - setEncoding(encoding?: string): void; - pause(): void; - resume(): void; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; } + /** + * @deprecated Use IncomingMessage + */ + export interface ClientResponse extends IncomingMessage { } export interface AgentOptions { /** @@ -390,10 +405,10 @@ declare module "http" { [errorCode: number]: string; [errorCode: string]: string; }; - export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; export function createClient(port?: number, host?: string): any; - export function request(options: any, callback?: Function): ClientRequest; - export function get(options: any, callback?: Function): ClientRequest; + export function request(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; } @@ -563,8 +578,8 @@ declare module "https" { }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.ClientResponse) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; export var globalAgent: Agent; } @@ -1036,6 +1051,36 @@ declare module "path" { export var delimiter: string; export function parse(p: string): ParsedPath; export function format(pP: ParsedPath): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } } declare module "string_decoder" { diff --git a/notifyjs/notifyjs-tests.ts b/notifyjs/notifyjs-tests.ts index 8771224c8e..1b1d7f9065 100644 --- a/notifyjs/notifyjs-tests.ts +++ b/notifyjs/notifyjs-tests.ts @@ -14,6 +14,7 @@ function test_Notify_constructor() { body : "fuga", icon : "./logo.png", tag : "user", + timeout : 1000, notifyShow : (e:Event)=> console.log("notifyShow", e), notifyClose : ()=> console.log("notifyClose"), notifyClick : ()=> console.log("notifyClick"), diff --git a/notifyjs/notifyjs.d.ts b/notifyjs/notifyjs.d.ts index f36b8fbcd0..0cff4e0c52 100644 --- a/notifyjs/notifyjs.d.ts +++ b/notifyjs/notifyjs.d.ts @@ -72,6 +72,11 @@ declare module notifyjs { * unique identifier to stop duplicate notifications */ tag? : string; + + /** + * number of seconds to close the notification automatically + */ + timeout? : number; /** * callback when notification is shown diff --git a/object-path/object-path-tests.ts b/object-path/object-path-tests.ts index 5984c78a8a..d29cec1410 100644 --- a/object-path/object-path-tests.ts +++ b/object-path/object-path-tests.ts @@ -1,68 +1,94 @@ -/// - -var - object = { - one: 1, - two: { - three: 3, - four: ['4'] - } - }, - array: any[] = [], - Null:any = null; - -objectPath.del(array) === ['12']; -objectPath.del(object) === object; -objectPath.del(object) === object; - -objectPath.del() === void 0; -objectPath.del(object, ['1','2','3']); -objectPath.del(object, [1,2,3]); -objectPath.del(object, 1); -objectPath.del(object, 'one').one === 1; - -objectPath.coalesce(object, ['1','2']) === void 0; -objectPath.coalesce(object, ['1',['2','1']]) === void 0; -objectPath.coalesce(object, ['1',['2','1']], 1) === 1; -objectPath.coalesce(object, [1,1], 1) === 1; -objectPath.coalesce(object, >[1,[1,1]], 1) === 1; - -objectPath.ensureExists(object, '1.2', 2); -objectPath.ensureExists(object, 1, 2); -objectPath.ensureExists(object, [1,2], 2); -objectPath.ensureExists(object, ['1','2'], 2); -objectPath.ensureExists(object, ['1','2'], 2) === 3; -objectPath.ensureExists(object, ['1','2'], 2) === [[]]; - -objectPath.push(object, 1, 1,2,3,4); -objectPath.push(object, 1, 1,'2', 3, false); -objectPath.push(object, 'one.four', 1,'2', 3, false); -objectPath.push(object, ['one','two'], [1,'2', 3, false]); - -objectPath.get(array) === array; -objectPath.get(Null) === Null; -objectPath.get() === void 0; -objectPath.get(object, 'one') === 1; -objectPath.get(object, ['two','three']) === 3; -objectPath.get(object, ['three'], 3) === 3; -objectPath.get(object, 'three', 3) === 3; -objectPath.get(object, 0, 3) === 3; -objectPath.get(object, 0, '3') === '3'; -objectPath.get(object, 0, ['1','2']) === ['1','2']; -objectPath.get(object, 0) === 10; - -objectPath.set(object, '1.2', true); -objectPath.set(object, ['1','2'], true); -objectPath.set(object, [1, 2], true); -objectPath.set(object, '1.2', true, true); -objectPath.set(object, '1.2', true, false); -objectPath.set(object, '1.2', true, false) === ['string']; -objectPath.set(object, '1.2', true, false) === object; - -objectPath.insert(object, '1.2', 1); -objectPath.insert(object, ['1','2'], 1); -objectPath.insert(object, 1, 1); -objectPath.insert(object, [1,2], 1); -objectPath.insert(object, '1.2', 1, 2); -objectPath.insert(object, ['1.2'], 1, 6); - +/// + +import ObjectPath = require('object-path'); + +var + object = { + one: 1, + two: { + three: 3, + four: ['4'] + } + }, + array: any[] = [], + Null:any = null; + +var obj = ObjectPath(object); + +obj.del(array); +obj.coalesce([1,2]); +obj.ensureExists('1.2', 1); +obj.push(1, 'value'); +obj.get(array); +obj.set(array, 'value'); +obj.insert(1, 10); + +objectPath.del(array) === ['12']; +objectPath.del(object) === object; +objectPath.del(object) === object; +obj.del() === object; + +objectPath.has(object, ['1','2','3']) === true; +objectPath.has(object, ['1.2.3']) === false; +objectPath.has(object, [1,2,3]) === true; +objectPath.has(object, 1) === false; +objectPath.has() === false; + +objectPath.del() === void 0; +objectPath.del(object, ['1','2','3']); +objectPath.del(object, [1,2,3]); +objectPath.del(object, 1); +objectPath.del(object, 'one').one === 1; +obj.del('one').one === 1; + +objectPath.coalesce(object, ['1','2']) === void 0; +objectPath.coalesce(object, ['1',['2','1']]) === void 0; +objectPath.coalesce(object, ['1',['2','1']], 1) === 1; +objectPath.coalesce(object, [1,1], 1) === 1; +objectPath.coalesce(object, >[1,[1,1]], 1) === 1; +obj.coalesce(>[1,[1,1]], 1) === 1; + +objectPath.ensureExists(object, '1.2', 2); +objectPath.ensureExists(object, 1, 2); +objectPath.ensureExists(object, [1,2], 2); +objectPath.ensureExists(object, ['1','2'], 2); +objectPath.ensureExists(object, ['1','2'], 2) === 3; +objectPath.ensureExists(object, ['1','2'], 2) === [[]]; +obj.ensureExists(['1','2'], 2) === [[]]; + +objectPath.push(object, 1, 1,2,3,4); +objectPath.push(object, 1, 1,'2', 3, false); +objectPath.push(object, 'one.four', 1,'2', 3, false); +objectPath.push(object, ['one','two'], [1,'2', 3, false]); +obj.push(['one','two'], [1,'2', 3, false]); + +objectPath.get(array) === array; +objectPath.get(Null) === Null; +objectPath.get() === void 0; +objectPath.get(object, 'one') === 1; +objectPath.get(object, ['two','three']) === 3; +objectPath.get(object, ['three'], 3) === 3; +objectPath.get(object, 'three', 3) === 3; +objectPath.get(object, 0, 3) === 3; +objectPath.get(object, 0, '3') === '3'; +objectPath.get(object, 0, ['1','2']) === ['1','2']; +objectPath.get(object, 0) === 10; +obj.get(0) === 10; + +objectPath.set(object, '1.2', true); +objectPath.set(object, ['1','2'], true); +objectPath.set(object, [1, 2], true); +objectPath.set(object, '1.2', true, true); +objectPath.set(object, '1.2', true, false); +objectPath.set(object, '1.2', true, false) === ['string']; +objectPath.set(object, '1.2', true, false) === object; +obj.set('1.2', true, false) === object; + +objectPath.insert(object, '1.2', 1); +objectPath.insert(object, ['1','2'], 1); +objectPath.insert(object, 1, 1); +objectPath.insert(object, [1,2], 1); +objectPath.insert(object, '1.2', 1, 2); +objectPath.insert(object, ['1.2'], 1, 6); +obj.insert(['1.2'], 1, 6); + diff --git a/object-path/object-path.d.ts b/object-path/object-path.d.ts index fe38f87028..711a305dc4 100644 --- a/object-path/object-path.d.ts +++ b/object-path/object-path.d.ts @@ -1,238 +1,470 @@ -// Type definitions for objectPath v0.6.0 -// Project: https://github.com/mariocasciaro/object-path -// Definitions by: Paulo Cesar -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare var objectPath: objectPath.IObjectPathStatic; - -declare module objectPath { - - interface IStringArray { - [index: number]: string; - } - - interface INumberArray { - [index: number]: number; - } - - interface IObjectPathStatic { - /*======== Del =========*/ - - /** - * Deletes a member from object or array - * @param {object} object - * @param {string[]|string} path - * @return object - */ - del(object: T, path: IStringArray): T; - /** - * @see objectPath.del - */ - del(object: T, path: INumberArray): T; - /** - * @see objectPath.del - */ - del(object: T, path: number): T; - /** - * @see objectPath.del - */ - del(object: T, path: string): T; - /** - * @see objectPath.del - */ - del(object: T): T; - /** - * @see objectPath.del - */ - del():void; - - /*======== Get =========*/ - /** - * Get a path from an object - * @param {object} object - * @param {string|string[]|number|number[]} path - * @param {*} [defaultValue=undefined] - */ - get(object: T, path: string, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T, path: IStringArray, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T, path: number, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T, path: INumberArray, defaultValue?: TResult): TResult; - /** - * @see objectPath.get - */ - get(object: T): T; - /** - * @see objectPath.get - */ - get():void; - - /*======== Set =========*/ - /** - * Set a path to a value - * @param {object} object - * @param {string|string[]|number|number[]} path - * @param {*} value - * @param {boolean} [doNotReplace=false] - * @return Any existing value on the path if any - */ - set(object: T, path: string, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T, path: number, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting; - /** - * @see objectPath.set - */ - set(object: T): T; - /** - * @see objectPath.set - */ - set():void; - - /*======== Push =========*/ - /** - * Create (if path isn't an array) and push the value to it. Can push unlimited number of values - * @param {object} object - */ - push(object: T, path: INumberArray, ...args:any[]):void; - /** - * @see objectPath.push - */ - push(object: T, path: IStringArray, ...args:any[]):void; - /** - * @see objectPath.push - */ - push(object: T, path: number, ...args:any[]):void; - /** - * @see objectPath.push - */ - push(object: T, path: string, ...args:any[]):void; - /** - * @see objectPath.push - */ - push():void; - - /*======== Coalesce =========*/ - /** - * Get the first non undefined property - * @param {object} object - * @param {string[]|string[][]|number[]|number[][]} paths - * @param {*} defaultValue - * @return {*} - */ - coalesce(object: T, paths: IStringArray, defaultValue?: any):TResult; - /** - * @see objectPath.coalesce - */ - coalesce(object: T, paths: INumberArray, defaultValue?: any):TResult; - /** - * @see objectPath.coalesce - */ - coalesce(object: T, paths: IStringArray[], defaultValue?: any):TResult; - /** - * @see objectPath.coalesce - */ - coalesce(object: T, paths: INumberArray[], defaultValue?: any):TResult; - - /*======== Empty =========*/ - /** - * Empty a path. Arrays are set to length 0, objects have all elements deleted, strings - * are set to empty, numbers to 0, everything else is set to null - * @param {object} object - * @param {string|string[]|number[]} path - */ - empty(object: T, path: string):TResult; - /** - * @see objectPath.empty - */ - empty(object: T, path: INumberArray):TResult; - /** - * @see objectPath.empty - */ - empty(object: T, path: IStringArray):TResult; - /** - * @see objectPath.empty - */ - empty(object: T, path: number):TResult; - /** - * @see objectPath.empty - */ - empty(object: T):T; - /** - * @see objectPath.empty - */ - empty():void; - - /*======== EnsureExists =========*/ - /** - * Set a value if it doesn't exist, do nothing if it does - * @param {object} object - * @param {string|string[]|number|number[]} path - */ - ensureExists(object: T, path: string, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T, path: number, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T, path: INumberArray, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T, path: IStringArray, value: any):TResult; - /** - * @see objectPath.ensureExists - */ - ensureExists(object: T): T; - /** - * @see objectPath.ensureExists - */ - ensureExists():void; - - /*======== Insert =========*/ - /** - * Insert an item in an array path - * @param {object} object - * @param {string|string[]|number|number[]} path - * @param {*} value - * @param {number} [at=0] - */ - insert(object: T, path: string, value: any, at?: number):void; - /** - * @see objectPath.insert - */ - insert(object: T, path: INumberArray, value: any, at?: number):void; - /** - * @see objectPath.insert - */ - insert(object: T, path: IStringArray, value: any, at?: number):void; - /** - * @see objectPath.insert - */ - insert(object: T, path: number, value: any, at?: number):void; - } - -} - -declare module 'objectPath' { - export = objectPath; +// Type definitions for objectPath v0.9.x +// Project: https://github.com/mariocasciaro/object-path +// Definitions by: Paulo Cesar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var objectPath: objectPath.IObjectPathStatic; + +declare module objectPath { + + interface IStringArray { + [index: number]: string; + } + + interface INumberArray { + [index: number]: number; + } + + interface IObjectPathStatic { + /** + * Binds an object + */ + (object: T): IObjectPathBound; + + /*======== Del =========*/ + + /** + * Deletes a member from object or array + * @param {object} object + * @param {string[]|string} path + * @return object + */ + del(object: T, path: IStringArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: INumberArray): T; + /** + * @see objectPath.del + */ + del(object: T, path: number): T; + /** + * @see objectPath.del + */ + del(object: T, path: string): T; + /** + * @see objectPath.del + */ + del(object: T): T; + /** + * @see objectPath.del + */ + del():void; + + /*======== Has =========*/ + /** + * Tests path existence + * @param {object} object + * @param {string[]|string} path + * @return object + */ + has(object: T, path: IStringArray): boolean; + /** + * @see objectPath.has + */ + has(object: T, path: INumberArray): boolean; + /** + * @see objectPath.has + */ + has(object: T, path: string): boolean; + /** + * @see objectPath.has + */ + has(object: T, path: number): boolean; + /** + * @see objectPath.has + */ + has(object: T): boolean; + /** + * @see objectPath.has + */ + has(): boolean; + + /*======== Get =========*/ + /** + * Get a path from an object + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} [defaultValue=undefined] + */ + get(object: T, path: string, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: IStringArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: number, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T, path: INumberArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(object: T): T; + /** + * @see objectPath.get + */ + get():void; + + /*======== Set =========*/ + /** + * Set a path to a value + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {boolean} [doNotReplace=false] + * @return Any existing value on the path if any + */ + set(object: T, path: string, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: number, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: IStringArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T, path: INumberArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(object: T): T; + /** + * @see objectPath.set + */ + set():void; + + /*======== Push =========*/ + /** + * Create (if path isn't an array) and push the value to it. Can push unlimited number of values + * @param {object} object + */ + push(object: T, path: INumberArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: IStringArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: number, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(object: T, path: string, ...args:any[]):void; + /** + * @see objectPath.push + */ + push():void; + + /*======== Coalesce =========*/ + /** + * Get the first non undefined property + * @param {object} object + * @param {string[]|string[][]|number[]|number[][]} paths + * @param {*} defaultValue + * @return {*} + */ + coalesce(object: T, paths: IStringArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: IStringArray[], defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(object: T, paths: INumberArray[], defaultValue?: any):TResult; + + /*======== Empty =========*/ + /** + * Empty a path. Arrays are set to length 0, objects have all elements deleted, strings + * are set to empty, numbers to 0, everything else is set to null + * @param {object} object + * @param {string|string[]|number[]} path + */ + empty(object: T, path: string):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: INumberArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: IStringArray):TResult; + /** + * @see objectPath.empty + */ + empty(object: T, path: number):TResult; + /** + * @see objectPath.empty + */ + empty(object: T):T; + /** + * @see objectPath.empty + */ + empty():void; + + /*======== EnsureExists =========*/ + /** + * Set a value if it doesn't exist, do nothing if it does + * @param {object} object + * @param {string|string[]|number|number[]} path + */ + ensureExists(object: T, path: string, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: number, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: INumberArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T, path: IStringArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(object: T): T; + /** + * @see objectPath.ensureExists + */ + ensureExists():void; + + /*======== Insert =========*/ + /** + * Insert an item in an array path + * @param {object} object + * @param {string|string[]|number|number[]} path + * @param {*} value + * @param {number} [at=0] + */ + insert(object: T, path: string, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: INumberArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: IStringArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(object: T, path: number, value: any, at?: number):void; + } + + interface IObjectPathBound { + /*======== Del =========*/ + + /** + * @see objectPath.ensureExists + */ + del(path: IStringArray): T; + /** + * @see objectPath.del + */ + del(path: INumberArray): T; + /** + * @see objectPath.del + */ + del(path: number): T; + /** + * @see objectPath.del + */ + del(path: string): T; + /** + * @see objectPath.del + */ + del(): T; + + /*======== Has =========*/ + /** + * @see objectPath.ensureExists + */ + has(path: IStringArray): boolean; + /** + * @see objectPath.has + */ + has(path: INumberArray): boolean; + /** + * @see objectPath.has + */ + has(path: string): boolean; + /** + * @see objectPath.has + */ + has(path: number): boolean; + /** + * @see objectPath.has + */ + has(): boolean; + + /*======== Get =========*/ + /** + * @see objectPath.ensureExists + */ + get(path: string, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(path: IStringArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(path: number, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(path: INumberArray, defaultValue?: TResult): TResult; + /** + * @see objectPath.get + */ + get(): T; + + /*======== Set =========*/ + /** + * @see objectPath.ensureExists + */ + set(path: string, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(path: number, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(path: IStringArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(path: INumberArray, value: any, doNotReplace?:boolean): TExisting; + /** + * @see objectPath.set + */ + set(): T; + + /*======== Push =========*/ + /** + * @see objectPath.ensureExists + */ + push(path: INumberArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(path: IStringArray, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(path: number, ...args:any[]):void; + /** + * @see objectPath.push + */ + push(path: string, ...args:any[]):void; + /** + * @see objectPath.push + */ + push():void; + + /*======== Coalesce =========*/ + /** + * @see objectPath.ensureExists + */ + coalesce(paths: IStringArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(paths: INumberArray, defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(paths: IStringArray[], defaultValue?: any):TResult; + /** + * @see objectPath.coalesce + */ + coalesce(paths: INumberArray[], defaultValue?: any):TResult; + + /*======== Empty =========*/ + /** + * @see objectPath.ensureExists + */ + empty(path: string):TResult; + /** + * @see objectPath.empty + */ + empty(path: INumberArray):TResult; + /** + * @see objectPath.empty + */ + empty(path: IStringArray):TResult; + /** + * @see objectPath.empty + */ + empty(path: number):TResult; + /** + * @see objectPath.empty + */ + empty():T; + + /*======== EnsureExists =========*/ + /** + * @see objectPath.ensureExists + */ + ensureExists(path: string, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(path: number, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(path: INumberArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(path: IStringArray, value: any):TResult; + /** + * @see objectPath.ensureExists + */ + ensureExists(): T; + + /*======== Insert =========*/ + /** + * @see objectPath.insert + */ + insert(path: string, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(path: INumberArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(path: IStringArray, value: any, at?: number):void; + /** + * @see objectPath.insert + */ + insert(path: number, value: any, at?: number):void; + } +} + +// browser version +declare module 'objectPath' { + export = objectPath; +} + +// node version +declare module 'object-path' { + export = objectPath; } \ No newline at end of file diff --git a/on-finished/on-finished-tests.ts b/on-finished/on-finished-tests.ts new file mode 100644 index 0000000000..c3956ac6b0 --- /dev/null +++ b/on-finished/on-finished-tests.ts @@ -0,0 +1,16 @@ +/// +/// + +import events = require('events'); +import onFinished = require('on-finished'); + +function test_finished() { + + var e = new events.EventEmitter(); + + var ret: NodeJS.EventEmitter = onFinished(e, () => { + //callback + }); + + var finished: boolean = onFinished.isFinished(e); +} diff --git a/on-finished/on-finished.d.ts b/on-finished/on-finished.d.ts new file mode 100644 index 0000000000..0ca4f22865 --- /dev/null +++ b/on-finished/on-finished.d.ts @@ -0,0 +1,18 @@ +// Type definitions for on-finished v2.2.0 +// Project: https://github.com/jshttp/on-finished +// Definitions by: Honza Dvorsky +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + + +declare module 'on-finished' { + + function onFinished(msg:NodeJS.EventEmitter, listener:Function): NodeJS.EventEmitter; + + module onFinished { + export function isFinished(msg:NodeJS.EventEmitter):boolean; + } + + export = onFinished; +} diff --git a/on-headers/on-headers-tests.ts b/on-headers/on-headers-tests.ts new file mode 100644 index 0000000000..11f33c4ef0 --- /dev/null +++ b/on-headers/on-headers-tests.ts @@ -0,0 +1,20 @@ +/// + +import http = require('http') +import onHeaders = require('on-headers') + +http.createServer(onRequest) + .listen(3000); + +function onRequest(req: http.ServerRequest, res: http.ServerResponse) { + onHeaders(res, addPoweredBy); + res.setHeader('Content-Type', 'text/plain') + res.end('hello!'); +} + +function addPoweredBy(): void { + // set if not set by end of request + if (!this.getHeader('X-Powered-By')) { + this.setHeader('X-Powered-By', 'Node.js'); + } +} diff --git a/on-headers/on-headers.d.ts b/on-headers/on-headers.d.ts new file mode 100644 index 0000000000..bf873fd826 --- /dev/null +++ b/on-headers/on-headers.d.ts @@ -0,0 +1,33 @@ +// Type definitions for serve-favicon 2.1.6 +// Project: https://github.com/jshttp/on-headers +// Definitions by: John Jeffery +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "on-headers" { + import http = require("http"); + + /** + * This will add the listener to fire when headers are emitted for res. + * The listener is passed the response object as its context (this). + * Headers are considered emitted only once, right before they + * are sent to the client. + * + * When this is called multiple times on the same res, the listeners + * are fired in the reverse order they were added. + * + * @param res HTTP server response object + * @param listener Function to call prior to headers being emitted, + * the response object is passed as this context. + */ + function onHeaders(res: http.ServerResponse, listener: Function):void; + + // Note that this definition might be able to be improved in a future + // version of typescript. At the moment it is not possible to declare + // the type of the 'this' context for a function, but it might be included + // in a future typescript version. + // https://github.com/Microsoft/TypeScript/issues/229 + + export = onHeaders; +} \ No newline at end of file diff --git a/onsenui/onsenui-tests.ts b/onsenui/onsenui-tests.ts new file mode 100644 index 0000000000..58b72da6ea --- /dev/null +++ b/onsenui/onsenui-tests.ts @@ -0,0 +1,216 @@ +/// + +function onsStatic(): void { + ons.ready(function(): void { + alert('Ready!'); + }); + ons.bootstrap(); + ons.enableAutoStatusBarFill(); + ons.disableAutoStatusBarFill(); + ons.findParentComponentUntil('ons-page'); + ons.findComponent('.class1'); + ons.setDefaultDeviceBackButtonListener(null); + ons.disableDeviceBackButtonHandler(); + ons.enableDeviceBackButtonHandler(); + ons.isReady(); + var content: HTMLElement = document.getElementById('#my-content'); + content.innerHTML = 'Test Button'; + ons.compile(content); + ons.isWebView(); + ons.createAlertDialog('myPage.html'); + ons.createDialog('myPage.html'); + ons.createPopover('myPage.html'); + + var options: alertOptions = { + message: 'text message' + }; + ons.notification.alert(options); + ons.notification.confirm(options); + ons.notification.prompt(options); + + var potrait: boolean = ons.orientation.isPortrait(); + var isLandscape: boolean = ons.orientation.isLandscape(); + ons.orientation.on('eventName', null); + ons.orientation.once('eventName', null); + ons.orientation.off('eventName', null); + + var web: boolean = ons.platform.isWebView(); + var ios: boolean = ons.platform.isIOS(); + var iPhone: boolean = ons.platform.isIPhone(); + var iPad: boolean = ons.platform.isIPad(); + var blackBerry: boolean = ons.platform.isBlackBerry(); + var opera: boolean = ons.platform.isOpera(); + var firefox: boolean = ons.platform.isFirefox(); + var safari: boolean = ons.platform.isSafari(); + var chrome: boolean = ons.platform.isChrome(); + var ie: boolean = ons.platform.isIE(); + var ios7above: boolean = ons.platform.isIOS7above(); + +} + +function onsPage(page: PageView): void { + var DBBHandler: any = page.getDeviceBackButtonHandler(); +} + +function onsCarousel(carousel: CarouselView): void { + carousel.next(); + carousel.prev(); + carousel.first(); + carousel.last(); + carousel.setSwipeable(true); + var swipeable: boolean = carousel.isSwipeable(); + carousel.setActiveCarouselItemIndex(0); + carousel.getActiveCarouselItemIndex(); + var autoScrollEnabled: boolean = carousel.isAutoScrollEnabled(); + carousel.setAutoScrollEnabled(true); + carousel.getAutoScrollRatio(); + carousel.setOverscrollable(true); + var overscrollable: boolean = carousel.isOverscrollable(); + carousel.refresh(); + var disabled: boolean = carousel.isDisabled(); + carousel.setDisabled(false); + carousel.on('eventName', null); + carousel.once('eventName', null); + carousel.off('eventName', null); +} + +function onsPullHook(pullHook: PullHookView): void { + pullHook.setDisabled(false); + var disabled: boolean = pullHook.isDisabled(); + pullHook.setHeight(15); + pullHook.setThresholdHeight(4); + pullHook.on('eventName', null); + pullHook.once('eventName', null); + pullHook.off('eventName', null); +} + +function onsSplitView(splitViewVar: SplitView): void { + splitViewVar.setMainPage('myPage.html'); + splitViewVar.setSecondaryPage('myPage2.html'); + splitViewVar.update(); + splitViewVar.on('eventName', null); + splitViewVar.once('eventName', null); + splitViewVar.off('eventName', null); +} + +function onsAlertDialog(alertDialog: AlertDialogView): void { + var options: dialogOptions = { + animation: 'default' + }; + alertDialog.show(options); + alertDialog.hide(options); + var shown: boolean = alertDialog.isShown(); + alertDialog.destroy(); + alertDialog.setCancelable(true); + var cancelable: boolean = alertDialog.isCancelable(); + alertDialog.setDisabled(false); + var disabled: boolean = alertDialog.isDisabled(); + alertDialog.on('eventName', null); + alertDialog.once('eventName', null); + alertDialog.off('eventName', null); +} + +function onsDialog(dialog: DialogView): void { + var options: dialogOptions = { + animation: 'default' + }; + dialog.show(options); + dialog.hide(options); + var shown: boolean = dialog.isShown(); + dialog.destroy(); + var DBBHandler: any = dialog.getDeviceBackButtonHandler(); + dialog.setCancelable(true); + var cancelable: boolean = dialog.isCancelable(); + dialog.setDisabled(false); + var disabled: boolean = dialog.isDisabled(); + dialog.on('eventName', null); + dialog.once('eventName', null); + dialog.off('eventName', null); +} + +function onsButton(button: ButtonView): void { + button.startSpin(); + button.stopSpin(); + var spinning: boolean = button.isSpinning(); + button.setSpinAnimation('slide-left'); + button.setDisabled(false); + var disabled: boolean = button.isDisabled(); +} + +function onsSwitch(switchVar: SwitchView): void { + var checked: boolean = switchVar.isChecked(); + switchVar.setChecked(true); + var checkbox: HTMLElement = switchVar.getCheckboxElement(); + switchVar.on('eventName', null); + switchVar.once('eventName', null); + switchVar.off('eventName', null); +} + +function onsModal(modal: ModalView): void { + modal.toggle(); + modal.show(); + modal.hide(); + var DBBHandler: boolean = modal.getDeviceBackButtonHandler(); +} + +function onsNavigator(navigator: NavigatorView): void { + var options: navigatorOptions = { + animation: 'slide' + }; + navigator.pushPage('myPage.html'); + navigator.insertPage(2, 'myPage2.html'); + navigator.popPage(); + navigator.resetToPage('myPage.html'); + var currentPage: any = navigator.getCurrentPage(); + var pages: objectArray = navigator.getPages(); + var DBBHandler: any = navigator.getDeviceBackButtonHandler(); + navigator.on('eventName', null); + navigator.once('eventName', null); + navigator.off('eventName', null); +} + +function onsSlidingMenu(slidingMenu: SlidingMenuView): void { + var options: slidingMenuOptions = { + closeMenu: true + }; + slidingMenu.setMainPage('myPage.html', options); + slidingMenu.setMenuPage('myMenu.html', options); + slidingMenu.openMenu(options); + slidingMenu.closeMenu(options); + slidingMenu.toggleMenu(options); + var opened: boolean = slidingMenu.isMenuOpened(); + var DBBHandler: any = slidingMenu.getDeviceBackButtonHandler(); + slidingMenu.setSwipeable(true); + slidingMenu.on('eventName', null); + slidingMenu.once('eventName', null); + slidingMenu.off('eventName', null); +} + +function onsTabbar(tabBar: TabbarView): void { + var options: tabbarOptions = { + keepPage: true + }; + tabBar.setActiveTab(2, options); + var activeTab: number = tabBar.getActiveTab(); + tabBar.loadPage('myPage.html'); + tabBar.on('eventName', null); + tabBar.once('eventName', null); + tabBar.off('eventName', null); +} + +function onsPopover(popover: PopoverView): void { + var options: popoverOptions = { + animation: 'fade' + } + popover.show('#element5', options); + popover.hide(options); + var shown: boolean = popover.isShown(); + popover.destroy(); + popover.setCancelable(true); + var cancelable: boolean = popover.isCancelable(); + popover.setDisabled(true); + var disabled: boolean = popover.isDisabled(); + popover.on('eventName', null); + popover.once('eventName', null); + popover.off('eventName', null); +} diff --git a/onsenui/onsenui.d.ts b/onsenui/onsenui.d.ts new file mode 100644 index 0000000000..287c8e2f51 --- /dev/null +++ b/onsenui/onsenui.d.ts @@ -0,0 +1,1017 @@ +// Type definitions for Onsen UI +// Project: http://onsen.io +// Definitions by: Fran Dios +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +// Some useful types +interface stringArray { + [index: number]: string; +} + +interface objectArray { + [index: number]: any; +} + + +/** + * @description Should be used as root component of each page. The content inside page component is scrollable + */ +interface PageView { + /** + * @return {Object} Device back button handler + * @description Get the associated back button handler. This method may return null if no handler is assigned + */ + getDeviceBackButtonHandler(): any; +} + +/** + * @description Carousel component + */ +interface CarouselView { + /** + * @description Show next ons-carousel item + */ + next(): void; + /** + * @description Show previous ons-carousel item + */ + prev(): void; + /** + * @description Show first ons-carousel item + */ + first(): void; + /** + * @description Show last ons-carousel item + */ + last(): void; + /** + * @param {Booelan} swipeable If value is true the carousel will be swipeable + * @description Set whether the carousel is swipeable or not + */ + setSwipeable(swipeable: boolean): void; + /** + * @return {Boolean} true if the carousel is swipeable + * @description Returns whether the carousel is swipeable or not + */ + isSwipeable(): boolean; + /** + * @param {Number} index The index that the carousel should be set to + * @description Specify the index of the ons-carousel-item to show + */ + setActiveCarouselItemIndex(index: number): void; + /** + * @return {Number} The current carousel item index + * @description Returns the index of the currently visible ons-carousel-item + */ + getActiveCarouselItemIndex(): number; + /** + * @param {Boolean} enabled If true auto scroll will be enabled + * @description Enable or disable "auto-scroll" attribute + */ + setAutoScrollEnabled(enabled: boolean): void; + /** + * @return {Boolean} true if auto scroll is enabled + * @description Returns whether the "auto-scroll" attribute is set or not + */ + isAutoScrollEnabled(): boolean; + /** + * @param {Number} ratio The desired ratio + * @description Set the auto scroll ratio. Must be a value between 0.0 and 1.0 + */ + setAutoScrollRatio(ratio: number): void; + /** + * @return {Number} The current auto scroll ratio + * @description Returns the current auto scroll ratio + */ + getAutoScrollRatio(): number; + /** + * @param {Boolean} overscrollable If true the carousel will be overscrollable + * @description Set whether the carousel is overscrollable or not + */ + setOverscrollable(overscrollable: boolean): void; + /** + * @return {Boolean} Whether the carousel is overscrollable or not + * @description Returns whether the carousel is overscrollable or not + */ + isOverscrollable(): boolean; + /** + * @description Update the layout of the carousel. Used when adding ons-carousel-items dynamically or to automatically adjust the size + */ + refresh(): void; + /** + * @return {Boolean} Whether the carousel is disabled or not + * @description Returns whether the dialog is disabled or enabled + */ + isDisabled(): boolean; + /** + * @param {Boolean} disabled If true the carousel will be disabled + * @description Disable or enable the dialog + */ + setDisabled(disabled: boolean): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description Component that adds "pull-to-refresh" to an element + */ +interface PullHookView { + /** + * @param {Boolean} disabled If true the pull hook will be disabled + * @description Disable or enable the component + */ + setDisabled(disabled: boolean): void; + /** + * @return {Boolean} true if the pull hook is disabled + * @description Returns whether the component is disabled or enabled + */ + isDisabled(): boolean; + /** + * @param {Number} height Desired height + * @description Specify the height + */ + setHeight(height: number): void; + /** + * @param {Number} thresholdHeight Desired threshold height + * @description Specify the threshold height + */ + setThresholdHeight(thresholdHeight: number): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description Divides the screen into a left and right section + */ +interface SplitView { + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an + * @description Show the page specified in pageUrl in the right section + */ + setMainPage(pageUrl: string): void; + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an + * @description Show the page specified in pageUrl in the left section + */ + setSecondaryPage(pageUrl: string): void; + /** + * @description Trigger an 'update' event and try to determine if the split behaviour should be changed + */ + update(): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface dialogOptions { + animation?: string; + callback?: any; +} + + +/** + * @modifier android Display an Android style alert dialog + * @description Alert dialog that is displayed on top of the current screen + */ +interface AlertDialogView { + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade", "slide" and "none" + * @param {Function} [options.callback] Function to execute after the dialog has been revealed + * @description Show the alert dialog + */ + show(options?: dialogOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade", "slide" and "none" + * @param {Function} [options.callback] Function to execute after the dialog has been hidden + * @description Hide the alert dialog + */ + hide(options?: dialogOptions): void; + /** + * @description Returns whether the dialog is visible or not + * @return {Boolean} true if the dialog is currently visible + */ + isShown(): boolean; + /** + * @description Destroy the alert dialog and remove it from the DOM tree + */ + destroy(): void; + /** + * @description Define whether the dialog can be canceled by the user or not + * @param {Boolean} cancelable If true the dialog will be cancelable + */ + setCancelable(cancelable: boolean): void; + /** + * @description Returns whether the dialog is cancelable or not + * @return {Boolean} true if the dialog is cancelable + */ + isCancelable(): boolean; + /** + * @description Disable or enable the alert dialog + * @param {Boolean} disabled If true the dialog will be disabled + */ + setDisabled(disabled: boolean): void; + /** + * @description Returns whether the dialog is disabled or enabled + * @return {Boolean} true if the dialog is disabled + */ + isDisabled(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description Dialog that is displayed on top of current screen + */ +interface DialogView { + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {Function} [options.callback] This function is called after the dialog has been revealed + * @description Show the dialog + */ + show(options?: dialogOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {Function} [options.callback] This functions is called after the dialog has been hidden + * @description Hide the dialog + */ + hide(options?: dialogOptions): void; + /** + * @description Returns whether the dialog is visible or not + * @return {Boolean} true if the dialog is visible + */ + isShown(): boolean; + /** + * @description Destroy the dialog and remove it from the DOM tree + */ + destroy(): void; + /** + * @return {Object} Device back button handler + * @description Retrieve the back button handler for overriding the default behavior + */ + getDeviceBackButtonHandler(): any; + /** + * @param {Boolean} cancelable If true the dialog will be cancelable + * @description Define whether the dialog can be canceled by the user or not + */ + setCancelable(cancelable: boolean): void; + /** + * @description Returns whether the dialog is cancelable or not + * @return {Boolean} true if the dialog is cancelable + */ + isCancelable(): boolean; + /** + * @description Disable or enable the dialog + * @param {Boolean} disabled If true the dialog will be disabled + */ + setDisabled(disabled: boolean): void; + /** + * @description Returns whether the dialog is disabled or enabled + * @return {Boolean} true if the dialog is disabled + */ + isDisabled(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @modifier outline Button with outline and transparent background + * @modifier light Button that doesn't stand out + * @modifier quiet Button with no outline and or background + * @modifier cta Button that really stands out + * @modifier large Large button that covers the width of the screen + * @modifier large--quiet Large quiet button + * @modifier large--cta Large call to action button + * @description Button component. If you want to place a button in a toolbar, use ons-toolbar-button or ons-back-button instead + */ +interface ButtonView { + /** + * @description Show spinner on the button + */ + startSpin(): void; + /** + * @description Remove spinner from button + */ + stopSpin(): void; + /** + * @return {Boolean} true if the button is spinning + * @description Return whether the spinner is visible or not + */ + isSpinning(): boolean; + /** + * @description Set spin animation. Possible values are "slide-left" (default), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in" + * @param {String} animation Animation name + */ + setSpinAnimation(animation: string): void; + /** + * @description Disable or enable the button + */ + setDisabled(disabled: boolean): void; + /** + * @return {Boolean} true if the button is disabled + * @description Returns whether the button is disabled or enabled + */ + isDisabled(): boolean; +} + +/** + * @description Switch component + */ +interface SwitchView { + /** + * @return {Boolean} true if the switch is on + * @description Returns true if the switch is ON + */ + isChecked(): boolean; + /** + * @param {Boolean} checked If true the switch will be set to on + * @description Set the value of the switch. isChecked can be either true or false + */ + setChecked(checked: boolean): void; + /** + * @return {HTMLElement} The underlying checkbox element + * @description Get inner input[type=checkbox] element + */ + getCheckboxElement(): HTMLElement; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +/** + * @description + * Modal component that masks current screen + * Underlying components are not subject to any events while the modal component is shown + */ +interface ModalView { + /** + * @description Toggle modal visibility + */ + toggle(): void; + /** + * @description Show modal + */ + show(): void; + /** + * @description Hide modal + */ + hide(): void; + /** + * @return {Object} Device back button handler + * @description Retrieve the back button handler + */ + getDeviceBackButtonHandler(): any; +} + +interface navigatorOptions { + animation?: string; + onTransitionEnd?: any; +} + +/** + * @description A component that provides page stack management and navigation. This component does not have a visible content + */ +interface NavigatorView { + /** + * @param {String} pageUrl Page URL. Can be either a HTML document or a <ons-template> + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none" + * @param {Function} [options.onTransitionEnd] Function that is called when the transition has ended + * @description Pushes the specified pageUrl into the page stack + */ + pushPage(pageUrl: string, options?: navigatorOptions): void; + /** + * @param {Number} index The index where it should be inserted + * @param {String} pageUrl Page URL. Can be either a HTML document or a <ons-template> + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none" + * @description Insert the specified pageUrl into the page stack with specified index + */ + insertPage(index: number, pageUrl: string, options?: navigatorOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.onTransitionEnd] Function that is called when the transition has ended + * @description Pops the current page from the page stack. The previous page will be displayed + */ + popPage(options?: navigatorOptions): void; + /** + * @param {String} pageUrl Page URL. Can be either a HTML document or an <ons-template> + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none" + * @param {Function} [options.onTransitionEnd] Function that is called when the transition has ended + * @description Clears page stack and adds the specified pageUrl to the page stack + */ + resetToPage(pageUrl: string, options?: navigatorOptions): void; + /** + * @return {Object} Current page object + * @description Get current page's navigator item. Use this method to access options passed by pushPage() or resetToPage() method + */ + getCurrentPage(): any; + /** + * @return {List} List of page objects + * @description Retrieve the entire page stack of the navigator + */ + getPages(): objectArray; + /** + * @return {Object} Device back button handler + * @description Retrieve the back button handler for overriding the default behavior + */ + getDeviceBackButtonHandler(): any; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface slidingMenuOptions { + closeMenu?: boolean; + callback?: any; +} + +/** + * @description Component for sliding UI where one page is overlayed over another page. The above page can be slided aside to reveal the page behind + */ +interface SlidingMenuView { + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an <ons-template> + * @param {Object} [options] Parameter object + * @param {Boolean} [options.closeMenu] If true the menu will be closed + * @param {Function} [options.callback] Function that is executed after the page has been set + * @description Show the page specified in pageUrl in the main contents pane + */ + setMainPage(pageUrl: string, options?: slidingMenuOptions): void; + /** + * @param {String} pageUrl Page URL. Can be either an HTML document or an <ons-template> + * @param {Object} [options] Parameter object + * @param {Boolean} [options.closeMenu] If true the menu will be closed after the menu page has been set + * @param {Function} [options.callback] This function will be executed after the menu page has been set + * @description Show the page specified in pageUrl in the side menu pane + */ + setMenuPage(pageUrl: string, options?: slidingMenuOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.callback] This function will be called after the menu has been opened + * @description Slide the above layer to reveal the layer behind + */ + openMenu(options?: slidingMenuOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.callback] This function will be called after the menu has been closed + * @description Slide the above layer to hide the layer behind + */ + closeMenu(options?: slidingMenuOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {Function} [options.callback] This function will be called after the menu has been opened or closed + * @description Slide the above layer to reveal the layer behind if it is currently hidden, otherwise, hide the layer behind + */ + toggleMenu(options?: slidingMenuOptions): void; + /** + * @return {Boolean} true if the menu is currently open + * @description Returns true if the menu page is open, otherwise false + */ + isMenuOpened(): boolean; + /** + * @return {Object} Device back button handler + * @description Retrieve the back-button handler + */ + getDeviceBackButtonHandler(): any; + /** + * @param {Boolean} swipeable If true the menu will be swipeable + * @description Specify if the menu should be swipeable or not + */ + setSwipeable(swipeable: boolean): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface tabbarOptions { + keepPage?: boolean; +} + +/** + * @description A component to display a tab bar on the bottom of a page. Used with ons-tab to manage pages using tabs + */ +interface TabbarView { + /** + * @param {Number} index Tab index + * @param {Object} [options] Parameter object + * @param {Boolean} [options.keepPage] If true the page will not be changed + * @param {String} [options.animation] Animation name. Available animations are "fade" and "none" + * @return {Boolean} true if the change was successful + * @description Show specified tab page. Animations and other options can be specified by the second parameter + */ + setActiveTab(index: number, options?: tabbarOptions): boolean; + /** + * @return {Number} The index of the currently active tab + * @description Returns tab index on current active tab. If active tab is not found, returns -1 + */ + getActiveTab(): number; + /** + * @param {String} url Page URL. Can be either an HTML document or an <ons-template> + * @description Displays a new page without changing the active index + */ + loadPage(url: string): void; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface popoverOptions { + animation?: string; +} + +/** + * @modifier android Display an Android style popover + * @description A component that displays a popover next to an element + */ +interface PopoverView { + /** + * @param {String|Event|HTMLElement} target Target element. Can be either a CSS selector, an event object or a DOM element + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade" and "none" + * @description Open the popover and point it at a target. The target can be either an event, a css selector or a DOM element + */ + show(target: any, options?: popoverOptions): void; + /** + * @param {Object} [options] Parameter object + * @param {String} [options.animation] Animation name. Available animations are "fade" and "none" + * @description Close the popover + */ + hide(options?: popoverOptions): void; + /** + * @return {Boolean} true if the popover is visible + * @description Returns whether the popover is visible or not + */ + isShown(): boolean; + /** + * @description Destroy the popover and remove it from the DOM tree + */ + destroy(): void; + /** + * @param {Boolean} cancelable If true the popover will be cancelable + * @description Set whether the popover can be canceled by the user when it is shown + */ + setCancelable(cancelable: boolean): void; + /** + * @return {Boolean} true if the popover is cancelable + * @description Returns whether the popover is cancelable or not + */ + isCancelable(): boolean; + /** + * @param {Boolean} disabled If true the popover will be disabled + * @description Disable or enable the popover + */ + setDisabled(disabled: boolean): void; + /** + * @return {Boolean} true if the popover is disabled + * @description Returns whether the popover is disabled or enabled + */ + isDisabled(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +//# Onsen Objects + +/** + * @description A global object that's used in Onsen UI. This object can be reached from the AngularJS scope + */ +interface onsStatic { + /** + * @description Method used to wait for app initialization. The callback will not be executed until Onsen UI has been completely initialized + * @param {Function} callback Function that executes after Onsen UI has been initialized + */ + ready(callback: any): void; + /** + * @description Initialize Onsen UI. Can be used to load Onsen UI without using the ng-app attribute from AngularJS + * @param {String} [moduleName] AngularJS module name + * @param {Array} [dependencies] List of AngularJS module dependencies + * @return {Object} An AngularJS module object + */ + bootstrap(moduleName?: string, dependencies?: objectArray): any; + /** + * @description Enable status bar fill feature on iOS7 and above + */ + enableAutoStatusBarFill(): void; + /** + * @description Disable status bar fill feature on iOS7 and above + */ + disableAutoStatusBarFill(): void; + /** + * @param {String} name Name of component, i.e. 'ons-page' + * @param {Object|jqLite|HTMLElement} [dom] $event, jqLite or HTMLElement object + * @return {Object} Component object. Will return null if no component was found + * @description Find parent component object of dom element + */ + findParentComponentUntil(name: string, dom?: any): any; + /** + * @param {String} selector CSS selector + * @param {HTMLElement} [dom] DOM element to search from + * @return {Object} Component object. Will return null if no component was found + * @description Find component object using CSS selector + */ + findComponent(selector: string, dom?: HTMLElement): any; + /** + * @param {Function} listener Function that executes when device back button is pressed + * @description Set default handler for device back button + */ + setDefaultDeviceBackButtonListener(listener: (eventObject: any) => any): void; + /** + * @description Disable device back button event handler + */ + disableDeviceBackButtonHandler(): void; + /** + * @description Enable device back button event handler + */ + enableDeviceBackButtonHandler(): void; + /** + * @return {Boolean} Will be true if Onsen UI is initialized + * @description Returns true if Onsen UI is initialized + */ + isReady(): boolean; + /** + * @param {HTMLElement} dom Element to compile + * @description Compile Onsen UI components + */ + compile(dom: HTMLElement): void; + /** + * @return {Boolean} Will be true if the app is running in Cordova + * @description Returns true if running inside Cordova + */ + isWebView(): boolean; + /** + * @param {String} page Page name. Can be either an HTML file or an containing a component + * @param {Object} [options] Parameter object + * @param {Object} [options.parentScope] Parent scope of the dialog. Used to bind models and access scope methods from the dialog + * @return {Promise} Promise object that resolves to the alert dialog component object + * @description Create a alert dialog instance from a template + */ + createAlertDialog(page: string): any; + /** + * @param {String} page Page name. Can be either an HTML file or an containing a component + * @param {Object} [options] Parameter object + * @param {Object} [options.parentScope] Parent scope of the dialog. Used to bind models and access scope methods from the dialog + * @return {Promise} Promise object that resolves to the dialog component object + * @description Create a dialog instance from a template + */ + createDialog(page: string): any; + /** + * @param {String} page Page name. Can be either an HTML file or an containing a component + * @param {Object} [options] Parameter object + * @param {Object} [options.parentScope] Parent scope of the dialog. Used to bind models and access scope methods from the dialog + * @return {Promise} Promise object that resolves to the popover component object + * @description Create a popover instance from a template + */ + createPopover(page: string): any; + + /** + * @description Utility methods to create different kinds of alert dialogs. There are three methods available: alert, confirm and prompt + */ + notification: onsNotification; + + /** + * @description Utility methods for orientation detection + */ + orientation: onsOrientation; + + /** + * @description Utility methods to detect current platform + */ + platform: onsPlatform; +} + + +interface alertOptions { + message?: string; + messageHTML?: string; + buttonLabel?: string; + buttonLabels?: stringArray; + primaryButtonIndex?: number; + cancelable?: boolean; + animation?: string; + title?: string; + modifier?: string; + callback?: any; +} + +interface onsNotification { + /** + * @param {Object} options Parameter object + * @param {String} [options.message] Alert message + * @param {String} [options.messageHTML] Alert message in HTML + * @param {String} [options.buttonLabel] Label for confirmation button. Default is "OK" + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {String} [options.title] Dialog title. Default is "Alert" + * @param {String} [options.modifier] Modifier for the dialog + * @param {Function} [options.callback] Function that executes after dialog has been closed + * @description + * Display an alert dialog to show the user a message + * The content of the message can be either simple text or HTML + * Must specify either message or messageHTML + */ + alert(options: alertOptions): void; + /** + * @param {Object} options Parameter object + * @param {String} [options.message] Confirmation question + * @param {String} [options.messageHTML] Dialog content in HTML + * @param {Array} [options.buttonLabels] Labels for the buttons. Default is ["Cancel", "OK"] + * @param {Number} [options.primaryButtonIndex] Index of primary button. Default is 1 + * @param {Boolean} [options.cancelable] Whether the dialog is cancelable or not. Default is false + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {String} [options.title] Dialog title. Default is "Confirm" + * @param {String} [options.modifier] Modifier for the dialog + * @param {Function} [options.callback] + * Function that executes after the dialog has been closed + * Argument for the function is the index of the button that was pressed or -1 if the dialog was canceled + * @description + * Display a dialog to ask the user for confirmation + * The default button labels are "Cancel" and "OK" but they can be customized + * Must specify either message or messageHTML + */ + confirm(options: alertOptions): void; + /** + * @param {Object} options Parameter object + * @param {String} [options.message] Prompt question + * @param {String} [options.messageHTML] Dialog content in HTML + * @param {String} [options.buttonLabel] Label for confirmation button. Default is "OK" + * @param {Number} [options.primaryButtonIndex] Index of primary button. Default is 1 + * @param {Boolean} [options.cancelable] Whether the dialog is cancelable or not. Default is false + * @param {String} [options.animation] Animation name. Available animations are "none", "fade" and "slide" + * @param {String} [options.title] Dialog title. Default is "Alert" + * @param {String} [options.modifier] Modifier for the dialog + * @param {Function} [options.callback] + * Function that executes after the dialog has been closed + * Argument for the function is the value of the input field or null if the dialog was canceled + * @description + * Display a dialog with a prompt to ask the user a question + * Must specify either message or messageHTML + */ + prompt(options: alertOptions): void; +} + +interface onsOrientation { + /** + * @return {Boolean} Will be true if the current orientation is portrait mode + * @description Returns whether the current screen orientation is portrait or not + */ + isPortrait(): boolean; + /** + * @return {Boolean} Will be true if the current orientation is landscape mode + * @description Returns whether the current screen orientation is landscape or not + */ + isLandscape(): boolean; + /** + * @description Add an event listener + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + on(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Add an event listener that's only triggered once + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + once(eventName: string, listener: (eventObject: any) => any): void; + /** + * @description Remove an event listener. If the listener is not specified all listeners for the event type will be removed + * @param {String} eventName Name of the event + * @param {Function} listener Function to execute when the event is triggered + */ + off(eventName: string, listener?: (eventObject: any) => any): void; +} + +interface onsPlatform { + /** + * @description Returns whether app is running in Cordova + * @return {Boolean} + */ + isWebView(): boolean; + + /** + * @description Returns whether the OS is iOS + * @return {Boolean} + */ + isIOS(): boolean; + + /** + * @description Returns whether the OS is Android + * @return {Boolean} + */ + isAndroid(): boolean; + + /** + * @description Returns whether the device is iPhone + * @return {Boolean} + */ + isIPhone(): boolean; + + /** + * @description Returns whether the device is iPad + * @return {Boolean} + */ + isIPad(): boolean; + + /** + * @description Returns whether the device is BlackBerry + * @return {Boolean} + */ + isBlackBerry(): boolean; + + /** + * @description Returns whether the browser is Opera + * @return {Boolean} + */ + isOpera(): boolean; + + /** + * @description Returns whether the browser is Firefox + * @return {Boolean} + */ + isFirefox(): boolean; + + /** + * @description Returns whether the browser is Safari + * @return {Boolean} + */ + isSafari(): boolean; + + /** + * @description Returns whether the browser is Chrome + * @return {Boolean} + */ + isChrome(): boolean; + + /** + * @description Returns whether the browser is Internet Explorer + * @return {Boolean} + */ + isIE(): boolean; + + /** + * @description Returns whether the iOS version is 7 or above + * @return {Boolean} + */ + isIOS7above(): boolean; +} + +declare var ons: onsStatic; diff --git a/passport-local/passport-local.d.ts b/passport-local/passport-local.d.ts index a2bec8daf7..2fc62dc7bf 100644 --- a/passport-local/passport-local.d.ts +++ b/passport-local/passport-local.d.ts @@ -13,6 +13,7 @@ declare module 'passport-local' { interface IStrategyOptions { usernameField?: string; passwordField?: string; + passReqToCallback?: boolean; } interface IStrategyOptionsWithRequest { @@ -30,6 +31,7 @@ declare module 'passport-local' { } interface VerifyFunction { + (req: express.Request, username: string, password: string, done: (error: any, user?: any, options?: IVerifyOptions) => void): void; (username: string, password: string, done: (error: any, user?: any, options?: IVerifyOptions) => void): void; } diff --git a/photoswipe/photoswipe-tests.ts b/photoswipe/photoswipe-tests.ts new file mode 100644 index 0000000000..79125bd05f --- /dev/null +++ b/photoswipe/photoswipe-tests.ts @@ -0,0 +1,209 @@ +/// + +function test_defaultUI() { + var items: PhotoSwipeUI_Default.Item[] = [ + { + src: "path/to/image.jpg", + w: 100, + h: 200, + specialProperty: true + }, + { + src: "path/to/image2.jpg", + w: 1000, + h: 2000, + specialProperty: false + } + ]; + + var options: PhotoSwipe.Options = { + index: 3, + getThumbBoundsFn: function(index) { + return {x: 100, y: 100, w: 100}; + }, + showAnimationDuration: 333, + hideAnimationDuration: 333, + showHideOpacity: false, + bgOpacity: 1, + spacing: 0.12, + allowNoPanText: true, + maxSpreadZoom: 2, + getDoubleTapZoom: function(isMouseClick, item) { + if (isMouseClick) { + return 1; + } else { + return item.initialZoomLevel < 0.7 ? 1 : 1.5; + } + }, + loop: true, + pinchToClose: true, + closeOnScroll: true, + closeOnVerticalDrag: true, + mouseUsed: false, + escKey: true, + arrowKeys: true, + history: true, + galleryUID: 3, + errorMsg: '
The image could not be loaded.
', + preload: [1, 1], + mainClass: "", + getNumItemsFn: () => { return 2; }, + focus: true, + isClickableElement: function(el) { + return el.tagName === 'A'; + }, + mainScrollEndFriction: 0.35, + panEndFriction: 0.35 + }; + + var photoSwipe: PhotoSwipe; + var uiOptions: PhotoSwipeUI_Default.Options = { + barsSize: {top: 44, bottom: 'auto'}, + timeToIdle: 4000, + timeToIdleOutside: 1000, + loadingIndicatorDelay: 1000, + addCaptionHTMLFn: function(item, captionEl, isFake) { + if (!item.title) { + ( captionEl.children[0]).innerHTML = ''; + return false; + } + ( captionEl.children[0]).innerHTML = item.title; + return true; + }, + closeEl: true, + captionEl: true, + fullscreenEl: true, + zoomEl: true, + shareEl: true, + counterEl: true, + arrowEl: true, + preloaderEl: true, + tapToClose: false, + tapToToggleControls: true, + clickToCloseNonZoomable: true, + closeElClasses: ['item', 'caption', 'zoom-wrap', 'ui', 'top-bar'], + indexIndicatorSep: ' / ', + shareButtons: [ + {id: 'facebook', label: 'Share on Facebook', url: 'https://www.facebook.com/sharer/sharer.php?u='}, + {id: 'twitter', label: 'Tweet', url: 'https://twitter.com/intent/tweet?text=&url='}, + {id: 'pinterest', label: 'Pin it', url: 'http://www.pinterest.com/pin/create/button/?url=&media=&description='}, + {id: 'download', label: 'Download image', url: '', download: true} + ], + getImageURLForShare: function( shareButtonData ) { + // `shareButtonData` - object from shareButtons array + // + // `pswp` is the gallery instance object, + // you should define it by yourself + // + return photoSwipe.currItem.src || ''; + }, + getPageURLForShare: function( shareButtonData ) { + return window.location.href; + }, + getTextForShare: function( shareButtonData ) { + return ( photoSwipe.currItem).title || ''; + }, + parseShareButtonOut: function(shareButtonData, shareButtonOut) { + return shareButtonOut; + } + }; + + var pswpElement = document.getElementById("gallery"); + photoSwipe = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, uiOptions); + +} + +function test_photoSwipeMethods() { + var photoSwipe: PhotoSwipe; + + photoSwipe.init(); + + alert(photoSwipe.currItem.src); + alert(photoSwipe.viewportSize.x); + photoSwipe.ui.init(); + photoSwipe.bg.style.borderStyle = "1px solid red"; + photoSwipe.container.style.borderStyle = "1px solid red"; + photoSwipe.options.timeToIdle = 2000; + alert(photoSwipe.getCurrentIndex() === 3); + alert(photoSwipe.getZoomLevel() === 1); + alert(photoSwipe.isDragging()); + + photoSwipe.goTo(9); + photoSwipe.next(); + photoSwipe.prev(); + + photoSwipe.updateSize(true); + + photoSwipe.close(); + photoSwipe.zoomTo(2, + { x: 250, y: 250 }, + 2000, + (x) => { return x*x*(3-2*x); }, + (zoomValue) => { console.log("zoom value is now" + zoomValue); }); + photoSwipe.applyZoomPan(1, 0, 0); + + photoSwipe.items[photoSwipe.getCurrentIndex()].src = "new/path/to/image.jpg"; + photoSwipe.invalidateCurrItems(); +} + +function test_photoSwipeEvents() { + var photoSwipe: PhotoSwipe; + + photoSwipe.listen('beforeChange', () => {}); + photoSwipe.listen('afterChange', () => {}); + photoSwipe.listen('beforeChange', () => {}); + photoSwipe.listen('imageLoadComplete', (idx: number, item: PhotoSwipeUI_Default.Item) => { + item.w *= 2; + }); + photoSwipe.listen('resize', () => {}); + photoSwipe.listen('gettingData', (idx: number, item: PhotoSwipeUI_Default.Item) => { + item.title = "abc"; + }); + photoSwipe.listen('mouseUsed', () => {}); + photoSwipe.listen('initialZoomIn', () => {}); + photoSwipe.listen('initialZoomInEnd', () => {}); + photoSwipe.listen('initialZoomOut', () => {}); + photoSwipe.listen('initialZoomOutEnd', () => {}); + photoSwipe.listen('parseVerticalMargin', (item: PhotoSwipeUI_Default.Item) => { + item.vGap.top = 20; + item.vGap.bottom = 40; + }); + photoSwipe.listen('close', () => {}); + photoSwipe.listen('unbindEvents', () => {}); + photoSwipe.listen('destroy', () => {}); + photoSwipe.listen('preventDragEvent', (e: MouseEvent, isDown: boolean, preventObj: {prevent: boolean}) => { + if (e.x > 50 && isDown) { + preventObj.prevent = true; + } + }); + + photoSwipe.listen('foo', (a, b, c) => { + alert(a + b + c); + }); + photoSwipe.shout('foo', 1, 2, 3); +} + +function test_customUI() { + var pswpElement = document.getElementById("gallery2"); + var myPhotoSwipe = new PhotoSwipe(pswpElement, MyUI, [], { + bgOpacity: 0, + index: 3, + foo: 123, + bar: "abc" + }); +} + +interface MyUIOptions extends PhotoSwipe.Options { + foo: number; + bar: string; +} + +class MyUI implements PhotoSwipe.UI { + constructor(pswp: PhotoSwipe, framework: PhotoSwipe.UIFramework) { + // dummy + } + + init() { + // dummy + } +} diff --git a/photoswipe/photoswipe.d.ts b/photoswipe/photoswipe.d.ts new file mode 100644 index 0000000000..b09fe75ddf --- /dev/null +++ b/photoswipe/photoswipe.d.ts @@ -0,0 +1,898 @@ +// Type definitions for PhotoSwipe 4.0.7 +// Project: http://photoswipe.com/ +// Definitions by: Xiaohan Zhang +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module PhotoSwipe { + /** + * A specific slide in the PhotoSwipe gallery. The terms "item", "slide", and "slide object" are used interchangeably. + */ + interface Item { + /** + * The url of this image. + */ + src: string; + /** + * The width of this image. + */ + w: number; + /** + * The height of this image. + */ + h: number; + + /** + * Internal property added by PhotoSwipe. + */ + loadError?: boolean; + + /** + * Internal property added by PhotoSwipe. + */ + vGap?: {top: number; bottom: number}; + + /** + * Internal property added by PhotoSwipe. + * This number is computed to be this item's smaller dimension divided by the larger dimension. + */ + fitRatio?: number; + + /** + * Internal property added by PhotoSwipe. + */ + initialZoomLevel?: number; + + /** + * Internal property added by PhotoSwipe. + */ + bounds?: any; + + /** + * Internal property added by PhotoSwipe. + */ + initialPosition?: any; + } + + /** + * Options for the base PhotoSwipe class. Derived from http://photoswipe.com/documentation/options.html + */ + interface Options { + /** + * Start slide index. 0 is the first slide. Must be integer, not a string. + * + * Default 0. + */ + index?: number; + + /** + * Function should return an object with coordinates from which initial zoom-in animation will start (or zoom-out animation will end). + * Object should contain three properties: x (X position, relative to document), y (Y position, relative to document), w (width of the element). + * Height will be calculated automatically based on size of large image. + * For example if you return {x:0,y:0,w:50} zoom animation will start in top left corner of your page. + * Function has one argument - index of the item that is opening or closing. + * + * Default undefined. + */ + getThumbBoundsFn?: (index: number) => { x: number; y: number; w: number }; + + /** + * Initial zoom-in transition duration in milliseconds. Set to 0 to disable. Besides this JS option, you need also to change transition duration in PhotoSwipe CSS file: + * .pswp--animate_opacity, + * .pswp__bg, + * .pswp__caption, + * .pswp__top-bar, + * .pswp--has_mouse .pswp__button--arrow--left, + * .pswp--has_mouse .pswp__button--arrow--right{ + * -webkit-transition: opacity 333ms cubic-bezier(.4,0,.22,1); + * transition: opacity 333ms cubic-bezier(.4,0,.22,1); + * } + * + * Default 333. + */ + showAnimationDuration?: number; + + /** + * The same as the previous option, just for closing (zoom-out) transition. + * After PhotoSwipe is opened pswp--open class will be added to the root element, you may use it to apply different transition duration in CSS. + * + * Default 333. + */ + hideAnimationDuration?: number; + + /** + * If set to false background opacity and image scale will be animated (image opacity is always 1). + * If set to true root PhotoSwipe element opacity and image scale will be animated. + * Enable it when dimensions of your small thumbnail don't match dimensions of large image. + * + * Default false. + */ + showHideOpacity?: boolean; + + /** + * Background (.pswp__bg) opacity. + * Should be a number from 0 to 1, e.g. 0.7. + * This style is defined via JS, not via CSS, as this value is used for a few gesture-based transitions. + * + * Default 1. + */ + bgOpacity?: number; + + /** + * Spacing ratio between slides. For example, 0.12 will render as a 12% of sliding viewport width (rounded). + * + * Default 0.12. + */ + spacing?: number; + + /** + * Allow swipe navigation to next/prev item when current item is zoomed. + * Option is always false on devices that don't have hardware touch support. + * + * Default true. + */ + allowNoPanText?: boolean; + + /** + * Maximum zoom level when performing spread (zoom) gesture. 2 means that image can be zoomed 2x from original size. + * Try to avoid huge values here, as too big image may cause memory issues on mobile (especially on iOS). + * + * Default 2. + */ + maxSpreadZoom?: number; + + /** + * Function should return zoom level to which image will be zoomed after double-tap gesture, or when user clicks on zoom icon, or mouse-click on image itself. + * If you return 1 image will be zoomed to its original size. + * Function is called each time zoom-in animation is initiated. So feel free to return different values for different images based on their size or screen DPI. + * + * Default is: + * + * function(isMouseClick, item) { + * + * // isMouseClick - true if mouse, false if double-tap + * // item - slide object that is zoomed, usually current + * // item.initialZoomLevel - initial scale ratio of image + * // e.g. if viewport is 700px and image is 1400px, + * // initialZoomLevel will be 0.5 + * + * if(isMouseClick) { + * + * // is mouse click on image or zoom icon + * + * // zoom to original + * return 1; + * + * // e.g. for 1400px image: + * // 0.5 - zooms to 700px + * // 2 - zooms to 2800px + * + * } else { + * + * // is double-tap + * + * // zoom to original if initial zoom is less than 0.7x, + * // otherwise to 1.5x, to make sure that double-tap gesture always zooms image + * return item.initialZoomLevel < 0.7 ? 1 : 1.5; + * } + * } + */ + getDoubleTapZoom?: (isMouseClick: boolean, item: Item) => number; + + /** + * Loop slides when using swipe gesture.If set to true you'll be able to swipe from last to first image. + * Option is always false when there are less than 3 slides. + * This option has no relation to arrows navigation. Arrows loop is turned on permanently. You can modify this behavior by making custom UI. + * + * Default true. + */ + loop?: boolean; + + /** + * Pinch to close gallery gesture. The gallery’s background will gradually fade out as the user zooms out. When the gesture is complete, the gallery will close. + * + * Default true. + */ + pinchToClose?: boolean; + + /** + * Close gallery on page scroll. Option works just for devices without hardware touch support. + * + * Default true. + */ + closeOnScroll?: boolean; + + /** + * Close gallery when dragging vertically and when image is not zoomed. Always false when mouse is used. + * + * Default true. + */ + closeOnVerticalDrag?: boolean; + + /** + * Option allows you to predefine if mouse was used or not. + * Some PhotoSwipe feature depend on it, for example default UI left/right arrows will be displayed only after mouse is used. + * If set to false, PhotoSwipe will start detecting when mouse is used by itself, mouseUsed event triggers when mouse is found. + * + * default false. + */ + mouseUsed?: boolean; + + /** + * esc keyboard key to close PhotoSwipe. Option can be changed dynamically (yourPhotoSwipeInstance.options.escKey = false;). + * + * Default true. + */ + escKey?: boolean; + + /** + * Keyboard left or right arrow key navigation. Option can be changed dynamically (yourPhotoSwipeInstance.options.arrowKeys = false;). + * + * Default true. + */ + arrowKeys?: boolean; + + /** + * If set to false disables history module (back button to close gallery, unique URL for each slide). You can also just exclude history.js module from your build. + * + * Default true. + */ + history?: boolean; + + /** + * Gallery unique ID. Used by History module when forming URL. For example, second picture of gallery with UID 1 will have URL: http://example.com/#&gid=1&pid=2. + * + * Default 1. + */ + galleryUID?: number; + + /** + * Error message when image was not loaded. %url% will be replaced by URL of image. + * + * Default is: + * + *
The image could not be loaded.
+ */ + errorMsg?: string; + + /** + * Lazy loading of nearby slides based on direction of movement. + * Should be an array with two integers, first one - number of items to preload before current image, second one - after the current image. + * E.g. if you set it to [1,3], it'll load 1 image before the current, and 3 images after current. Values can not be less than 1. + * + * Default [1, 1]. + */ + preload?: number[]; + + /** + * String with name of class that will be added to root element of PhotoSwipe (.pswp). Can contain multiple classes separated by space. + */ + mainClass?: string; + + /** + * Function that should return total number of items in gallery. Don't put very complex code here, function is executed very often. + * + * By default it returns length of slides array. + */ + getNumItemsFn?: () => number; + + /** + * Will set focus on PhotoSwipe element after it's open. + * + * Default true. + */ + focus?: boolean; + + /** + * Function should check if the element (el) is clickable. + * If it is – PhotoSwipe will not call preventDefault and click event will pass through. + * Function should be as light is possible, as it's executed multiple times on drag start and drag release. + * + * Default is: + * + * function(el) { + * return el.tagName === 'A'; + * } + */ + isClickableElement?: (el: HTMLElement) => boolean; + } + + interface UIFramework { + [name: string]: any; + } + + /** + * Base type for PhotoSwipe user interfaces. + * T is the type of options that this PhotoSwipe.UI uses. + * + * To build your own PhotoSwipe.UI class: + * + * (1) Write an interface for the custom UI's Options that extends PhotoSwipe.Options. + * (2) Write your custom class, implementing the PhotoSwipe.UI interface. + * (3) Pass in your custom interface to the type parameter T of the PhotoSwipe.UI interface. + * + * Example: + * + * // (1) + * interface MyUIOptions extends PhotoSwipe.Options { + * foo: number; + * bar: string; + * } + * + * // (2) and (3) + * class MyUI implements PhotoSwipe.UI { + * constructor(pswp: PhotoSwipe, framework: PhotoSwipe.UIFramework) { + * } + * } + * + * var pswpWithMyUI = new PhotoSwipe(element, MyUI, items, {foo: 1, bar: "abc"}); + */ + interface UI { + /** + * Called by PhotoSwipe after it constructs the UI. + */ + init: () => void; + } +} + +/** + * Base PhotoSwipe class. Derived from http://photoswipe.com/documentation/api.html + */ +declare class PhotoSwipe { + /** + * Constructs a PhotoSwipe. + * + * Note: By default Typescript will not correctly typecheck the options parameter. Make sure to + * explicitly annotate the type of options being passed into the constructor like so: + * + * new PhotoSwipe( element, PhotoSwipeUI_Default, items, options ); + * + * It accepts 4 arguments: + * + * (1) PhotoSwipe element (it must be added to DOM). + * (2) PhotoSwipe UI class. If you included default photoswipe-ui-default.js, class will be PhotoSwipeUI_Default. Can be "false". + * (3) Array with objects (slides). + * (4) Options. + */ + constructor(pswpElement: HTMLElement, + uiConstructor: (new (pswp: PhotoSwipe, framework: PhotoSwipe.UIFramework) => PhotoSwipe.UI) | boolean, + items: PhotoSwipe.Item[], + options: T); + + /** + * Current slide object. + */ + currItem: PhotoSwipe.Item; + + /** + * Items in this gallery. PhotoSwipe will (almost) dynamically respond to changes in this array. + * To add, edit, or remove slides after PhotoSwipe is opened, you just need to modify the items array. + * + * For example, you can push new slide objects into the items array: + * + * pswp.items.push({ + * src: "path/to/image.jpg", + * w:1200, + * h:500 + * }); + * + * If you changed slide that is CURRENT, NEXT or PREVIOUS (which you should try to avoid) – you need to call method that will update their content: + * + * // sets a flag that slides should be updated + * pswp.invalidateCurrItems(); + * // updates the content of slides + * pswp.updateSize(true); + * + * If you're using the DefaultUI, call pswp.ui.update() to update that as well. Also note: + * + * (1) You can't reassign whole array, you can only modify it (e.g. use splice to remove elements). + * (2) If you're going to remove current slide – call goTo method before. + * (3) There must be at least one slide. + * (4) This technique is used to serve responsive images. + */ + items: PhotoSwipe.Item[]; + + /** + * Size of the current viewport. + */ + viewportSize: { + x: number; + y: number; + }; + + /** + * The Framework. Holds utility methods. + */ + framework: PhotoSwipe.UIFramework; + + /** + * The ui instance constructed by PhotoSwipe. + */ + ui: PhotoSwipe.UI; + + /** + * The background element (with class .pswp__bg). + */ + bg: HTMLElement; + + /** + * The container element (with class .pswp__container). + */ + container: HTMLElement; + + /** + * Options for this PhotoSwipe. This object is a copy of the options parameter passed into the constructor. + * Some properties in options are dynamically modifiable. + */ + options: T; + + /** + * Current item index. + */ + getCurrentIndex(): number; + + /** + * Current zoom level. + */ + getZoomLevel(): number; + + /** + * Whether one (or more) pointer is used. + */ + isDragging(): boolean; + + /** + * Whether two (or more) pointers are used. + */ + isZooming(): boolean; + + /** + * true wehn transition between is running (after swipe). + */ + isMainScrollAnimating(): boolean; + + /** + * Initialize and open gallery (you can bind events before this method). + */ + init(): void; + + /** + * Go to slide by index. + */ + goTo(index: number): void; + + /** + * Go to the next slide. + */ + next(): void; + + /** + * Go to the previous slide. + */ + prev(): void; + + /** + * Update gallery size + * @param {boolean} `force` If you set it to `true`, size of the gallery will be updated even if viewport size hasn't changed. + */ + updateSize(force: boolean): void; + + /** + * Close gallery. Calls destroy() after closing. + */ + close(): void; + + /** + * Destroy gallery (unbind listeners, free memory). Automatically called after close(). + */ + destroy(): void; + + /** + * Zoom in/out the current slide to a specified zoom level, optionally with animation. + * + * @param {number} `destZoomLevel` Destination scale number. Set to 1 for unzoomed. + * Use `pswp.currItem.fitRatio - image` to zoom the image to perfectly fit into the viewport. + * @param {object} `centerPoint` The center of the zoom, relative to viewport. + * @param {number} `speed` Animation duration in milliseconds. Can be 0. + * @param {function} `easingFn` Easing function (optional). Set to false to use default easing. + * This method is passed in the percentage that the animation is finished (from 0 to 1) and should return an eased value (which should be 0 at the start and 1 at the end). + * @param {function} `updateFn` Function will be called on each update frame (optional). + * This method is passed the eased zoom level. + * + * Example below will 2x zoom to center of slide: + * + * pswp.zoomTo(2, {x:pswp.viewportSize.x/2,y:pswp.viewportSize.y/2}, 2000, false, function(now) {}); + * + */ + zoomTo(destZoomLevel: number, + centerPoint: {x: number; y: number}, + speed: number, + easingFn?: (k: number) => number, + updateFn?: (now: number) => void): void; + + /** + * Apply zoom and pan to the current slide + * + * @param {number} `zoomLevel` + * @param {int} `panX` + * @param {int} `panY` + * + * For example: `pswp.applyZoomPan(1, 0, 0)` + * will zoom current image to the original size + * and will place it on top left corner. + * + */ + applyZoomPan(zoomLevel: number, panX: number, panY: number): void; + + /** + * Call this method after dynamically modifying the current, next, or previous slide in the items array. + */ + invalidateCurrItems(): void; + + /** + * PhotoSwipe uses very simple Event/Messaging system. + * It has two methods shout (triggers event) and listen (handles event). + * For now there is no method to unbind listener, but all of them are cleared when PhotoSwipe is closed. + */ + listen(eventName: string, callback: (...args: any[]) => void): void; + + /** + * Called before slides change (before the content is changed ,but after navigation). Update UI here. + */ + listen(eventName: 'beforeChange', callback: () => void): void; + /** + * Called after slides change (after content has changed). + */ + listen(eventName: 'afterChange', callback: () => void): void; + /** + * Called when an image is loaded. + */ + listen(eventName: 'imageLoadComplete', callback: (index: number, item: PhotoSwipe.Item) => void): void; + /** + * Called when the viewport size changes. + */ + listen(eventName: 'resize', callback: () => void): void; + /** + * Triggers when PhotoSwipe reads slide object data, which happens before content is set, or before lazy-loading is initiated. + * Use it to dynamically change properties of the slide object. + */ + listen(eventName: 'gettingData', callback: (index: number, item: PhotoSwipe.Item) => void): void; + /** + * Called when mouse is first used (triggers only once). + */ + listen(eventName: 'mouseUsed', callback: () => void): void; + /** + * Called when opening zoom in animation starting. + */ + listen(eventName: 'initialZoomIn', callback: () => void): void; + /** + * Called when opening zoom in animation finished. + */ + listen(eventName: 'initialZoomInEnd', callback: () => void): void; + /** + * Called when closing zoom out animation started. + */ + listen(eventName: 'initialZoomOut', callback: () => void): void; + /** + * Called when closing zoom out animation finished. + */ + listen(eventName: 'initialZoomOutEnd', callback: () => void): void; + /** + * Allows overriding vertical margin for individual items. + * + * Example: + * + * pswp.listen('parseVerticalMargin', function(item) { + * var gap = item.vGap; + * + * gap.top = 50; // There will be 50px gap from top of viewport + * gap.bottom = 100; // and 100px gap from the bottom + * }); + */ + listen(eventName: 'parseVerticalMargin', callback: (item: PhotoSwipe.Item) => void): void; + /** + * Called when the gallery starts closing. + */ + listen(eventName: 'close', callback: () => void): void; + /** + * Gallery unbinds events (triggers before closing animation). + */ + listen(eventName: 'unbindEvents', callback: () => void): void; + /** + * Called after the gallery is closed and the closing animation finishes. + * Clean up your stuff here. + */ + listen(eventName: 'destroy', callback: () => void): void; + /** + * Allow to call preventDefault on down and up events. + */ + listen(eventName: 'preventDragEvent', callback: (e: MouseEvent, isDown: boolean, preventObj: {prevent: boolean}) => void): void; + + /** + * Triggers eventName event with args passed through to listeners. + */ + shout(eventName: string, ...args: any[]): void; +} + +/** + * Default UI class for PhotoSwipe. This class is largely undocumented and doesn't seem to have a public facing API. + */ +declare class PhotoSwipeUI_Default implements PhotoSwipe.UI { + constructor(pswp: PhotoSwipe, framework: PhotoSwipe.UIFramework); + init(): void; + + /** + * Call this method to update the UI after the items array has been modified in the original PhotoSwipe element. + */ + update(): void; +} + +declare module PhotoSwipeUI_Default { + /** + * Options for the PhotoSwipe Default UI. Derived from http://photoswipe.com/documentation/options.html + */ + interface Options extends PhotoSwipe.Options { + /** + * Size of top & bottom bars in pixels. "bottom" parameter can be 'auto' (will calculate height of caption). + * Option applies only when mouse is used, or when width of screen is more than 1200px. + * Also look at `parseVerticalMargin` event. + * + * Default {top: 44, bottom: "auto"}. + */ + barsSize?: { top: number; bottom: number | string }; + + /** + * Adds class pswp__ui--idle to pswp__ui element when mouse isn't moving for timeToIdle milliseconds. + * + * Default 4000. + */ + timeToIdle?: number; + + /** + * Adds class pswp__ui--idle to pswp__ui element when mouse leaves the window for timeToIdleOutside milliseconds. + * + * Default 1000. + */ + timeToIdleOutside?: number; + + /** + * Delay in milliseconds until loading indicator is displayed. + * + * Default 1000. + */ + loadingIndicatorDelay?: number; + + /** + * Function to build caption markup. The function takes three parameters: + * + * item - slide object + * captionEl - caption DOM element + * isFake - true when content is added to fake caption container + * (used to get size of next or previous caption) + * + * Return whether to show the caption or not. + * + * Default is: + * + * function(item, captionEl, isFake) { + * if(!item.title) { + * captionEl.children[0].innerHTML = ''; + * return false; + * } + * captionEl.children[0].innerHTML = item.title; + * return true; + * } + * + */ + addCaptionHTMLFn?: (item: Item, captionEl: HTMLElement, isFake: boolean) => boolean; + + /** + * Whether to show the close button. + * + * Default true. + */ + closeEl?: boolean; + + /** + * Whether to show the caption. + * + * Default true. + */ + captionEl?: boolean; + + /** + * Whether to show the fullscreen button. + * + * Default true. + */ + fullscreenEl?: boolean; + + /** + * Whether to show the zoom button. + * + * Default true. + */ + zoomEl?: boolean; + + /** + * Whether to show the share button. + * + * Default true. + */ + shareEl?: boolean; + + /** + * Whether to show the current image's index in the gallery (located in top-left corner by default). + * + * Default true. + */ + counterEl?: boolean; + + /** + * Whether to show the left/right directional arrows. + * + * Default true. + */ + arrowEl?: boolean; + + /** + * Whether to show the preloader element. + * + * Default true. + */ + preloaderEl?: boolean; + + /** + * Tap on sliding area should close gallery. + * + * Default false. + */ + tapToClose?: boolean; + + /** + * Tap should toggle visibility of controls. + * + * Default true. + */ + tapToToggleControls?: boolean; + + /** + * Mouse click on image should close the gallery, only when image is smaller than size of the viewport. + * + * Default true. + */ + clickToCloseNonZoomable?: boolean; + + /** + * Element classes that should close PhotoSwipe when clicked on. + * In HTML markup, class should always start with "pswp__", e.g.: "pswp__item", "pswp__caption". + * + * "pswp__ui--over-close" class will be added to root element of UI when mouse is over one of these elements + * By default it's used to highlight the close button. + * + * Default ['item', 'caption', 'zoom-wrap', 'ui', 'top-bar']. + */ + closeElClasses?: string[]; + + /** + * Separator for "1 of X" counter. + * + * Default ' / '. + */ + indexIndicatorSep?: string; + + /** + * The entries that show up when you click the Share button. + * + * Default is: + * + * [ + * {id:'facebook', label:'Share on Facebook', url:'https://www.facebook.com/sharer/sharer.php?u='}, + * {id:'twitter', label:'Tweet', url:'https://twitter.com/intent/tweet?text=&url='}, + * {id:'pinterest', label:'Pin it', url:'http://www.pinterest.com/pin/create/button/?url=&media=&description='}, + * {id:'download', label:'Download image', url:'', download:true} + * ] + * + */ + shareButtons?: ShareButtonData[]; + + /** + * A callback that should return the URL for the currently selected image. The callback is passed + * the shareButtonData entry that was clicked on. + * + * Default is: + * + * function( shareButtonData ) { + * // `shareButtonData` - object from shareButtons array + * // + * // `pswp` is the gallery instance object, + * // you should define it by yourself + * // + * return pswp.currItem.src || ''; + * } + * + */ + getImageURLForShare?: (shareButtonData: ShareButtonData) => string; + + /** + * A callback that should return the "Page" associated with the selected image. (e.g. on Facebook, the shared + * content will be associated with the returned page). The callback is passed the shareButtonData entry that + * was clicked on. + * + * Default is: + * + * function( shareButtonData ) { + * return window.location.href; + * } + * + */ + getPageURLForShare?: (shareButtonData: ShareButtonData) => string; + + /** + * A callback that should return the Text associated with the selected image. The callback is passed + * the shareButtonData entry that was clicked on. + * + * Default is: + * + * function( shareButtonData ) { + * return pswp.currItem.title || ''; + * } + * + */ + getTextForShare?: (shareButtonData: ShareButtonData) => string; + + /** + * A final output callback that you can use to further modify the share button's HTML. The callback is passed + * (1) the shareButtonData entry being generated, and (2) the default HTML generated by PhotoSwipUI_Default. + * + * Default is: + * + * function(shareButtonData, shareButtonOut) { + * return shareButtonOut; + * } + * + */ + parseShareButtonOut?: (shareButtonData: ShareButtonData, shareButtonOut: string) => string; + } + + interface ShareButtonData { + /** + * An id for this share button entry. The share element associated with this entry will be classed with + * 'pswp__share--' + id + */ + id: string; + + /** + * The user-visible text to display for this entry. + */ + label: string; + + /** + * The full sharing endpoint URL for this social media site (e.g. Facebook's is facebook.com/sharer/sharer.php), with URL parameters. + * PhotoSwipUI_Default treats the URL specially. In the url string, any of the following text is treated specially: + * '{{url}}', '{{image_url}}, '{{raw_image_url}}, '{{text}}'. PhotoSwipeUI_Default will replace each of them with the following value: + * + * {{url}} becomes the (URIEncoded) url to the current "Page" (as returned by getPageURLForShare). + * {{image_url}} becomes the (URIEncoded) url of the selected image (as returned by getImageURLForShare). + * {{raw_image_url}} becomes the raw url of the selected image (as returned by getImageURLForShare). + * {{text}} becomes the (URIEncoded) share text of the selected image (as returned by getTextForShare). + */ + url: string; + + /** + * Whether this link is a direct download button or not. + * + * Default false. + */ + download?: boolean; + } + + /** + * Extra properties that the Default UI accepts. + */ + interface Item extends PhotoSwipe.Item { + /** + * The caption for this item. + */ + title?: string; + } +} diff --git a/polymer/polymer-tests.ts b/polymer/polymer-tests.ts index a606692fd3..f594b4f226 100644 --- a/polymer/polymer-tests.ts +++ b/polymer/polymer-tests.ts @@ -10,6 +10,31 @@ class AbstractPolymerElement implements PolymerElement { asyncFire(eventName: string, details?: any, targetNode?: any, bubbles?: boolean, cancelable?: boolean): void { } cancelUnbindAll(): void { } + + /** + * User must call from attached callback + */ + resizableAttachedHandler(): void {} + + /** + * User must call from detached callback + */ + resizableDetachedHandler(): void {} + + /** + * User must call from attached callback + */ + resizerAttachedHandler(): void {} + + /** + * User must call from detached callback + */ + resizerDetachedHandler(): void {} + + /** + * User should call when resizing or un-hiding children + */ + notifyResize(): void {} } class AbstractWebComponent extends AbstractPolymerElement { diff --git a/polymer/polymer.app-router.d.ts b/polymer/polymer.app-router.d.ts index 633479ba2b..adf2f8d3b9 100644 --- a/polymer/polymer.app-router.d.ts +++ b/polymer/polymer.app-router.d.ts @@ -3,9 +3,11 @@ // Definitions by: Louis Grignon // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module PolymerComponents { module App { - export interface Router extends HTMLElement { + export interface Router extends PolymerElement, HTMLElement { init(): void; go(path: string, options?: { replace?: boolean }): void; } diff --git a/polymer/polymer.core-drawer-panel.d.ts b/polymer/polymer.core-drawer-panel.d.ts index 2bad7b633a..f219b4d0bc 100644 --- a/polymer/polymer.core-drawer-panel.d.ts +++ b/polymer/polymer.core-drawer-panel.d.ts @@ -3,9 +3,11 @@ // Definitions by: Louis Grignon // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module PolymerComponents { export module Core { - export interface DrawerPanel extends HTMLElement { + export interface DrawerPanel extends PolymerElement, HTMLElement { /** * Width of the drawer panel. default: '256px' */ diff --git a/polymer/polymer.core-overlay.d.ts b/polymer/polymer.core-overlay.d.ts new file mode 100644 index 0000000000..706dee8990 --- /dev/null +++ b/polymer/polymer.core-overlay.d.ts @@ -0,0 +1,92 @@ +// Type definitions for polymer's paper-toast +// Project: https://github.com/Polymer/core-selector +// Definitions by: Louis Grignon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module PolymerComponents { + export module Core { + export interface Overlay extends PolymerElement, HTMLElement { + /** + * The target element that will be shown when the overlay is opened. If unspecified, the core-overlay itself is the target. + * default: the overlay element + */ + target: Object; + + /** + * A core-overlay's size is guaranteed to be constrained to the window size. To achieve this, the sizingElement is sized with a max-height/width. By default this element is the target element, but it can be specifically set to a specific element inside the target if that is more appropriate. This is useful, for example, when a region inside the overlay should scroll if needed. + * default: the target element + */ + sizingTarget: Object; + + /** + * Set opened to true to show an overlay and to false to hide it. A core-overlay may be made initially opened by setting its opened attribute. + * default: false + */ + opened: boolean; + + /** + * If true, the overlay has a backdrop darkening the rest of the screen. The backdrop element is attached to the document body and may be styled with the class core-overlay-backdrop. When opened the core-opened class is applied. + * default: false + */ + backdrop: boolean; + + /** + * If true, the overlay is guaranteed to display above page content. + * default: false + */ + layered: boolean; + + /** + * By default an overlay will close automatically if the user taps outside it or presses the escape key. Disable this behavior by setting the autoCloseDisabled property to true. + * default: false + */ + autoCloseDisabled: boolean; + + /** + * By default an overlay will focus its target or an element inside it with the autoFocus attribute. Disable this behavior by setting the autoFocusDisabled property to true. + * default: false + */ + autoFocusDisabled: boolean; + + /** + * This property specifies an attribute on elements that should close the overlay on tap. Should not set closeSelector if this is set. + * default: "core-overlay-toggle" + */ + closeAttribute: string; + + /** + * This property specifies a selector matching elements that should close the overlay on tap. Should not set closeAttribute if this is set. + * default: '' + */ + closeSelector: string; + + /** + * The transition property specifies a string which identifies a core-transition element that will be used to help the overlay open and close. The default core-transition-fade will cause the overlay to fade in and out. + * default: 'core-transition-fade' + */ + transition: string; + + /** + * Toggle the opened state of the overlay. + */ + toggle(): void; + + /** + * Open the overlay. This is equivalent to setting the opened property to true. + */ + open(): void; + + /** + * Close the overlay. This is equivalent to setting the opened property to false. + */ + close(): void; + + /** + * Extensions of core-overlay should implement the resizeHandler method to adjust the size and position of the overlay when the browser window resizes. + */ + resizeHandler(): void; + } + } +} \ No newline at end of file diff --git a/polymer/polymer.core-selector.d.ts b/polymer/polymer.core-selector.d.ts new file mode 100644 index 0000000000..c7941cdde7 --- /dev/null +++ b/polymer/polymer.core-selector.d.ts @@ -0,0 +1,20 @@ +// Type definitions for polymer's paper-toast +// Project: https://github.com/Polymer/core-selector +// Definitions by: Louis Grignon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module PolymerComponents { + export module Core { + export interface Selector extends PolymerElement, HTMLElement { + } + + export interface SelectorOnSelectEvent extends Event { + detail: { + item: HTMLElement; + isSelected: boolean; + }; + } + } +} \ No newline at end of file diff --git a/polymer/polymer.d.ts b/polymer/polymer.d.ts index dfb812f8c0..ed084a4485 100644 --- a/polymer/polymer.d.ts +++ b/polymer/polymer.d.ts @@ -18,6 +18,31 @@ interface PolymerElement { domReady? (): void; detached? (): void; attributeChanged? (attrName: string, oldVal: any, newVal: any): void; + + /** + * User must call from attached callback + */ + resizableAttachedHandler(): void; + + /** + * User must call from detached callback + */ + resizableDetachedHandler(): void; + + /** + * User must call from attached callback + */ + resizerAttachedHandler(): void; + + /** + * User must call from detached callback + */ + resizerDetachedHandler(): void; + + /** + * User should call when resizing or un-hiding children + */ + notifyResize(): void; } interface Polymer { @@ -34,9 +59,6 @@ interface Polymer { (tagName: string, prototype: any): void; (prototype: PolymerElement): void; (): void; - // hacks for mixins - CoreResizer: any; - CoreResizable: any; } declare var Polymer: Polymer; diff --git a/polymer/polymer.paper-dialog.d.ts b/polymer/polymer.paper-dialog.d.ts new file mode 100644 index 0000000000..51758e42cb --- /dev/null +++ b/polymer/polymer.paper-dialog.d.ts @@ -0,0 +1,30 @@ +// Type definitions for polymer's paper-dialog +// Project: https://github.com/Polymer/paper-dialog +// Definitions by: Louis Grignon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module PolymerComponents { + export module Paper { + export interface Dialog extends PolymerComponents.Core.Overlay, HTMLElement { + /** + * The title of the dialog. + * default: '' + */ + heading: string; + + /** + * See paper-dialog-transition + * default: '' + */ + transition: string; + + /** + * default: true + */ + layered: boolean; + } + } +} \ No newline at end of file diff --git a/polymer/polymer.paper-toast.d.ts b/polymer/polymer.paper-toast.d.ts index fbf8cd7a65..6e29c1c8b6 100644 --- a/polymer/polymer.paper-toast.d.ts +++ b/polymer/polymer.paper-toast.d.ts @@ -3,9 +3,11 @@ // Definitions by: Louis Grignon // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module PolymerComponents { export module Paper { - export interface Toast extends HTMLElement { + export interface Toast extends PolymerElement, HTMLElement { /** * The text shows in a toast. * default: '' diff --git a/qunit/qunit.d.ts b/qunit/qunit.d.ts index dbf5d9c087..ddbf014e43 100644 --- a/qunit/qunit.d.ts +++ b/qunit/qunit.d.ts @@ -170,7 +170,7 @@ interface QUnitAssert { * resolution callback for each async operation. The callback returned from assert.async() * will throw an Error if is invoked more than once. */ - async(): any; + async(): () => void; /** * A deep recursive comparison assertion, working on primitive types, arrays, objects, diff --git a/restangular/restangular-tests.ts b/restangular/restangular-tests.ts index 11d7a086d2..82dfcd8059 100644 --- a/restangular/restangular-tests.ts +++ b/restangular/restangular-tests.ts @@ -82,6 +82,9 @@ myApp.controller('TestCtrl', ( Restangular.one('accounts', 123).getList('buildings'); Restangular.one('accounts', 123).getList('buildings'); + var accountData = Restangular.one('accounts', 123).plain(); + var accountClone: restangular.IElement = Restangular.one('accounts', 123).clone(); + baseAccounts.getList().then(function (accounts) { var firstAccount = accounts[0]; $scope.buildings = firstAccount.getList("buildings"); diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 8b8fd9d2f4..c2013f6c49 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -112,7 +112,10 @@ declare module restangular { trace(queryParams?: any, headers?: any): IPromise; options(queryParams?: any, headers?: any): IPromise; patch(queryParams?: any, headers?: any): IPromise; + clone(): IElement; + plain(): any; withHttpConfig(httpConfig: IRequestConfig): IElement; + save(queryParams?: any, headers?: any): IPromise; getRestangularUrl(): string; } diff --git a/sanitizer/sanitizer-tests.ts b/sanitizer/sanitizer-tests.ts new file mode 100644 index 0000000000..6a4c8982d6 --- /dev/null +++ b/sanitizer/sanitizer-tests.ts @@ -0,0 +1,53 @@ +/// + +import sanitizer = require('sanitizer'); + +// example copied from the tests https://github.com/theSmaw/Caja-HTML-Sanitizer/blob/master/test/test-sanitizer.js#L346 +var events:any[] = []; +var addTextEvent = function(type:string, text:string, param:any) { + var n = events.length; + + if (events[n - 3] === type && events[n - 1] === param) { + events[n - 2] += text; + } else { + events.push(type, text, param); + } +}; + +sanitizer.makeSaxParser({ + startTag: function(name, attribs, param) { + events.push('startTag', name + '[' + attribs.join(';') + ']', param); + }, + + endTag: function(name, param) { + events.push('endTag', name, param); + }, + + pcdata: function(text, param) { + addTextEvent('pcdata', text, param); + }, + + cdata: function(text, param) { + addTextEvent('cdata', text, param); + }, + + rcdata: function(text, param) { + addTextEvent('rcdata', text, param); + }, + + comment: function(text, param) { + events.push('comment', text, param); + }, + + startDoc: function(param) { + events.push('startDoc', '', param); + }, + + endDoc: function(param) { + events.push('endDoc', '', param); + } +}); +sanitizer.escape(''); +sanitizer.sanitize(''); +sanitizer.normalizeRCData(''); +sanitizer.unescapeEntities(''); diff --git a/sanitizer/sanitizer.d.ts b/sanitizer/sanitizer.d.ts new file mode 100644 index 0000000000..16d9448c96 --- /dev/null +++ b/sanitizer/sanitizer.d.ts @@ -0,0 +1,27 @@ +// Type definitions for Sanitizer +// Project: https://github.com/theSmaw/Caja-HTML-Sanitizer +// Definitions by: Dave Taylor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'sanitizer' { + export interface ISaxHandler { + startTag(name:string, attribs:string[], param:any):void; + endTag(name:string, param:any):void; + pcdata(text:string, param:any):void; + cdata(text:string, param:any):void; + rcdata(text:string, param:any):void; + comment(text:string, param:any):void; + startDoc(param:any):void; + endDoc(param:any):void; + } + + export function escape(s:string):string; + + export function makeSaxParser(yourHandler:ISaxHandler):(...any:any[])=>any; + + export function normalizeRCData(s:string):string; + + export function sanitize(s:string):string; + + export function unescapeEntities(s:string):string; +} diff --git a/slickgrid/slick.autotooltips-tests.ts b/slickgrid/slick.autotooltips-tests.ts new file mode 100644 index 0000000000..f2e7f6f39c --- /dev/null +++ b/slickgrid/slick.autotooltips-tests.ts @@ -0,0 +1,8 @@ +/// + +var grid = new Slick.Grid("#myGrid", [], [], {}); +grid.registerPlugin(new Slick.AutoTooltips({ + enableForCells: true, + enableForHeaderCells: true, + maxToolTipLength: 100 +})); diff --git a/slickgrid/slick.autotooltips.d.ts b/slickgrid/slick.autotooltips.d.ts new file mode 100644 index 0000000000..34e761754a --- /dev/null +++ b/slickgrid/slick.autotooltips.d.ts @@ -0,0 +1,35 @@ +// Type definitions for SlickGrid AutoToolTips Plugin 2.1.0 +// Project: https://github.com/mleibman/SlickGrid +// Definitions by: Ryo Iwamoto +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Slick { + export interface SlickGridAutoTooltipsOption extends PluginOptions { + /** + * Enable tooltip for grid cells + * @default true + */ + enableForCells?: boolean; + + /** + * Enable tooltip for header cells + * @default false + */ + enableForHeaderCells?: boolean; + + /** + * The maximum length for a tooltip + * @default null + */ + maxToolTipLength?: number; + } + + /** + * AutoTooltips plugin to show/hide tooltips when columns are too narrow to fit content. + */ + export class AutoTooltips extends Plugin { + constructor(option?: SlickGridAutoTooltipsOption); + } +} diff --git a/soundjs/soundjs.d.ts b/soundjs/soundjs.d.ts index f719be5b32..90e50200d6 100644 --- a/soundjs/soundjs.d.ts +++ b/soundjs/soundjs.d.ts @@ -177,6 +177,7 @@ declare module createjs { static registerManifest(manifest: Object[], basePath: string): Object; static registerPlugins(plugins: any[]): boolean; static registerSound(src: string | Object, id?: string, data?: number | Object, basePath?: string): Object; + static registerSounds(sounds: Object[], basePath?: string): Object[]; static removeAllSounds(): void; static removeManifest(manifest: any[], basePath: string): Object; static removeSound(src: string | Object, basePath: string): boolean; diff --git a/squirejs/squirejs-tests.ts b/squirejs/squirejs-tests.ts new file mode 100644 index 0000000000..fc1701fbf6 --- /dev/null +++ b/squirejs/squirejs-tests.ts @@ -0,0 +1,37 @@ +/// + +import Squire = require('Squire'); + +// Default Configuration +var injector = new Squire(); + +// Different Context +injector = new Squire('other-requirejs-context'); + +// require(Array dependencies, Function callback, Function errback) +injector.require(['a'], function(A: any) {}, function(err: any) {}); + +// mock(String name | Object(name: mock), Object mock) +injector.mock("a", {}); +injector.mock({a: {}}); + +// store(String name | Array names) +injector.store('a'); +injector.store(['a', 'b']); + +// clean(Optional (String name | Array names)) +injector.clean('a'); +injector.clean(['a', 'b']); +injector.clean(); + +// remove() +injector.remove(); + +// run() +injector.run(['a'], function test(a: any) {})(function done() {}); + +// Squire.Helpers.returns(Any what) +Squire.Helpers.returns({}); + +// Squire.Helpers.constructs(Any what) +Squire.Helpers.constructs({}); diff --git a/squirejs/squirejs.d.ts b/squirejs/squirejs.d.ts new file mode 100644 index 0000000000..693ca7d907 --- /dev/null +++ b/squirejs/squirejs.d.ts @@ -0,0 +1,28 @@ +// Type definitions for Squire 0.2.1 +// Project: https://github.com/iammerrick/Squire.js +// Definitions by: Bradley Ayers +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'Squire' { + class Squire { + constructor(); + constructor(context: string); + mock(name: string, mock: any): Squire; + mock(mocks: {[name: string]: any}): Squire; + require(dependencies: string[], callback: Function, errback: Function): Squire; + store(name: string | string[]): Squire; + clean(): Squire; + clean(name: string | string[]): Squire; + remove(): String; + run(dependencies: string[], test: Function): (done: Function) => void; + } + + module Squire { + module Helpers { + export function returns(what: T): () => T; + export function constructs(what: T): () => (() => T); + } + } + + export = Squire; +} diff --git a/strophe/strophe-tests.ts b/strophe/strophe-tests.ts new file mode 100644 index 0000000000..78ffb3941e --- /dev/null +++ b/strophe/strophe-tests.ts @@ -0,0 +1,102 @@ +/// + +function log(msg: string): void { + console.log(msg); +} + +function rawInput(data: string): void { + log('RECV: ' + data); +} + +function rawOutput(data: string): void { + log('SENT: ' + data); +} + +function onOwnMessage(msg: HTMLElement): boolean { + + console.log(msg); + var elems = msg.getElementsByTagName('own-message'); + if (elems.length > 0) { + var own = elems[0]; + var to = msg.getAttribute('to'); + var from = msg.getAttribute('from'); + var iq = $iq({ + to: from, + type: 'error', + id: msg.getAttribute('id') + }).cnode(own).up().c('error', { type: 'cancel', code: '501' }) + .c('feature-not-implemented', { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' }); + + connection.sendIQ(iq); + } + + return true; +} + +function onMessage(msg: Element): boolean { + var to = msg.getAttribute('to'); + var from = msg.getAttribute('from'); + var type = msg.getAttribute('type'); + var elems = msg.getElementsByTagName('body'); + + if (type == "chat" && elems.length > 0) { + var body = elems[0]; + + log('ECHOBOT: I got a message from ' + from + ': ' + + Strophe.getText(body)); + + var text = Strophe.getText(body) + " (this is echo)"; + + //var reply = $msg({to: from, from: to, type: 'chat', id: 'purple4dac25e4'}).c('active', {xmlns: "http://jabber.org/protocol/chatstates"}).up().cnode(body); + //.cnode(Strophe.copyElement(body)); + //connection.send(reply.tree()); + + log('ECHOBOT: I sent ' + from + ': ' + Strophe.getText(body)); + } + + // we must return true to keep the handler alive. + // returning false would remove it after it finishes. + return true; +} + + +function sendMessage() { + var message = "some message"; + var to = "some recipient"; + if (message && to) { + var reply = $msg({ + to: to, + type: 'chat' + }) + .cnode(Strophe.xmlElement('body', message)).up() + .c('active', { xmlns: "http://jabber.org/protocol/chatstates" }); + + connection.send(reply); + + log('I sent ' + to + ': ' + message); + } +} + +var connection = new Strophe.Connection("someservice"); +connection.rawInput = rawInput; +connection.rawOutput = rawOutput; + +function onConnect(status: Strophe.Status): void { + if (status == Strophe.Status.CONNECTING) { + log('Strophe is connecting.'); + } else if (status == Strophe.Status.CONNFAIL) { + log('Strophe failed to connect.'); + } else if (status == Strophe.Status.DISCONNECTING) { + log('Strophe is disconnecting.'); + } else if (status == Strophe.Status.DISCONNECTED) { + log('Strophe is disconnected.'); + } else if (status == Strophe.Status.CONNECTED) { + log('Strophe is connected.'); + log('ECHOBOT: Send a message to ' + connection.jid + + ' to talk to me.'); + + connection.addHandler(onMessage, null, 'message', null, null, null); + connection.addHandler(onOwnMessage, null, 'iq', 'set', null, null); + connection.send($pres().tree()); + } +} diff --git a/strophe/strophe.d.ts b/strophe/strophe.d.ts new file mode 100644 index 0000000000..dc9eebad7d --- /dev/null +++ b/strophe/strophe.d.ts @@ -0,0 +1,1088 @@ +// Type definitions for Strophe.js v1.2.0 +// Project: http://strophe.im/strophejs/ +// Definitions by: David Deutsch +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** Function: $build + * Create a Strophe.Builder. + * This is an alias for 'new Strophe.Builder(name, attrs)'. + * + * Parameters: + * (String) name - The root element name. + * (Object) attrs - The attributes for the root element in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $build(name: string, attrs?: any): Strophe.Builder; + +/** Function: $msg + * Create a Strophe.Builder with a element as the root. + * + * Parmaeters: + * (Object) attrs - The element attributes in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $msg(attrs?: any): Strophe.Builder; + +/** Function: $iq + * Create a Strophe.Builder with an element as the root. + * + * Parameters: + * (Object) attrs - The element attributes in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $iq(attrs?: any): Strophe.Builder; + +/** Function: $pres + * Create a Strophe.Builder with a element as the root. + * + * Parameters: + * (Object) attrs - The element attributes in object notation. + * + * Returns: + * A new Strophe.Builder object. + */ +declare function $pres(attrs?: any): Strophe.Builder; + +declare module Strophe { + /** Constant: VERSION + * The version of the Strophe library. Unreleased builds will have + * a version of head-HASH where HASH is a partial revision. + */ + var VERSION: string; + + /** Constants: XMPP Namespace Constants + * Common namespace constants from the XMPP RFCs and XEPs. + * + * NS.HTTPBIND - HTTP BIND namespace from XEP 124. + * NS.BOSH - BOSH namespace from XEP 206. + * NS.CLIENT - Main XMPP client namespace. + * NS.AUTH - Legacy authentication namespace. + * NS.ROSTER - Roster operations namespace. + * NS.PROFILE - Profile namespace. + * NS.DISCO_INFO - Service discovery info namespace from XEP 30. + * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30. + * NS.MUC - Multi-User Chat namespace from XEP 45. + * NS.SASL - XMPP SASL namespace from RFC 3920. + * NS.STREAM - XMPP Streams namespace from RFC 3920. + * NS.BIND - XMPP Binding namespace from RFC 3920. + * NS.SESSION - XMPP Session namespace from RFC 3920. + * NS.XHTML_IM - XHTML-IM namespace from XEP 71. + * NS.XHTML - XHTML body namespace from XEP 71. + */ + var NS: { + HTTPBIND: string; + BOSH: string; + CLIENT: string; + AUTH: string; + ROSTER: string; + PROFILE: string; + DISCO_INFO: string; + DISCO_ITEMS: string; + MUC: string; + SASL: string; + STREAM: string; + FRAMING: string; + BIND: string; + SESSION: string; + VERSION: string; + STANZAS: string; + XHTML_IM: string; + XHTML: string; + } + + /** Constants: Connection Status Constants + * Connection status constants for use by the connection handler + * callback. + * + * Status.ERROR - An error has occurred + * Status.CONNECTING - The connection is currently being made + * Status.CONNFAIL - The connection attempt failed + * Status.AUTHENTICATING - The connection is authenticating + * Status.AUTHFAIL - The authentication attempt failed + * Status.CONNECTED - The connection has succeeded + * Status.DISCONNECTED - The connection has been terminated + * Status.DISCONNECTING - The connection is currently being terminated + * Status.ATTACHED - The connection has been attached + */ + enum Status { + ERROR, + CONNECTING, + CONNFAIL, + AUTHENTICATING, + AUTHFAIL, + CONNECTED, + DISCONNECTED, + DISCONNECTING, + ATTACHED, + REDIRECT + } + + /** Constants: Log Level Constants + * Logging level indicators. + * + * LogLevel.DEBUG - Debug output + * LogLevel.INFO - Informational output + * LogLevel.WARN - Warnings + * LogLevel.ERROR - Errors + * LogLevel.FATAL - Fatal errors + */ + enum LogLevel { + DEBUG, + INFO, + WARN, + ERROR, + FATAL + } + + /** Function: addNamespace + * This function is used to extend the current namespaces in + * Strophe.NS. It takes a key and a value with the key being the + * name of the new namespace, with its actual value. + * For example: + * Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub"); + * + * Parameters: + * (String) name - The name under which the namespace will be + * referenced under Strophe.NS + * (String) value - The actual namespace. + */ + function addNamespace(name: string, value: string): void; + + /** Function: forEachChild + * Map a function over some or all child elements of a given element. + * + * This is a small convenience function for mapping a function over + * some or all of the children of an element. If elemName is null, all + * children will be passed to the function, otherwise only children + * whose tag names match elemName will be passed. + * + * Parameters: + * (XMLElement) elem - The element to operate on. + * (String) elemName - The child element tag name filter. + * (Function) func - The function to apply to each child. This + * function should take a single argument, a DOM element. + */ + function forEachChild(elem: Element, elemName: string, func:(child: Element) => any): void; + + /** Function: isTagEqual + * Compare an element's tag name with a string. + * + * This function is case sensitive. + * + * Parameters: + * (XMLElement) el - A DOM element. + * (String) name - The element name. + * + * Returns: + * true if the element's tag name matches _el_, and false + * otherwise. + */ + function isTagEqual(el: Element, name: string): boolean; + + /** Function: xmlGenerator + * Get the DOM document to generate elements. + * + * Returns: + * The currently used DOM document. + */ + function xmlGenerator(): Document; + + /** Function: xmlElement + * Create an XML DOM element. + * + * This function creates an XML DOM element correctly across all + * implementations. Note that these are not HTML DOM elements, which + * aren't appropriate for XMPP stanzas. + * + * Parameters: + * (String) name - The name for the element. + * (Array|Object) attrs - An optional array or object containing + * key/value pairs to use as element attributes. The object should + * be in the format {'key': 'value'} or {key: 'value'}. The array + * should have the format [['key1', 'value1'], ['key2', 'value2']]. + * (String) text - The text child data for the element. + * + * Returns: + * A new XML DOM element. + */ + function xmlElement(name: string, attrs?: any, text?: string): Element; + function xmlElement(name: string, text?: string, attrs?: any): Element; + + /* Function: xmlescape + * Excapes invalid xml characters. + * + * Parameters: + * (String) text - text to escape. + * + * Returns: + * Escaped text. + */ + function xmlescape(text: string): string; + + /* Function: xmlunescape + * Unexcapes invalid xml characters. + * + * Parameters: + * (String) text - text to unescape. + * + * Returns: + * Unescaped text. + */ + function xmlunescape(text: string): string; + + /** Function: xmlTextNode + * Creates an XML DOM text node. + * + * Provides a cross implementation version of document.createTextNode. + * + * Parameters: + * (String) text - The content of the text node. + * + * Returns: + * A new XML DOM text node. + */ + function xmlTextNode(text: string): Text; + + /** Function: xmlHtmlNode + * Creates an XML DOM html node. + * + * Parameters: + * (String) html - The content of the html node. + * + * Returns: + * A new XML DOM text node. + */ + function xmlHtmlNode(html: string): Document; + + /** Function: getText + * Get the concatenation of all text children of an element. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * A String with the concatenated text of all text element children. + */ + function getText(elem: Element): string; + + /** Function: copyElement + * Copy an XML DOM element. + * + * This function copies a DOM element and all its descendants and returns + * the new copy. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * A new, copied DOM element tree. + */ + function copyElement(elem: Element): Element; + + /** Function: createHtml + * Copy an HTML DOM element into an XML DOM. + * + * This function copies a DOM element and all its descendants and returns + * the new copy. + * + * Parameters: + * (Element) elem - A DOM element. + * + * Returns: + * A new, copied DOM element tree. + */ + function createHtml(elem: Element): Element; + + /** Function: escapeNode + * Escape the node part (also called local part) of a JID. + * + * Parameters: + * (String) node - A node (or local part). + * + * Returns: + * An escaped node (or local part). + */ + function escapeNode(node: string): string; + + /** Function: unescapeNode + * Unescape a node part (also called local part) of a JID. + * + * Parameters: + * (String) node - A node (or local part). + * + * Returns: + * An unescaped node (or local part). + */ + function unescapeNode(node: string): string; + + /** Function: getNodeFromJid + * Get the node portion of a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the node. + */ + function getNodeFromJid(jid: string): string; + + /** Function: getDomainFromJid + * Get the domain portion of a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the domain. + */ + function getDomainFromJid(jid: string): string; + + /** Function: getResourceFromJid + * Get the resource portion of a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the resource. + */ + function getResourceFromJid(jid: string): string; + + /** Function: getBareJidFromJid + * Get the bare JID from a JID String. + * + * Parameters: + * (String) jid - A JID. + * + * Returns: + * A String containing the bare JID. + */ + function getBareJidFromJid(jid: string): string; + + /** Function: log + * User overrideable logging function. + * + * This function is called whenever the Strophe library calls any + * of the logging functions. The default implementation of this + * function does nothing. If client code wishes to handle the logging + * messages, it should override this with + * > Strophe.log = function (level, msg) { + * > (user code here) + * > }; + * + * Please note that data sent and received over the wire is logged + * via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput(). + * + * The different levels and their meanings are + * + * DEBUG - Messages useful for debugging purposes. + * INFO - Informational messages. This is mostly information like + * 'disconnect was called' or 'SASL auth succeeded'. + * WARN - Warnings about potential problems. This is mostly used + * to report transient connection errors like request timeouts. + * ERROR - Some error occurred. + * FATAL - A non-recoverable fatal error occurred. + * + * Parameters: + * (Integer) level - The log level of the log message. This will + * be one of the values in Strophe.LogLevel. + * (String) msg - The log message. + */ + function log(level: LogLevel, msg: string): void; + + /** Functions: debug, info, warn, error + * Log a message at the appropriate Strophe.LogLevel + * + * Parameters: + * (String) msg - The log message. + */ + function debug(msg: string): void; + function info(msg: string): void; + function warn(msg: string): void; + function error(msg: string): void; + function fatal(msg: string): void; + + /** Function: serialize + * Render a DOM element and all descendants to a String. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * The serialized element tree as a String. + */ + function serialize(elem: Element | Builder): string; + + /** Function: addConnectionPlugin + * Extends the Strophe.Connection object with the given plugin. + * + * Parameters: + * (String) name - The name of the extension. + * (Object) ptype - The plugin's prototype. + */ + function addConnectionPlugin(name: string, ptype: any): void; + + /** Class: Strophe.Builder + * XML DOM builder. + * + * This object provides an interface similar to JQuery but for building + * DOM element easily and rapidly. All the functions except for toString() + * and tree() return the object, so calls can be chained. Here's an + * example using the $iq() builder helper. + * > $iq({to: 'you', from: 'me', type: 'get', id: '1'}) + * > .c('query', {xmlns: 'strophe:example'}) + * > .c('example') + * > .toString() + * The above generates this XML fragment + * > + * > + * > + * > + * > + * The corresponding DOM manipulations to get a similar fragment would be + * a lot more tedious and probably involve several helper variables. + * + * Since adding children makes new operations operate on the child, up() + * is provided to traverse up the tree. To add two children, do + * > builder.c('child1', ...).up().c('child2', ...) + * The next operation on the Builder will be relative to the second child. + */ + class Builder { + /** Constructor: Strophe.Builder + * Create a Strophe.Builder object. + * + * The attributes should be passed in object notation. For example + * > var b = new Builder('message', {to: 'you', from: 'me'}); + * or + * > var b = new Builder('messsage', {'xml:lang': 'en'}); + * + * Parameters: + * (String) name - The name of the root element. + * (Object) attrs - The attributes for the root element in object notation. + * + * Returns: + * A new Strophe.Builder. + */ + constructor(name: string, attrs?: any); + + /** Function: tree + * Return the DOM tree. + * + * This function returns the current DOM tree as an element object. This + * is suitable for passing to functions like Strophe.Connection.send(). + * + * Returns: + * The DOM tree as a element object. + */ + tree(): Element; + + /** Function: toString + * Serialize the DOM tree to a String. + * + * This function returns a string serialization of the current DOM + * tree. It is often used internally to pass data to a + * Strophe.Request object. + * + * Returns: + * The serialized DOM tree in a String. + */ + toString(): string; + + /** Function: up + * Make the current parent element the new current element. + * + * This function is often used after c() to traverse back up the tree. + * For example, to add two children to the same element + * > builder.c('child1', {}).up().c('child2', {}); + * + * Returns: + * The Stophe.Builder object. + */ + up(): Builder; + + /** Function: attrs + * Add or modify attributes of the current element. + * + * The attributes should be passed in object notation. This function + * does not move the current element pointer. + * + * Parameters: + * (Object) moreattrs - The attributes to add/modify in object notation. + * + * Returns: + * The Strophe.Builder object. + */ + attrs(moreattrs: any): Builder; + + /** Function: c + * Add a child to the current element and make it the new current + * element. + * + * This function moves the current element pointer to the child, + * unless text is provided. If you need to add another child, it + * is necessary to use up() to go back to the parent in the tree. + * + * Parameters: + * (String) name - The name of the child. + * (Object) attrs - The attributes of the child in object notation. + * (String) text - The text to add to the child. + * + * Returns: + * The Strophe.Builder object. + */ + c(name: string, attrs?: any, text?: string): Builder; + + /** Function: cnode + * Add a child to the current element and make it the new current + * element. + * + * This function is the same as c() except that instead of using a + * name and an attributes object to create the child it uses an + * existing DOM element object. + * + * Parameters: + * (XMLElement) elem - A DOM element. + * + * Returns: + * The Strophe.Builder object. + */ + cnode(elem: Node): Builder; + + /** Function: t + * Add a child text element. + * + * This *does not* make the child the new current element since there + * are no children of text elements. + * + * Parameters: + * (String) text - The text data to append to the current element. + * + * Returns: + * The Strophe.Builder object. + */ + t(text: string): Builder; + + /** Function: h + * Replace current element contents with the HTML passed in. + * + * This *does not* make the child the new current element + * + * Parameters: + * (String) html - The html to insert as contents of current element. + * + * Returns: + * The Strophe.Builder object. + */ + h(html: string): Builder; + } + + interface ConnectionOptions { + protocol?: string; + sync?: boolean; + } + + /** Class: Strophe.Connection + * XMPP Connection manager. + * + * This class is the main part of Strophe. It manages a BOSH connection + * to an XMPP server and dispatches events to the user callbacks as + * data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1 + * and legacy authentication. + * + * After creating a Strophe.Connection object, the user will typically + * call connect() with a user supplied callback to handle connection level + * events like authentication failure, disconnection, or connection + * complete. + * + * The user will also have several event handlers defined by using + * addHandler() and addTimedHandler(). These will allow the user code to + * respond to interesting stanzas or do something periodically with the + * connection. These handlers will be active once authentication is + * finished. + * + * To send data to the connection, use send(). + */ + class Connection { + + jid: string; + authzid: string; + pass: string; + authcid: string; + domain: string; + servtype: string; + maxRetries: number; + //todo: what other members are meant to be public? + + /** Constructor: Strophe.Connection + * Create and initialize a Strophe.Connection object. + * + * The transport-protocol for this connection will be chosen automatically + * based on the given service parameter. URLs starting with "ws://" or + * "wss://" will use WebSockets, URLs starting with "http://", "https://" + * or without a protocol will use BOSH. + * + * To make Strophe connect to the current host you can leave out the protocol + * and host part and just pass the path, e.g. + * + * > var conn = new Strophe.Connection("/http-bind/"); + * + * WebSocket options: + * + * If you want to connect to the current host with a WebSocket connection you + * can tell Strophe to use WebSockets through a "protocol" attribute in the + * optional options parameter. Valid values are "ws" for WebSocket and "wss" + * for Secure WebSocket. + * So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call + * + * > var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"}); + * + * Note that relative URLs _NOT_ starting with a "/" will also include the path + * of the current site. + * + * Also because downgrading security is not permitted by browsers, when using + * relative URLs both BOSH and WebSocket connections will use their secure + * variants if the current connection to the site is also secure (https). + * + * BOSH options: + * + * by adding "sync" to the options, you can control if requests will + * be made synchronously or not. The default behaviour is asynchronous. + * If you want to make requests synchronous, make "sync" evaluate to true: + * > var conn = new Strophe.Connection("/http-bind/", {sync: true}); + * You can also toggle this on an already established connection: + * > conn.options.sync = true; + * + * + * Parameters: + * (String) service - The BOSH or WebSocket service URL. + * (Object) options - A hash of configuration options + * + * Returns: + * A new Strophe.Connection object. + */ + constructor(service: string, options?: ConnectionOptions); + + /** Function: reset + * Reset the connection. + * + * This function should be called after a connection is disconnected + * before that connection is reused. + */ + reset(): void; + + /** Function: pause + * Pause the request manager. + * + * This will prevent Strophe from sending any more requests to the + * server. This is very useful for temporarily pausing + * BOSH-Connections while a lot of send() calls are happening quickly. + * This causes Strophe to send the data in a single request, saving + * many request trips. + */ + pause(): void; + + /** Function: resume + * Resume the request manager. + * + * This resumes after pause() has been called. + */ + resume(): void; + + /** Function: getUniqueId + * Generate a unique ID for use in elements. + * + * All stanzas are required to have unique id attributes. This + * function makes creating these easy. Each connection instance has + * a counter which starts from zero, and the value of this counter + * plus a colon followed by the suffix becomes the unique id. If no + * suffix is supplied, the counter is used as the unique id. + * + * Suffixes are used to make debugging easier when reading the stream + * data, and their use is recommended. The counter resets to 0 for + * every new connection for the same reason. For connections to the + * same server that authenticate the same way, all the ids should be + * the same, which makes it easy to see changes. This is useful for + * automated testing as well. + * + * Parameters: + * (String) suffix - A optional suffix to append to the id. + * + * Returns: + * A unique string to be used for the id attribute. + */ + getUniqueId(suffix?: string | number): string; + + /** Function: connect + * Starts the connection process. + * + * As the connection process proceeds, the user supplied callback will + * be triggered multiple times with status updates. The callback + * should take two arguments - the status code and the error condition. + * + * The status code will be one of the values in the Strophe.Status + * constants. The error condition will be one of the conditions + * defined in RFC 3920 or the condition 'strophe-parsererror'. + * + * The Parameters _wait_, _hold_ and _route_ are optional and only relevant + * for BOSH connections. Please see XEP 124 for a more detailed explanation + * of the optional parameters. + * + * Parameters: + * (String) jid - The user's JID. This may be a bare JID, + * or a full JID. If a node is not supplied, SASL ANONYMOUS + * authentication will be attempted. + * (String) pass - The user's password. + * (Function) callback - The connect callback function. + * (Integer) wait - The optional HTTPBIND wait value. This is the + * time the server will wait before returning an empty result for + * a request. The default setting of 60 seconds is recommended. + * (Integer) hold - The optional HTTPBIND hold value. This is the + * number of connections the server will hold at one time. This + * should almost always be set to 1 (the default). + * (String) route - The optional route value. + */ + connect(jid?: string, pass?: string, callback?: (status: Status, condition: string) => any, wait?: number, hold?: number, route?: string): void; + + /** Function: attach + * Attach to an already created and authenticated BOSH session. + * + * This function is provided to allow Strophe to attach to BOSH + * sessions which have been created externally, perhaps by a Web + * application. This is often used to support auto-login type features + * without putting user credentials into the page. + * + * Parameters: + * (String) jid - The full JID that is bound by the session. + * (String) sid - The SID of the BOSH session. + * (String) rid - The current RID of the BOSH session. This RID + * will be used by the next request. + * (Function) callback The connect callback function. + * (Integer) wait - The optional HTTPBIND wait value. This is the + * time the server will wait before returning an empty result for + * a request. The default setting of 60 seconds is recommended. + * Other settings will require tweaks to the Strophe.TIMEOUT value. + * (Integer) hold - The optional HTTPBIND hold value. This is the + * number of connections the server will hold at one time. This + * should almost always be set to 1 (the default). + * (Integer) wind - The optional HTTBIND window value. This is the + * allowed range of request ids that are valid. The default is 5. + */ + attach(jid: string, sid: string, rid: string, callback?: (status: Status, condition: string) => any, wait?: number, hold?: number, wind?: number): void; + + /** Function: xmlInput + * User overrideable function that receives XML data coming into the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.xmlInput = function (elem) { + * > (user code) + * > }; + * + * Due to limitations of current Browsers' XML-Parsers the opening and closing + * tag for WebSocket-Connoctions will be passed as selfclosing here. + * + * BOSH-Connections will have all stanzas wrapped in a tag. See + * if you want to strip this tag. + * + * Parameters: + * (XMLElement) elem - The XML data received by the connection. + */ + xmlInput(elem: Element): void; + + /** Function: xmlOutput + * User overrideable function that receives XML data sent to the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.xmlOutput = function (elem) { + * > (user code) + * > }; + * + * Due to limitations of current Browsers' XML-Parsers the opening and closing + * tag for WebSocket-Connoctions will be passed as selfclosing here. + * + * BOSH-Connections will have all stanzas wrapped in a tag. See + * if you want to strip this tag. + * + * Parameters: + * (XMLElement) elem - The XMLdata sent by the connection. + */ + xmlOutput(elem: Element): void; + + /** Function: rawInput + * User overrideable function that receives raw data coming into the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.rawInput = function (data) { + * > (user code) + * > }; + * + * Parameters: + * (String) data - The data received by the connection. + */ + rawInput(data: string): void; + + /** Function: rawOutput + * User overrideable function that receives raw data sent to the + * connection. + * + * The default function does nothing. User code can override this with + * > Strophe.Connection.rawOutput = function (data) { + * > (user code) + * > }; + * + * Parameters: + * (String) data - The data sent by the connection. + */ + rawOutput(data: string): void; + + /** Function: send + * Send a stanza. + * + * This function is called to push data onto the send queue to + * go out over the wire. Whenever a request is sent to the BOSH + * server, all pending data is sent and the queue is flushed. + * + * Parameters: + * (XMLElement | + * [XMLElement] | + * Strophe.Builder) elem - The stanza to send. + */ + send(elem: Element | Element[]| Builder): void; + + /** Function: flush + * Immediately send any pending outgoing data. + * + * Normally send() queues outgoing data until the next idle period + * (100ms), which optimizes network use in the common cases when + * several send()s are called in succession. flush() can be used to + * immediately send all pending data. + */ + flush(): void; + + /** Function: sendIQ + * Helper function to send IQ stanzas. + * + * Parameters: + * (XMLElement) elem - The stanza to send. + * (Function) callback - The callback function for a successful request. + * (Function) errback - The callback function for a failed or timed + * out request. On timeout, the stanza will be null. + * (Integer) timeout - The time specified in milliseconds for a + * timeout to occur. + * + * Returns: + * The id used to send the IQ. + */ + sendIQ(elem: Element | Builder, callback?: (stanza: Element) => any, errback?: (stanza: Element) => any, timeout?: number): string; //todo: Is callback correct? + + /** Function: addTimedHandler + * Add a timed handler to the connection. + * + * This function adds a timed handler. The provided handler will + * be called every period milliseconds until it returns false, + * the connection is terminated, or the handler is removed. Handlers + * that wish to continue being invoked should return true. + * + * Because of method binding it is necessary to save the result of + * this function if you wish to remove a handler with + * deleteTimedHandler(). + * + * Note that user handlers are not active until authentication is + * successful. + * + * Parameters: + * (Integer) period - The period of the handler. + * (Function) handler - The callback function. + * + * Returns: + * A reference to the handler that can be used to remove it. + */ + addTimedHandler(period: number, handler: () => boolean): any; + + /** Function: deleteTimedHandler + * Delete a timed handler for a connection. + * + * This function removes a timed handler from the connection. The + * handRef parameter is *not* the function passed to addTimedHandler(), + * but is the reference returned from addTimedHandler(). + * + * Parameters: + * (Strophe.TimedHandler) handRef - The handler reference. + */ + deleteTimedHandler(handRef: any): void; + + + /** Function: addHandler + * Add a stanza handler for the connection. + * + * This function adds a stanza handler to the connection. The + * handler callback will be called for any stanza that matches + * the parameters. Note that if multiple parameters are supplied, + * they must all match for the handler to be invoked. + * + * The handler will receive the stanza that triggered it as its argument. + * *The handler should return true if it is to be invoked again; + * returning false will remove the handler after it returns.* + * + * As a convenience, the ns parameters applies to the top level element + * and also any of its immediate children. This is primarily to make + * matching /iq/query elements easy. + * + * The options argument contains handler matching flags that affect how + * matches are determined. Currently the only flag is matchBare (a + * boolean). When matchBare is true, the from parameter and the from + * attribute on the stanza will be matched as bare JIDs instead of + * full JIDs. To use this, pass {matchBare: true} as the value of + * options. The default value for matchBare is false. + * + * The return value should be saved if you wish to remove the handler + * with deleteHandler(). + * + * Parameters: + * (Function) handler - The user callback. + * (String) ns - The namespace to match. + * (String) name - The stanza name to match. + * (String) type - The stanza type attribute to match. + * (String) id - The stanza id attribute to match. + * (String) from - The stanza from attribute to match. + * (String) options - The handler options + * + * Returns: + * A reference to the handler that can be used to remove it. + */ + addHandler(handler: (stanza: Element) => boolean, ns: string, name: string, type?: string, id?: string, from?: string, options?: { matchBare: boolean }): any; //todo: is callback correct? Also, are the elements specified as optional truly optional? + + /** Function: deleteHandler + * Delete a stanza handler for a connection. + * + * This function removes a stanza handler from the connection. The + * handRef parameter is *not* the function passed to addHandler(), + * but is the reference returned from addHandler(). + * + * Parameters: + * (Strophe.Handler) handRef - The handler reference. + */ + deleteHandler(handRef: any): void; + + /** Function: disconnect + * Start the graceful disconnection process. + * + * This function starts the disconnection process. This process starts + * by sending unavailable presence and sending BOSH body of type + * terminate. A timeout handler makes sure that disconnection happens + * even if the BOSH server does not respond. + * If the Connection object isn't connected, at least tries to abort all pending requests + * so the connection object won't generate successful requests (which were already opened). + * + * The user supplied connection callback will be notified of the + * progress as this process happens. + * + * Parameters: + * (String) reason - The reason the disconnect is occuring. + */ + disconnect(reason: string): void; + } + + /** Class: Strophe.SASLMechanism + * + * encapsulates SASL authentication mechanisms. + * + * User code may override the priority for each mechanism or disable it completely. + * See for information about changing priority and for informatian on + * how to disable a mechanism. + * + * By default, all mechanisms are enabled and the priorities are + * + * SCRAM-SHA1 - 40 + * DIGEST-MD5 - 30 + * Plain - 20 + */ + class SASLMechanism { + /** + * PrivateConstructor: Strophe.SASLMechanism + * SASL auth mechanism abstraction. + * + * Parameters: + * (String) name - SASL Mechanism name. + * (Boolean) isClientFirst - If client should send response first without challenge. + * (Number) priority - Priority. + * + * Returns: + * A new Strophe.SASLMechanism object. + */ + constructor(name: string, isClientFirst: boolean, priority: number); + + /** + * Function: test + * Checks if mechanism able to run. + * To disable a mechanism, make this return false; + * + * To disable plain authentication run + * > Strophe.SASLPlain.test = function() { + * > return false; + * > } + * + * See for a list of available mechanisms. + * + * Parameters: + * (Strophe.Connection) connection - Target Connection. + * + * Returns: + * (Boolean) If mechanism was able to run. + */ + test(connection: Connection): boolean; + + /** PrivateFunction: onStart + * Called before starting mechanism on some connection. + * + * Parameters: + * (Strophe.Connection) connection - Target Connection. + */ + protected onStart(connection: Connection): void; + + /** PrivateFunction: onChallenge + * Called by protocol implementation on incoming challenge. If client is + * first (isClientFirst == true) challenge will be null on the first call. + * + * Parameters: + * (Strophe.Connection) connection - Target Connection. + * (String) challenge - current challenge to handle. + * + * Returns: + * (String) Mechanism response. + */ + protected onChallenge(connection: Connection, challenge: string): string; + + /** PrivateFunction: onFailure + * Protocol informs mechanism implementation about SASL failure. + */ + protected onFailure(): void; + + /** PrivateFunction: onSuccess + * Protocol informs mechanism implementation about SASL success. + */ + protected onSuccess(): void; + } + + /** Constants: SASL mechanisms + * Available authentication mechanisms + * + * Strophe.SASLAnonymous - SASL Anonymous authentication. + * Strophe.SASLPlain - SASL Plain authentication. + * Strophe.SASLMD5 - SASL Digest-MD5 authentication + * Strophe.SASLSHA1 - SASL SCRAM-SHA1 authentication + */ + var SASLAnonymous: SASLMechanism; + var SASLPlain: SASLMechanism; + var SASLSHA1: SASLMechanism; + var SASLMD5: SASLMechanism; +} + diff --git a/sweetalert/sweetalert-tests.ts b/sweetalert/sweetalert-tests.ts new file mode 100644 index 0000000000..1ccb93ba39 --- /dev/null +++ b/sweetalert/sweetalert-tests.ts @@ -0,0 +1,93 @@ +/// + +// A basic message +swal("Here's a message!"); + +// A title with a text under +swal("Here's a message!", "It's pretty, isn't it?"); + +// A success message! +swal("Good job!", "You clicked the button!", "success"); + +// A warning message, with a function attached to the "Confirm"-button... +swal({ + title: "Are you sure?", + text: "You will not be able to recover this imaginary file!", + type: "warning", + showCancelButton: true, + confirmButtonColor: "#DD6B55", + confirmButtonText: "Yes, delete it!", + closeOnConfirm: false +}, + function () { + swal("Deleted!", "Your imaginary file has been deleted.", "success"); + }); + +// ... and by passing a parameter, you can execute something else for "Cancel". +swal({ + title: "Are you sure?", + text: "You will not be able to recover this imaginary file!", + type: "warning", + showCancelButton: true, + confirmButtonColor: "#DD6B55", + confirmButtonText: "Yes, delete it!", + cancelButtonText: "No, cancel plx!", + closeOnConfirm: false, + closeOnCancel: false +}, + function (isConfirm) { + if (isConfirm) { + swal("Deleted!", "Your imaginary file has been deleted.", "success"); + } else { + swal("Cancelled", "Your imaginary file is safe :)", "error"); + } + }); + +// A message with a custom icon +swal({ + title: "Sweet!", + text: "Here's a custom image.", + imageUrl: "images/thumbs-up.jpg" +}); + +// An HTML message +swal({ + title: "HTML Title!", + text: "A custom html message.", + html: true +}); + +// A message with auto close timer +swal({ + title: "Auto close alert!", + text: "I will close in 2 seconds.", + timer: 2000, + showConfirmButton: false +}); + +// A replacement for the "prompt" function +swal({ + title: "An input!", + text: "Write something interesting:", + type: "input", + showCancelButton: true, + closeOnConfirm: false, + animation: "slide-from-top" +}, + function (inputValue) { + if (inputValue === false) return false; + + if (inputValue === "") { + swal.showInputError("You need to write something!"); + return false; + } + + swal("Nice!", "You wrote: " + inputValue, "success"); + } + ); + +swal.setDefaults({ confirmButtonColor: "#000000" }); + +swal.close(); + +swal.showInputError("Invalid email!"); \ No newline at end of file diff --git a/sweetalert/sweetalert.d.ts b/sweetalert/sweetalert.d.ts new file mode 100644 index 0000000000..d5b4cd607f --- /dev/null +++ b/sweetalert/sweetalert.d.ts @@ -0,0 +1,181 @@ +// Type definitions for SweetAlert 0.5.0 +// Project: https://github.com/t4t5/sweetalert/ +// Definitions by: Markus Peloso +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var sweetAlert: SweetAlert.SweetAlertStatic; +declare var swal: SweetAlert.SweetAlertStatic; + +declare module "sweetalert" { + export = swal; +} + +declare module SweetAlert { + interface SettingsBase { + /** + * A description for the modal. + * Default: null + */ + text?: string; + + /** + * The type of the modal. SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". You can also set it as "input" to get a prompt modal. + * Default: null + */ + type?: string; + + /** + * If set to true, the user can dismiss the modal by pressing the Escape key. + * Default: true + */ + allowEsxcapeKey?: boolean; + + /** + * A custom CSS class for the modal. + * Default: null + */ + customClass?: string; + + /** + * If set to true, the user can dismiss the modal by clicking outside it. + * Default: false + */ + allowOutsideClick?: boolean; + + /** + * If set to true, a "Cancel"-button will be shown, which the user can click on to dismiss the modal. + * Default: false + */ + showCancelButton?: boolean; + + /** + * If set to false, the "OK/Confirm"-button will be hidden. Make sure you set a timer or set allowOutsideClick to true when using this, in order not to annoy the user. + * Default: true + */ + showConfirmButton?: boolean; + + /** + * Use this to change the text on the "Confirm"-button. If showCancelButton is set as true, the confirm button will automatically show "Confirm" instead of "OK". + * Default: "OK" + */ + confirmButtonText?: string; + + /** + * Use this to change the background color of the "Confirm"-button (must be a HEX value). + * Default: "#AEDEF4" + */ + confirmButtonColor?: string; + + /** + * Use this to change the text on the "Cancel"-button. + * Default: "Cancel" + */ + cancelButtonText?: string; + + /** + * Set to false if you want the modal to stay open even if the user presses the "Confirm"-button. This is especially useful if the function attached to the "Confirm"-button is another SweetAlert. + * Default: true + */ + closeOnConfirm?: boolean; + + /** + * Add a customized icon for the modal.Should contain a string with the path to the image. + * Default: null + */ + imageUrl?: string; + + /** + * If imageUrl is set, you can specify imageSize to describes how big you want the icon to be in px. Pass in a string with two values separated by an "x". The first value is the width, the second is the height. + * Default: "80x80" + */ + imageSize?: string; + + /** + * Auto close timer of the modal.Set in ms (milliseconds). + * Default: null + */ + timer?: number; + + /** + * If set to true, will not escape title and text parameters. (Set to false if you're worried about XSS attacks.) + * Default: false + */ + html?: boolean; + + /** + * If set to false, the modal's animation will be disabled. Possible animations: "slide-from-top", "slide-from-bottom", "pop" (use true instead) and "none" (use false instead). + * Default: true, "pop" + */ + animation?: boolean | string; + + /** + * Change the type of the input field when using type: "input" (this can be useful if you want users to type in their password for example). + * Default: "text" + */ + inputType?: string; + } + + interface Settings extends SettingsBase { + /** + * The title of the modal. + */ + title: string; + } + + interface SetDefaultsSettings extends SettingsBase { + /** + * The title of the modal. + * Default: null + */ + title?: string; + } + + /** + * Is true or false if the user confirms or cancels the alert. Except for the type "input", then when the user confirms the alert, this variable contains the value of the input element. + */ + type CallbackArgument = boolean | string; + + interface SweetAlertStatic { + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param title The title of the modal. + */ + (title: string): void; + + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param title The title of the modal. + * @param text A description for the modal. + */ + (title: string, text: string): void; + + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param title The title of the modal. + * @param text A description for the modal. + * @param type The type of the modal. SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". You can also set it as "input" to get a prompt modal. + */ + (title: string, text: string, type: string): void; + + /** + * SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. An awesome replacement for JavaScript's alert. + * @param callback The callback from the users action. The value is true or false if the user confirms or cancels the alert. Except for the type "input", then when the user confirms the alert, the argument contains the value of the input element. + */ + (settings: Settings, callback?: (isConfirmOrInputValue: CallbackArgument) => any): void; + + /** + * If you end up using a lot of the same settings when calling SweetAlert, you can use setDefaults at the start of your program to set them once and for all! + */ + setDefaults(settings: SetDefaultsSettings): void; + + /** + * Close the currently open SweetAlert programmatically. + */ + close(): void; + + /** + * Show an error message after validating the input field, if the user's data is bad. + */ + showInputError(errorMessage: string): void; + } +} \ No newline at end of file diff --git a/switchery/switchery-tests.ts b/switchery/switchery-tests.ts new file mode 100644 index 0000000000..2a06795027 --- /dev/null +++ b/switchery/switchery-tests.ts @@ -0,0 +1,71 @@ +/// + +// +// Examples from https://github.com/abpetkov/switchery +// + +function multipleSwitches() { + + var elems = Array.prototype.slice.call( document.querySelectorAll( '.js-switch' ) ); + + elems.forEach( (html: Element) => { + var switchery = new Switchery( html ); + } ); +} + + +function disabledSwitch() { + + var elem = document.querySelector( '.js-switch' ) + + //inactive switch + var switchery = new Switchery( elem, {disabled: true} ); + + //Customize the default opacity of the disabled switch, using the disabledOpacity option. + switchery = new Switchery( elem, {disabled: true, disabledOpacity: 0.75} ); +} + + +function coloredSwitch() { + + var elem = document.querySelector( '.js-switch' ) + + //You can change the primary color of the switch to fit your design perfectly: + var switchery = new Switchery( elem, {color: '#41b7f1'} ); + + //Or the secondary color, which will change the switch background color and border color: + switchery = new Switchery( elem, {secondaryColor: '#bbf0f0'} ); + + //Since version 0.6.3, you're even allowed to change the jack color from JS, as follows: + switchery = new Switchery( elem, {jackColor: '#fffc00'} ); +} + +function switchSizes() { + + var elem = document.querySelector( '.js-switch' ) + + var switchery = new Switchery( elem, {size: 'small'} ); + switchery = new Switchery( elem, {size: 'large'} ); +} + +function checkingState() { + + var elem = document.querySelector( '.js-switch' ) + + //On click: + + var clickCheckbox = document.querySelector( '.js-check-click' ) + var clickButton = document.querySelector( '.js-check-click-button' ); + + clickButton.addEventListener( 'click', () => { + alert( clickCheckbox.checked ); + } ); + + //On change: + + var changeCheckbox = document.querySelector( '.js-check-change' ); + + changeCheckbox.onchange = function () { + alert( changeCheckbox.checked ); + }; +} \ No newline at end of file diff --git a/switchery/switchery.d.ts b/switchery/switchery.d.ts new file mode 100644 index 0000000000..4d953aff88 --- /dev/null +++ b/switchery/switchery.d.ts @@ -0,0 +1,64 @@ +// Type definitions for switchery 0.7.0 +// Project: https://github.com/abpetkov/switchery +// Definitions by: Bruno Grieder +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Switchery { + + export interface Options { + + /** + * color of the switch element (HEX or RGB value) + * @default '#64bd63' + */ + color? : string; + /** + * secondary color for background color and border, when the switch is off + * @default '#dfdfdf' + */ + secondaryColor? : string; + /** + * color of the jack/handle element + * @default '#fff' + */ + jackColor? : string; + /** + * class name for the switch element (by default styled in switchery.css) + * @default 'switchery' + */ + className? : string; + /** + * enable or disable click events and changing the state of the switch (boolean value) + * @default false + */ + disabled? : boolean; + /** + * opacity of the switch when it's disabled (0 to 1) + * @default 0.5 + */ + disabledOpacity? : number; + /** + * length of time that the transition will take, ex. '0.4s', '1s', '2.2s' (Note: transition speed of the handle is twice shorter) + * @default '0.4s' + */ + speed? : string; + /** + * size of the switch element (small or large) + * @default 'default' + */ + size? : string; + } + + +} + +declare class Switchery { + + constructor(node: Node, options?: Switchery.Options); + +} + +declare module "switchery" { + + export = Switchery +} \ No newline at end of file diff --git a/threejs/three.d.ts b/threejs/three.d.ts index b748444071..a9255f3b5e 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1211,11 +1211,11 @@ declare module THREE { getObjectByProperty( name: string, value: string, recursive?: boolean ): Object3D; - getWorldPosition(optionalTarget: Vector3): Vector3; - getWorldQuaternion(optionalTarget: Quaternion): Quaternion; - getWorldRotation(optionalTarget: Euler): Euler; - getWorldScale(optionalTarget: Vector3): Vector3; - getWorldDirection(optionalTarget: Vector3): Vector3; + getWorldPosition(optionalTarget?: Vector3): Vector3; + getWorldQuaternion(optionalTarget?: Quaternion): Quaternion; + getWorldRotation(optionalTarget?: Euler): Euler; + getWorldScale(optionalTarget?: Vector3): Vector3; + getWorldDirection(optionalTarget?: Vector3): Vector3; /** * Translates object along arbitrary axis by distance. diff --git a/titanium/titanium-tests.ts b/titanium/titanium-tests.ts index a4057b80cb..087ba05c27 100644 --- a/titanium/titanium-tests.ts +++ b/titanium/titanium-tests.ts @@ -26,7 +26,7 @@ function test_window() { } function test_tableview() { - var data = []; + var data : Ti.UI.View[] = []; for (var i = 0; i < 10; i++) { var row = Ti.UI.createTableViewRow(); var label = Ti.UI.createLabel({ @@ -73,12 +73,12 @@ function test_network() { var url = "http://www.appcelerator.com"; var client = Ti.Network.createHTTPClient({ // function called when the response data is available - onload : function(e) { + onload : function(e: SuccessResponse) { alert(this.responseText); }, // function called when an error occurs, including a timeout - onerror : function(e) { - alert(e.rror); + onerror : function(e: FailureResponse) { + alert(e.error); }, timeout : 5000 // in milliseconds }); diff --git a/titanium/titanium.d.ts b/titanium/titanium.d.ts index 5ebe930241..a325611df3 100644 --- a/titanium/titanium.d.ts +++ b/titanium/titanium.d.ts @@ -1,33 +1,36 @@ -// Type definitions for Titanium Movile 3.1.3.GA +// Type definitions for Titanium Mobile 3.5.0 // Project: http://www.appcelerator.com/ -// Definitions by: Airam Rguez +// Definitions by: Craig Younkins // Definitions: https://github.com/borisyankov/DefinitelyTyped -// This file has been automatically generated. declare module Ti { + export var apiName : string; export var bubbleParent : boolean; export var buildDate : string; export var buildHash : string; export var userAgent : string; - export var version : number; + export var version : string; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; export function createBuffer (params: CreateBufferArgs) : Ti.Buffer; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBubbleParent () : boolean; export function getBuildDate () : string; export function getBuildHash () : string; export function getUserAgent () : string; - export function getVersion () : number; + export function getVersion () : string; export function include (name: string) : void; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; export function setBubbleParent (bubbleParent: boolean) : void; export function setUserAgent (userAgent: string) : void; export module XML { + export var apiName : string; export var bubbleParent : boolean; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBubbleParent () : boolean; export function parseString (xml: string) : Ti.XML.Document; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; @@ -175,6 +178,9 @@ declare module Ti { } export interface Text extends Ti.XML.CharacterData { splitText (offset: number) : Ti.XML.Text; + } + export enum Comment { + } export enum DocumentFragment { @@ -184,9 +190,6 @@ declare module Ti { systemId : string; getPublicId () : string; getSystemId () : string; - } - export enum Comment { - } export interface NodeList extends Ti.Proxy { length : number; @@ -349,6 +352,12 @@ declare module Ti { export var TEXT_AUTOCAPITALIZATION_NONE : number; export var TEXT_AUTOCAPITALIZATION_SENTENCES : number; export var TEXT_AUTOCAPITALIZATION_WORDS : number; + export var TEXT_STYLE_BODY : string; + export var TEXT_STYLE_CAPTION1 : string; + export var TEXT_STYLE_CAPTION2 : string; + export var TEXT_STYLE_FOOTNOTE : string; + export var TEXT_STYLE_HEADLINE : string; + export var TEXT_STYLE_SUBHEADLINE : string; export var TEXT_VERTICAL_ALIGNMENT_BOTTOM : any; export var TEXT_VERTICAL_ALIGNMENT_CENTER : any; export var TEXT_VERTICAL_ALIGNMENT_TOP : any; @@ -370,6 +379,7 @@ declare module Ti { export var URL_ERROR_TIMEOUT : number; export var URL_ERROR_UNKNOWN : number; export var URL_ERROR_UNSUPPORTED_SCHEME : number; + export var apiName : string; export var backgroundColor : string; export var backgroundImage : string; export var bubbleParent : boolean; @@ -378,7 +388,7 @@ declare module Ti { export var orientation : number; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; - export function convertUnits (convertFromValue: string, convertToUnits: string) : number; + export function convertUnits (convertFromValue: string, convertToUnits: number) : number; export function create2DMatrix (parameters?: MatrixCreationDict) : Ti.UI._2DMatrix; export function create3DMatrix (parameters?: Dictionary) : Ti.UI._3DMatrix; export function createActivityIndicator (parameters?: Dictionary) : Ti.UI.ActivityIndicator; @@ -401,6 +411,7 @@ declare module Ti { export function createPickerColumn (parameters?: Dictionary) : Ti.UI.PickerColumn; export function createPickerRow (parameters?: Dictionary) : Ti.UI.PickerRow; export function createProgressBar (parameters?: Dictionary) : Ti.UI.ProgressBar; + export function createRefreshControl (parameters?: Dictionary) : Ti.UI.RefreshControl; export function createSMSDialog (parameters?: Dictionary) : Ti.UI.SMSDialog; export function createScrollView (parameters?: Dictionary) : Ti.UI.ScrollView; export function createScrollableView (parameters?: Dictionary) : Ti.UI.ScrollableView; @@ -420,6 +431,7 @@ declare module Ti { export function createWebView (parameters?: Dictionary) : Ti.UI.WebView; export function createWindow (parameters?: Dictionary) : Ti.UI.Window; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBackgroundColor () : string; export function getBackgroundImage () : string; export function getBubbleParent () : boolean; @@ -439,6 +451,7 @@ declare module Ti { export var POPOVER_ARROW_DIRECTION_RIGHT : number; export var POPOVER_ARROW_DIRECTION_UNKNOWN : number; export var POPOVER_ARROW_DIRECTION_UP : number; + export var apiName : string; export var bubbleParent : boolean; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; @@ -446,6 +459,7 @@ declare module Ti { export function createPopover (parameters?: Dictionary) : Ti.UI.iPad.Popover; export function createSplitWindow (parameters?: Dictionary) : Ti.UI.iPad.SplitWindow; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBubbleParent () : boolean; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; export function setBubbleParent (bubbleParent: boolean) : void; @@ -460,220 +474,447 @@ declare module Ti { } export interface DocumentViewer extends Ti.UI.View { setUrl (url: string) : void; - show(animated?: boolean, view?: any) : void; + show () : void; } - export interface Popover extends Ti.UI.View { + export interface Popover extends Ti.Proxy { arrowDirection : number; + contentView : Ti.UI.View; + height : any; leftNavButton : any; + passthroughViews : Array; rightNavButton : any; title : string; + width : any; + add () : void; getArrowDirection () : number; + getContentView () : Ti.UI.View; + getHeight () : any; getLeftNavButton () : any; + getPassthroughViews () : Array; getRightNavButton () : any; getTitle () : string; + getWidth () : any; + hide (options: PopoverParams) : void; + remove () : void; + setArrowDirection (arrowDirection: number) : void; + setContentView (contentView: Ti.UI.View) : void; + setHeight (height: number) : void; + setHeight (height: string) : void; setLeftNavButton (leftNavButton: any) : void; setPassthroughViews (passthroughViews: Array) : void; setRightNavButton (rightNavButton: any) : void; setTitle (title: string) : void; + setWidth (width: number) : void; + setWidth (width: string) : void; + show (params: PopoverParams) : void; } } - export interface ScrollableView extends Ti.UI.View { - cacheSize : number; - clipViews : boolean; - currentPage : number; - disableBounce : boolean; - hitRect : Dimension; - overScrollMode : number; - overlayEnabled : boolean; - pagingControlAlpha : number; - pagingControlColor : string; - pagingControlHeight : number; - pagingControlOnTop : boolean; - pagingControlTimeout : number; - scrollingEnabled : boolean; - showPagingControl : boolean; - views : Array; - addView (view: Ti.UI.View) : void; - getCacheSize () : number; - getClipViews () : boolean; - getCurrentPage () : number; - getDisableBounce () : boolean; - getHitRect () : Dimension; - getOverScrollMode () : number; - getOverlayEnabled () : boolean; - getPagingControlAlpha () : number; - getPagingControlColor () : string; - getPagingControlHeight () : number; - getPagingControlOnTop () : boolean; - getPagingControlTimeout () : number; - getScrollingEnabled () : boolean; - getShowPagingControl () : boolean; - getViews () : Array; - moveNext () : void; - movePrevious () : void; - removeView (view: number) : void; - removeView (view: Ti.UI.View) : void; - scrollToView (view: number) : void; - scrollToView (view: Ti.UI.View) : void; - setCacheSize (cacheSize: number) : void; - setCurrentPage (currentPage: number) : void; - setDisableBounce (disableBounce: boolean) : void; - setHitRect (hitRect: Dimension) : void; - setOverScrollMode (overScrollMode: number) : void; - setOverlayEnabled (overlayEnabled: boolean) : void; - setPagingControlAlpha (pagingControlAlpha: number) : void; - setPagingControlColor (pagingControlColor: string) : void; - setPagingControlHeight (pagingControlHeight: number) : void; - setPagingControlOnTop (pagingControlOnTop: boolean) : void; - setScrollingEnabled (scrollingEnabled: boolean) : void; - setShowPagingControl (showPagingControl: boolean) : void; - setViews (views: Array) : void; - } - export interface View extends Ti.Proxy { - accessibilityHidden : boolean; - accessibilityHint : string; - accessibilityLabel : string; - accessibilityValue : string; - anchorPoint : Point; - animatedCenter : Point; - backgroundColor : string; - backgroundDisabledColor : string; - backgroundDisabledImage : string; - backgroundFocusedColor : string; - backgroundFocusedImage : string; - backgroundGradient : Gradient; - backgroundImage : string; - backgroundLeftCap : number; - backgroundRepeat : boolean; - backgroundSelectedColor : string; - backgroundSelectedImage : string; - backgroundTopCap : number; - borderColor : string; - borderRadius : number; - borderWidth : number; - bottom : any; - center : Point; - children : Array; - enabled : boolean; - focusable : boolean; - height : any; - horizontalWrap : boolean; - keepScreenOn : boolean; - layout : string; - left : any; - opacity : number; - rect : Dimension; - right : any; - size : Dimension; - softKeyboardOnFocus : number; - tintColor : any; - top : any; - touchEnabled : boolean; - transform : any; - visible : boolean; - width : any; - zIndex : number; - add (view: Ti.UI.View) : void; - animate (animation: Ti.UI.Animation, callback: (...args : any[]) => any) : void; - animate (animation: Dictionary, callback: (...args : any[]) => any) : void; - convertPointToView (point: Point, destinationView: Ti.UI.View) : Point; - finishLayout () : void; - getAccessibilityHidden () : boolean; - getAccessibilityHint () : string; - getAccessibilityLabel () : string; - getAccessibilityValue () : string; - getAnchorPoint () : Point; - getAnimatedCenter () : Point; - getBackgroundColor () : string; - getBackgroundDisabledColor () : string; - getBackgroundDisabledImage () : string; - getBackgroundFocusedColor () : string; - getBackgroundFocusedImage () : string; - getBackgroundGradient () : Gradient; - getBackgroundImage () : string; - getBackgroundLeftCap () : number; - getBackgroundRepeat () : boolean; - getBackgroundSelectedColor () : string; - getBackgroundSelectedImage () : string; - getBackgroundTopCap () : number; - getBorderColor () : string; - getBorderRadius () : number; - getBorderWidth () : number; - getBottom () : any; - getCenter () : Point; - getChildren () : Array; - getEnabled () : boolean; - getFocusable () : boolean; - getHeight () : any; - getHorizontalWrap () : boolean; - getKeepScreenOn () : boolean; - getLayout () : string; - getLeft () : any; - getOpacity () : number; - getRect () : Dimension; - getRight () : any; - getSize () : Dimension; - getSoftKeyboardOnFocus () : number; - getTintColor () : string; - getTop () : any; - getTouchEnabled () : boolean; - getTransform () : any; - getVisible () : boolean; - getWidth () : any; - getZIndex () : number; - hide () : void; - remove (view: Ti.UI.View) : void; - removeAllChildren () : void; - setAccessibilityHidden (accessibilityHidden: boolean) : void; - setAccessibilityHint (accessibilityHint: string) : void; - setAccessibilityLabel (accessibilityLabel: string) : void; - setAccessibilityValue (accessibilityValue: string) : void; - setAnchorPoint (anchorPoint: Point) : void; - setBackgroundColor (backgroundColor: string) : void; - setBackgroundDisabledColor (backgroundDisabledColor: string) : void; - setBackgroundDisabledImage (backgroundDisabledImage: string) : void; - setBackgroundFocusedColor (backgroundFocusedColor: string) : void; - setBackgroundFocusedImage (backgroundFocusedImage: string) : void; - setBackgroundGradient (backgroundGradient: Gradient) : void; - setBackgroundImage (backgroundImage: string) : void; - setBackgroundLeftCap (backgroundLeftCap: number) : void; - setBackgroundRepeat (backgroundRepeat: boolean) : void; - setBackgroundSelectedColor (backgroundSelectedColor: string) : void; - setBackgroundSelectedImage (backgroundSelectedImage: string) : void; - setBackgroundTopCap (backgroundTopCap: number) : void; - setBorderColor (borderColor: string) : void; - setBorderRadius (borderRadius: number) : void; - setBorderWidth (borderWidth: number) : void; - setBottom (bottom: number) : void; - setBottom (bottom: string) : void; - setCenter (center: Point) : void; - setEnabled (enabled: boolean) : void; - setFocusable (focusable: boolean) : void; - setHeight (height: number) : void; - setHeight (height: string) : void; - setHorizontalWrap (horizontalWrap: boolean) : void; - setKeepScreenOn (keepScreenOn: boolean) : void; - setLayout (layout: string) : void; - setLeft (left: number) : void; - setLeft (left: string) : void; - setOpacity (opacity: number) : void; - setRight (right: number) : void; - setRight (right: string) : void; - setSoftKeyboardOnFocus (softKeyboardOnFocus: number) : void; - setTintColor (tintColor: string) : void; - setTop (top: number) : void; - setTop (top: string) : void; - setTouchEnabled (touchEnabled: boolean) : void; - setTransform (transform: Ti.UI._2DMatrix) : void; - setTransform (transform: Ti.UI._3DMatrix) : void; - setVisible (visible: boolean) : void; - setWidth (width: number) : void; - setWidth (width: string) : void; - setZIndex (zIndex: number) : void; - show (...args: Array) : void; - startLayout () : void; - toImage (callback?: (...args : any[]) => any, honorScaleFactor?: boolean) : Ti.Blob; - updateLayout (params: Dictionary) : void; + export module iOS { + export var AD_SIZE_LANDSCAPE : string; + export var AD_SIZE_PORTRAIT : string; + export var ANIMATION_CURVE_EASE_IN : number; + export var ANIMATION_CURVE_EASE_IN_OUT : number; + export var ANIMATION_CURVE_EASE_OUT : number; + export var ANIMATION_CURVE_LINEAR : number; + export var ATTRIBUTE_BACKGROUND_COLOR : number; + export var ATTRIBUTE_BASELINE_OFFSET : number; + export var ATTRIBUTE_EXPANSION : number; + export var ATTRIBUTE_FONT : number; + export var ATTRIBUTE_FOREGROUND_COLOR : number; + export var ATTRIBUTE_KERN : number; + export var ATTRIBUTE_LETTERPRESS_STYLE : number; + export var ATTRIBUTE_LIGATURE : number; + export var ATTRIBUTE_LINK : number; + export var ATTRIBUTE_OBLIQUENESS : number; + export var ATTRIBUTE_SHADOW : number; + export var ATTRIBUTE_STRIKETHROUGH_COLOR : number; + export var ATTRIBUTE_STRIKETHROUGH_STYLE : number; + export var ATTRIBUTE_STROKE_COLOR : number; + export var ATTRIBUTE_STROKE_WIDTH : number; + export var ATTRIBUTE_TEXT_EFFECT : number; + export var ATTRIBUTE_UNDERLINES_STYLE : number; + export var ATTRIBUTE_UNDERLINE_BY_WORD : number; + export var ATTRIBUTE_UNDERLINE_COLOR : number; + export var ATTRIBUTE_UNDERLINE_PATTERN_DASH : number; + export var ATTRIBUTE_UNDERLINE_PATTERN_DASH_DOT : number; + export var ATTRIBUTE_UNDERLINE_PATTERN_DASH_DOT_DOT : number; + export var ATTRIBUTE_UNDERLINE_PATTERN_DOT : number; + export var ATTRIBUTE_UNDERLINE_PATTERN_SOLID : number; + export var ATTRIBUTE_UNDERLINE_STYLE_DOUBLE : number; + export var ATTRIBUTE_UNDERLINE_STYLE_NONE : number; + export var ATTRIBUTE_UNDERLINE_STYLE_SINGLE : number; + export var ATTRIBUTE_UNDERLINE_STYLE_THICK : number; + export var ATTRIBUTE_WRITING_DIRECTION : number; + export var ATTRIBUTE_WRITING_DIRECTION_EMBEDDING : number; + export var ATTRIBUTE_WRITING_DIRECTION_LEFT_TO_RIGHT : number; + export var ATTRIBUTE_WRITING_DIRECTION_NATURAL : number; + export var ATTRIBUTE_WRITING_DIRECTION_OVERRIDE : number; + export var ATTRIBUTE_WRITING_DIRECTION_RIGHT_TO_LEFT : number; + export var AUTODETECT_ADDRESS : number; + export var AUTODETECT_ALL : number; + export var AUTODETECT_CALENDAR : number; + export var AUTODETECT_LINK : number; + export var AUTODETECT_NONE : number; + export var AUTODETECT_PHONE : number; + export var BLEND_MODE_CLEAR : number; + export var BLEND_MODE_COLOR : number; + export var BLEND_MODE_COLOR_BURN : number; + export var BLEND_MODE_COLOR_DODGE : number; + export var BLEND_MODE_COPY : number; + export var BLEND_MODE_DARKEN : number; + export var BLEND_MODE_DESTINATION_ATOP : number; + export var BLEND_MODE_DESTINATION_IN : number; + export var BLEND_MODE_DESTINATION_OUT : number; + export var BLEND_MODE_DESTINATION_OVER : number; + export var BLEND_MODE_DIFFERENCE : number; + export var BLEND_MODE_EXCLUSION : number; + export var BLEND_MODE_HARD_LIGHT : number; + export var BLEND_MODE_HUE : number; + export var BLEND_MODE_LIGHTEN : number; + export var BLEND_MODE_LUMINOSITY : number; + export var BLEND_MODE_MULTIPLY : number; + export var BLEND_MODE_NORMAL : number; + export var BLEND_MODE_OVERLAY : number; + export var BLEND_MODE_PLUS_DARKER : number; + export var BLEND_MODE_PLUS_LIGHTER : number; + export var BLEND_MODE_SATURATION : number; + export var BLEND_MODE_SCREEN : number; + export var BLEND_MODE_SOFT_LIGHT : number; + export var BLEND_MODE_SOURCE_ATOP : number; + export var BLEND_MODE_SOURCE_IN : number; + export var BLEND_MODE_SOURCE_OUT : number; + export var BLEND_MODE_XOR : number; + export var CLIP_MODE_DEFAULT : number; + export var CLIP_MODE_DISABLED : number; + export var CLIP_MODE_ENABLED : number; + export var COLLISION_MODE_ALL : number; + export var COLLISION_MODE_BOUNDARY : number; + export var COLLISION_MODE_ITEM : number; + export var COLOR_GROUP_TABLEVIEW_BACKGROUND : string; + export var COLOR_SCROLLVIEW_BACKGROUND : string; + export var COLOR_UNDER_PAGE_BACKGROUND : string; + export var COLOR_VIEW_FLIPSIDE_BACKGROUND : string; + export var PUSH_MODE_CONTINUOUS : number; + export var PUSH_MODE_INSTANTANEOUS : number; + export var SCROLL_DECELERATION_RATE_FAST : number; + export var SCROLL_DECELERATION_RATE_NORMAL : number; + export var WEBVIEW_NAVIGATIONTYPE_BACK_FORWARD : number; + export var WEBVIEW_NAVIGATIONTYPE_FORM_RESUBMITTED : number; + export var WEBVIEW_NAVIGATIONTYPE_FORM_SUBMITTED : number; + export var WEBVIEW_NAVIGATIONTYPE_LINK_CLICKED : number; + export var WEBVIEW_NAVIGATIONTYPE_OTHER : number; + export var WEBVIEW_NAVIGATIONTYPE_RELOAD : number; + export var apiName : string; + export var bubbleParent : boolean; + export function addEventListener (name: string, callback: (...args : any[]) => any) : void; + export function applyProperties (props: Dictionary) : void; + export function create3DMatrix (parameters?: Dictionary) : Ti.UI.iOS._3DMatrix; + export function createAdView (parameters?: Dictionary) : Ti.UI.iOS.AdView; + export function createAnchorAttachmentBehavior (parameters?: Dictionary) : Ti.UI.iOS.AnchorAttachmentBehavior; + export function createAnimator (parameters?: Dictionary) : Ti.UI.iOS.Animator; + export function createAttributedString (parameters?: Dictionary) : Ti.UI.iOS.AttributedString; + export function createCollisionBehavior (parameters?: Dictionary) : Ti.UI.iOS.CollisionBehavior; + export function createCoverFlowView (parameters?: Dictionary) : Ti.UI.iOS.CoverFlowView; + export function createDocumentViewer (parameters?: Dictionary) : Ti.UI.iOS.DocumentViewer; + export function createDynamicItemBehavior (parameters?: Dictionary) : Ti.UI.iOS.DynamicItemBehavior; + export function createGravityBehavior (parameters?: Dictionary) : Ti.UI.iOS.GravityBehavior; + export function createNavigationWindow (parameters?: Dictionary) : Ti.UI.iOS.NavigationWindow; + export function createPushBehavior (parameters?: Dictionary) : Ti.UI.iOS.PushBehavior; + export function createSnapBehavior (parameters?: Dictionary) : Ti.UI.iOS.SnapBehavior; + export function createTabbedBar (parameters?: Dictionary) : Ti.UI.iOS.TabbedBar; + export function createToolbar (parameters?: Dictionary) : Ti.UI.iOS.Toolbar; + export function createTransitionAnimation (transition: transitionAnimationParam) : Ti.Proxy; + export function createViewAttachmentBehavior (parameters?: Dictionary) : Ti.UI.iOS.ViewAttachmentBehavior; + export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; + export function getBubbleParent () : boolean; + export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; + export function setBubbleParent (bubbleParent: boolean) : void; + export interface Animator extends Ti.Proxy { + behaviors : Array; + referenceView : Ti.UI.View; + running : boolean; + addBehavior (behavior: Ti.Proxy) : void; + getBehaviors () : Array; + getReferenceView () : Ti.UI.View; + getRunning () : boolean; + removeAllBehaviors () : void; + removeBehavior (behavior: Ti.Proxy) : void; + setBehaviors (behaviors: Array) : void; + setReferenceView (referenceView: Ti.UI.View) : void; + startAnimator () : void; + stopAnimator () : void; + updateItemUsingCurrentState (item: Ti.UI.View) : void; + } + export interface DynamicItemBehavior extends Ti.Proxy { + allowsRotation : boolean; + angularResistance : number; + density : number; + elasticity : number; + friction : number; + items : Array; + resistance : number; + addAngularVelocityForItem (item: Ti.UI.View, velocity: number) : void; + addItem (item: Ti.UI.View) : void; + addLinearVelocityForItem (item: Ti.UI.View, velocity: Point) : void; + angularVelocityForItem (item: Ti.UI.View) : number; + getAllowsRotation () : boolean; + getAngularResistance () : number; + getDensity () : number; + getElasticity () : number; + getFriction () : number; + getItems () : Array; + getResistance () : number; + linearVelocityForItem (item: Ti.UI.View) : Point; + removeItem (item: Ti.UI.View) : void; + setAllowsRotation (allowsRotation: boolean) : void; + setAngularResistance (angularResistance: number) : void; + setDensity (density: number) : void; + setElasticity (elasticity: number) : void; + setFriction (friction: number) : void; + setResistance (resistance: number) : void; + } + export interface SnapBehavior extends Ti.Proxy { + damping : number; + item : Ti.UI.View; + snapPoint : Point; + getDamping () : number; + getItem () : Ti.UI.View; + getSnapPoint () : Point; + setDamping (damping: number) : void; + setItem (item: Ti.UI.View) : void; + setSnapPoint (snapPoint: Point) : void; + } + export interface GravityBehavior extends Ti.Proxy { + angle : number; + gravityDirection : Point; + items : Array; + magnitude : number; + addItem (item: Ti.UI.View) : void; + getAngle () : number; + getGravityDirection () : Point; + getItems () : Array; + getMagnitude () : number; + removeItem (item: Ti.UI.View) : void; + setAngle (angle: number) : void; + setGravityDirection (gravityDirection: Point) : void; + setMagnitude (magnitude: number) : void; + } + export interface CollisionBehavior extends Ti.Proxy { + boundaryIdentifiers : Array; + collisionMode : number; + items : Array; + referenceInsets : ReferenceInsets; + treatReferenceAsBoundary : boolean; + addBoundary (boundary: BoundaryIdentifier) : void; + addItem (item: Ti.UI.View) : void; + getBoundaryIdentifiers () : Array; + getCollisionMode () : number; + getItems () : Array; + getReferenceInsets () : ReferenceInsets; + getTreatReferenceAsBoundary () : boolean; + removeAllBoundaries () : void; + removeBoundary (boundary: BoundaryIdentifier) : void; + removeItem (item: Ti.UI.View) : void; + setCollisionMode (collisionMode: number) : void; + setReferenceInsets (referenceInsets: ReferenceInsets) : void; + setTreatReferenceAsBoundary (treatReferenceAsBoundary: boolean) : void; + } + export interface Toolbar extends Ti.UI.View { + barColor : string; + borderBottom : boolean; + borderTop : boolean; + extendBackground : boolean; + items : Array; + translucent : boolean; + getBarColor () : string; + getBorderBottom () : boolean; + getBorderTop () : boolean; + getExtendBackground () : boolean; + getItems () : Array; + getTranslucent () : boolean; + setBarColor (barColor: string) : void; + setBorderBottom (borderBottom: boolean) : void; + setBorderTop (borderTop: boolean) : void; + setItems (items: Array) : void; + setTranslucent (translucent: boolean) : void; + } + export interface ViewAttachmentBehavior extends Ti.Proxy { + anchorItem : Ti.UI.View; + anchorOffset : Point; + damping : number; + distance : number; + frequency : number; + item : Ti.UI.View; + itemOffset : Point; + getAnchorItem () : Ti.UI.View; + getAnchorOffset () : Point; + getDamping () : number; + getDistance () : number; + getFrequency () : number; + getItem () : Ti.UI.View; + getItemOffset () : Point; + setAnchorItem (anchorItem: Ti.UI.View) : void; + setAnchorOffset (anchorOffset: Point) : void; + setDamping (damping: number) : void; + setDistance (distance: number) : void; + setFrequency (frequency: number) : void; + setItem (item: Ti.UI.View) : void; + setItemOffset (itemOffset: Point) : void; + } + export interface PushBehavior extends Ti.Proxy { + active : boolean; + angle : number; + items : Array; + magnitude : number; + pushDirection : Point; + pushMode : number; + addItem (item: Ti.UI.View) : void; + getActive () : boolean; + getAngle () : number; + getItems () : Array; + getMagnitude () : number; + getPushDirection () : Point; + getPushMode () : number; + removeItem (item: Ti.UI.View) : void; + setActive (active: boolean) : void; + setAngle (angle: number) : void; + setMagnitude (magnitude: number) : void; + setPushDirection (pushDirection: Point) : void; + setPushMode (pushMode: number) : void; + } + export interface CoverFlowView extends Ti.UI.View { + images : any; + selected : number; + getImages () : any; + getSelected () : number; + setImage (index: number, image: string) : void; + setImage (image: Ti.Blob) : void; + setImage (image: Ti.Filesystem.File) : void; + setImage (index: number, image: CoverFlowImageType) : void; + setImages (images: Array) : void; + setImages (images: Array) : void; + setImages (images: Array) : void; + setImages (images: Array) : void; + setSelected (selected: number) : void; + } + export interface DocumentViewer extends Ti.UI.View { + name : string; + url : string; + getName () : string; + getUrl () : string; + hide (options?: DocumentViewerOptions) : void; + setUrl (url: string) : void; + show (options?: DocumentViewerOptions) : void; + } + export interface NavigationWindow extends Ti.UI.Window { + window : Ti.UI.Window; + closeWindow (window: Ti.UI.Window, options: Dictionary) : void; + getWindow () : Ti.UI.Window; + openWindow (window: Ti.UI.Window, options: Dictionary) : void; + } + export interface AttributedString extends Ti.Proxy { + attributes : Array; + text : string; + addAttribute (attribute: Attribute) : void; + getAttributes () : Array; + getText () : string; + setAttributes (attributes: Array) : void; + setText (text: string) : void; + } + export interface AnchorAttachmentBehavior extends Ti.Proxy { + anchor : Point; + damping : number; + distance : number; + frequency : number; + item : Ti.UI.View; + offset : Point; + getAnchor () : Point; + getDamping () : number; + getDistance () : number; + getFrequency () : number; + getItem () : Ti.UI.View; + getOffset () : Point; + setAnchor (anchor: Point) : void; + setDamping (damping: number) : void; + setDistance (distance: number) : void; + setFrequency (frequency: number) : void; + setItem (item: Ti.UI.View) : void; + setOffset (offset: Point) : void; + } + export interface TabbedBar extends Ti.UI.View { + index : number; + labels : any; + style : number; + getIndex () : number; + getLabels () : any; + getStyle () : number; + setIndex (index: number) : void; + setLabels (labels: Array) : void; + setLabels (labels: Array) : void; + setStyle (style: number) : void; + } + export interface _3DMatrix extends Ti.Proxy { + m11 : number; + m12 : number; + m13 : number; + m14 : number; + m21 : number; + m22 : number; + m23 : number; + m24 : number; + m31 : number; + m32 : number; + m33 : number; + m34 : number; + m41 : number; + m42 : number; + m43 : number; + m44 : number; + getM11 () : number; + getM12 () : number; + getM13 () : number; + getM14 () : number; + getM21 () : number; + getM22 () : number; + getM23 () : number; + getM24 () : number; + getM31 () : number; + getM32 () : number; + getM33 () : number; + getM34 () : number; + getM41 () : number; + getM42 () : number; + getM43 () : number; + getM44 () : number; + invert () : Ti.UI._3DMatrix; + multiply (t2: Ti.UI._3DMatrix) : Ti.UI._3DMatrix; + rotate (angle: number, x: number, y: number, z: number) : Ti.UI._3DMatrix; + scale (sx: number, sy: number, sz: number) : Ti.UI._3DMatrix; + setM11 (m11: number) : void; + setM12 (m12: number) : void; + setM13 (m13: number) : void; + setM14 (m14: number) : void; + setM21 (m21: number) : void; + setM22 (m22: number) : void; + setM23 (m23: number) : void; + setM24 (m24: number) : void; + setM31 (m31: number) : void; + setM32 (m32: number) : void; + setM33 (m33: number) : void; + setM34 (m34: number) : void; + setM41 (m41: number) : void; + setM42 (m42: number) : void; + setM43 (m43: number) : void; + setM44 (m44: number) : void; + translate (tx: number, ty: number, tz: number) : Ti.UI._3DMatrix; + } + export interface AdView extends Ti.UI.View { + adSize : string; + cancelAction () : void; + getAdSize () : string; + setAdSize (adSize: string) : void; + } } export module iPhone { export var MODAL_PRESENTATION_CURRENT_CONTEXT : number; @@ -684,6 +925,7 @@ declare module Ti { export var MODAL_TRANSITION_STYLE_CROSS_DISSOLVE : number; export var MODAL_TRANSITION_STYLE_FLIP_HORIZONTAL : number; export var MODAL_TRANSITION_STYLE_PARTIAL_CURL : number; + export var apiName : string; export var appBadge : number; export var appSupportsShakeToEdit : boolean; export var bubbleParent : boolean; @@ -693,6 +935,7 @@ declare module Ti { export function applyProperties (props: Dictionary) : void; export function createNavigationGroup (parameters?: Dictionary) : Ti.UI.iPhone.NavigationGroup; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getAppBadge () : number; export function getAppSupportsShakeToEdit () : boolean; export function getBubbleParent () : boolean; @@ -703,8 +946,6 @@ declare module Ti { export function setAppBadge (appBadge: number) : void; export function setAppSupportsShakeToEdit (appSupportsShakeToEdit: boolean) : void; export function setBubbleParent (bubbleParent: boolean) : void; - export function setStatusBarHidden (statusBarHidden: boolean) : void; - export function setStatusBarStyle (statusBarStyle: number) : void; export function showStatusBar (params?: showStatusBarParams) : void; export enum ScrollIndicatorStyle { BLACK, @@ -848,6 +1089,7 @@ declare module Ti { } export interface TextArea extends Ti.UI.View { appearance : number; + attributedString : Ti.UI.iOS.AttributedString; autoLink : number; autocapitalization : number; autocorrect : boolean; @@ -857,6 +1099,7 @@ declare module Ti { ellipsize : boolean; enableReturnKey : boolean; font : Font; + handleLinks : boolean; hintText : string; keyboardToolbar : any; keyboardToolbarColor : string; @@ -866,6 +1109,7 @@ declare module Ti { returnKeyType : number; scrollable : boolean; scrollsToTop : boolean; + selection : textAreaSelectedParams; suppressReturn : boolean; textAlign : any; value : string; @@ -873,6 +1117,7 @@ declare module Ti { blur () : void; focus () : void; getAppearance () : number; + getAttributedString () : Ti.UI.iOS.AttributedString; getAutoLink () : number; getAutocapitalization () : number; getAutocorrect () : boolean; @@ -882,6 +1127,7 @@ declare module Ti { getEllipsize () : boolean; getEnableReturnKey () : boolean; getFont () : Font; + getHandleLinks () : boolean; getHintText () : string; getKeyboardToolbar () : any; getKeyboardToolbarColor () : string; @@ -891,12 +1137,14 @@ declare module Ti { getReturnKeyType () : number; getScrollable () : boolean; getScrollsToTop () : boolean; + getSelection () : textAreaSelectedParams; getSuppressReturn () : boolean; getTextAlign () : any; getValue () : string; getVerticalAlign () : any; hasText () : boolean; setAppearance (appearance: number) : void; + setAttributedString (attributedString: Ti.UI.iOS.AttributedString) : void; setAutoLink (autoLink: number) : void; setAutocapitalization (autocapitalization: number) : void; setAutocorrect (autocorrect: boolean) : void; @@ -906,6 +1154,7 @@ declare module Ti { setEllipsize (ellipsize: boolean) : void; setEnableReturnKey (enableReturnKey: boolean) : void; setFont (font: Font) : void; + setHandleLinks (handleLinks: boolean) : void; setHintText (hintText: string) : void; setKeyboardToolbar (keyboardToolbar: Array) : void; setKeyboardToolbar (keyboardToolbar: Ti.UI.iOS.Toolbar) : void; @@ -924,6 +1173,169 @@ declare module Ti { setVerticalAlign (verticalAlign: number) : void; setVerticalAlign (verticalAlign: string) : void; } + export interface View extends Ti.Proxy { + accessibilityHidden : boolean; + accessibilityHint : string; + accessibilityLabel : string; + accessibilityValue : string; + anchorPoint : Point; + animatedCenter : Point; + backgroundColor : string; + backgroundDisabledColor : string; + backgroundDisabledImage : string; + backgroundFocusedColor : string; + backgroundFocusedImage : string; + backgroundGradient : Gradient; + backgroundImage : string; + backgroundLeftCap : number; + backgroundRepeat : boolean; + backgroundSelectedColor : string; + backgroundSelectedImage : string; + backgroundTopCap : number; + borderColor : string; + borderRadius : number; + borderWidth : number; + bottom : any; + center : Point; + children : Array; + clipMode : number; + enabled : boolean; + focusable : boolean; + height : any; + horizontalWrap : boolean; + keepScreenOn : boolean; + layout : string; + left : any; + opacity : number; + overrideCurrentAnimation : boolean; + pullBackgroundColor : string; + rect : Dimension; + right : any; + size : Dimension; + softKeyboardOnFocus : number; + tintColor : any; + top : any; + touchEnabled : boolean; + transform : any; + viewShadowColor : string; + viewShadowOffset : Point; + viewShadowRadius : number; + visible : boolean; + width : any; + zIndex : number; + add (view: Ti.UI.View) : void; + animate (animation: Ti.UI.Animation, callback: (...args : any[]) => any) : void; + animate (animation: Dictionary, callback: (...args : any[]) => any) : void; + convertPointToView (point: Point, destinationView: Ti.UI.View) : Point; + finishLayout () : void; + getAccessibilityHidden () : boolean; + getAccessibilityHint () : string; + getAccessibilityLabel () : string; + getAccessibilityValue () : string; + getAnchorPoint () : Point; + getAnimatedCenter () : Point; + getBackgroundColor () : string; + getBackgroundDisabledColor () : string; + getBackgroundDisabledImage () : string; + getBackgroundFocusedColor () : string; + getBackgroundFocusedImage () : string; + getBackgroundGradient () : Gradient; + getBackgroundImage () : string; + getBackgroundLeftCap () : number; + getBackgroundRepeat () : boolean; + getBackgroundSelectedColor () : string; + getBackgroundSelectedImage () : string; + getBackgroundTopCap () : number; + getBorderColor () : string; + getBorderRadius () : number; + getBorderWidth () : number; + getBottom () : any; + getCenter () : Point; + getChildren () : Array; + getClipMode () : number; + getEnabled () : boolean; + getFocusable () : boolean; + getHeight () : any; + getHorizontalWrap () : boolean; + getKeepScreenOn () : boolean; + getLayout () : string; + getLeft () : any; + getOpacity () : number; + getOverrideCurrentAnimation () : boolean; + getPullBackgroundColor () : string; + getRect () : Dimension; + getRight () : any; + getSize () : Dimension; + getSoftKeyboardOnFocus () : number; + getTintColor () : string; + getTop () : any; + getTouchEnabled () : boolean; + getTransform () : any; + getViewShadowColor () : string; + getViewShadowOffset () : Point; + getViewShadowRadius () : number; + getVisible () : boolean; + getWidth () : any; + getZIndex () : number; + hide () : void; + remove (view: Ti.UI.View) : void; + removeAllChildren () : void; + setAccessibilityHidden (accessibilityHidden: boolean) : void; + setAccessibilityHint (accessibilityHint: string) : void; + setAccessibilityLabel (accessibilityLabel: string) : void; + setAccessibilityValue (accessibilityValue: string) : void; + setAnchorPoint (anchorPoint: Point) : void; + setBackgroundColor (backgroundColor: string) : void; + setBackgroundDisabledColor (backgroundDisabledColor: string) : void; + setBackgroundDisabledImage (backgroundDisabledImage: string) : void; + setBackgroundFocusedColor (backgroundFocusedColor: string) : void; + setBackgroundFocusedImage (backgroundFocusedImage: string) : void; + setBackgroundGradient (backgroundGradient: Gradient) : void; + setBackgroundImage (backgroundImage: string) : void; + setBackgroundLeftCap (backgroundLeftCap: number) : void; + setBackgroundRepeat (backgroundRepeat: boolean) : void; + setBackgroundSelectedColor (backgroundSelectedColor: string) : void; + setBackgroundSelectedImage (backgroundSelectedImage: string) : void; + setBackgroundTopCap (backgroundTopCap: number) : void; + setBorderColor (borderColor: string) : void; + setBorderRadius (borderRadius: number) : void; + setBorderWidth (borderWidth: number) : void; + setBottom (bottom: number) : void; + setBottom (bottom: string) : void; + setCenter (center: Point) : void; + setClipMode (clipMode: number) : void; + setEnabled (enabled: boolean) : void; + setFocusable (focusable: boolean) : void; + setHeight (height: number) : void; + setHeight (height: string) : void; + setHorizontalWrap (horizontalWrap: boolean) : void; + setKeepScreenOn (keepScreenOn: boolean) : void; + setLayout (layout: string) : void; + setLeft (left: number) : void; + setLeft (left: string) : void; + setOpacity (opacity: number) : void; + setPullBackgroundColor (pullBackgroundColor: string) : void; + setRight (right: number) : void; + setRight (right: string) : void; + setSoftKeyboardOnFocus (softKeyboardOnFocus: number) : void; + setTintColor (tintColor: string) : void; + setTop (top: number) : void; + setTop (top: string) : void; + setTouchEnabled (touchEnabled: boolean) : void; + setTransform (transform: Ti.UI._2DMatrix) : void; + setTransform (transform: Ti.UI._3DMatrix) : void; + setViewShadowColor (viewShadowColor: string) : void; + setViewShadowOffset (viewShadowOffset: Point) : void; + setViewShadowRadius (viewShadowRadius: number) : void; + setVisible (visible: boolean) : void; + setWidth (width: number) : void; + setWidth (width: string) : void; + setZIndex (zIndex: number) : void; + show () : void; + startLayout () : void; + toImage (callback?: (...args : any[]) => any, honorScaleFactor?: boolean) : Ti.Blob; + updateLayout (params: Dictionary) : void; + } export enum ActivityIndicatorStyle { BIG, BIG_DARK, @@ -933,8 +1345,11 @@ declare module Ti { export interface Switch extends Ti.UI.View { color : string; font : Font; + onTintColor : string; style : number; textAlign : any; + thumbTintColor : string; + tintColor : string; title : string; titleOff : string; titleOn : string; @@ -942,8 +1357,10 @@ declare module Ti { verticalAlign : any; getColor () : string; getFont () : Font; + getOnTintColor () : string; getStyle () : number; getTextAlign () : any; + getThumbTintColor () : string; getTitle () : string; getTitleOff () : string; getTitleOn () : string; @@ -951,9 +1368,11 @@ declare module Ti { getVerticalAlign () : any; setColor (color: string) : void; setFont (font: Font) : void; + setOnTintColor (onTintColor: string) : void; setStyle (style: number) : void; setTextAlign (textAlign: string) : void; setTextAlign (textAlign: number) : void; + setThumbTintColor (thumbTintColor: string) : void; setTitle (title: string) : void; setTitleOff (titleOff: string) : void; setTitleOn (titleOn: string) : void; @@ -961,6 +1380,22 @@ declare module Ti { setVerticalAlign (verticalAlign: number) : void; setVerticalAlign (verticalAlign: string) : void; } + export interface DashboardItem extends Ti.Proxy { + badge : number; + canDelete : boolean; + image : any; + selectedImage : any; + getBadge () : number; + getCanDelete () : boolean; + getImage () : any; + getSelectedImage () : any; + setBadge (badge: number) : void; + setCanDelete (canDelete: boolean) : void; + setImage (image: string) : void; + setImage (image: Ti.Blob) : void; + setSelectedImage (selectedImage: string) : void; + setSelectedImage (selectedImage: Ti.Blob) : void; + } export interface Tab extends Ti.UI.View { active : boolean; activeIcon : string; @@ -1056,6 +1491,18 @@ declare module Ti { setFontSize (fontSize: number) : void; setTitle (title: string) : void; } + export interface ButtonBar extends Ti.UI.View { + index : number; + labels : any; + style : number; + getIndex () : number; + getLabels () : any; + getStyle () : number; + setIndex (index: number) : void; + setLabels (labels: Array) : void; + setLabels (labels: Array) : void; + setStyle (style: number) : void; + } export interface Slider extends Ti.UI.View { disabledLeftTrackImage : string; disabledRightTrackImage : string; @@ -1169,12 +1616,14 @@ declare module Ti { export var WEBVIEW_PLUGINS_OFF : number; export var WEBVIEW_PLUGINS_ON : number; export var WEBVIEW_PLUGINS_ON_DEMAND : number; + export var apiName : string; export var bubbleParent : boolean; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; export function createProgressIndicator (parameters?: Dictionary) : Ti.UI.Android.ProgressIndicator; export function createSearchView (parameters?: Dictionary) : Ti.UI.Android.SearchView; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBubbleParent () : boolean; export function hideSoftKeyboard () : void; export function openPreferences () : void; @@ -1225,22 +1674,6 @@ declare module Ti { show () : void; } } - export interface DashboardItem extends Ti.Proxy { - badge : number; - canDelete : boolean; - image : any; - selectedImage : any; - getBadge () : number; - getCanDelete () : boolean; - getImage () : any; - getSelectedImage () : any; - setBadge (badge: number) : void; - setCanDelete (canDelete: boolean) : void; - setImage (image: string) : void; - setImage (image: Ti.Blob) : void; - setSelectedImage (selectedImage: string) : void; - setSelectedImage (selectedImage: Ti.Blob) : void; - } export interface DashboardView extends Ti.UI.View { columnCount : number; data : Array; @@ -1308,192 +1741,6 @@ declare module Ti { setTitle (title: string) : void; show () : void; } - export module iOS { - export var AD_SIZE_LANDSCAPE : string; - export var AD_SIZE_PORTRAIT : string; - export var ANIMATION_CURVE_EASE_IN : number; - export var ANIMATION_CURVE_EASE_IN_OUT : number; - export var ANIMATION_CURVE_EASE_OUT : number; - export var ANIMATION_CURVE_LINEAR : number; - export var AUTODETECT_ADDRESS : number; - export var AUTODETECT_ALL : number; - export var AUTODETECT_CALENDAR : number; - export var AUTODETECT_LINK : number; - export var AUTODETECT_NONE : number; - export var AUTODETECT_PHONE : number; - export var BLEND_MODE_CLEAR : number; - export var BLEND_MODE_COLOR : number; - export var BLEND_MODE_COLOR_BURN : number; - export var BLEND_MODE_COLOR_DODGE : number; - export var BLEND_MODE_COPY : number; - export var BLEND_MODE_DARKEN : number; - export var BLEND_MODE_DESTINATION_ATOP : number; - export var BLEND_MODE_DESTINATION_IN : number; - export var BLEND_MODE_DESTINATION_OUT : number; - export var BLEND_MODE_DESTINATION_OVER : number; - export var BLEND_MODE_DIFFERENCE : number; - export var BLEND_MODE_EXCLUSION : number; - export var BLEND_MODE_HARD_LIGHT : number; - export var BLEND_MODE_HUE : number; - export var BLEND_MODE_LIGHTEN : number; - export var BLEND_MODE_LUMINOSITY : number; - export var BLEND_MODE_MULTIPLY : number; - export var BLEND_MODE_NORMAL : number; - export var BLEND_MODE_OVERLAY : number; - export var BLEND_MODE_PLUS_DARKER : number; - export var BLEND_MODE_PLUS_LIGHTER : number; - export var BLEND_MODE_SATURATION : number; - export var BLEND_MODE_SCREEN : number; - export var BLEND_MODE_SOFT_LIGHT : number; - export var BLEND_MODE_SOURCE_ATOP : number; - export var BLEND_MODE_SOURCE_IN : number; - export var BLEND_MODE_SOURCE_OUT : number; - export var BLEND_MODE_XOR : number; - export var COLOR_GROUP_TABLEVIEW_BACKGROUND : string; - export var COLOR_SCROLLVIEW_BACKGROUND : string; - export var COLOR_UNDER_PAGE_BACKGROUND : string; - export var COLOR_VIEW_FLIPSIDE_BACKGROUND : string; - export var WEBVIEW_NAVIGATIONTYPE_BACK_FORWARD : number; - export var WEBVIEW_NAVIGATIONTYPE_FORM_RESUBMITTED : number; - export var WEBVIEW_NAVIGATIONTYPE_FORM_SUBMITTED : number; - export var WEBVIEW_NAVIGATIONTYPE_LINK_CLICKED : number; - export var WEBVIEW_NAVIGATIONTYPE_OTHER : number; - export var WEBVIEW_NAVIGATIONTYPE_RELOAD : number; - export var bubbleParent : boolean; - export function addEventListener (name: string, callback: (...args : any[]) => any) : void; - export function applyProperties (props: Dictionary) : void; - export function create3DMatrix (parameters?: Dictionary) : Ti.UI.iOS._3DMatrix; - export function createAdView (parameters?: Dictionary) : Ti.UI.iOS.AdView; - export function createCoverFlowView (parameters?: Dictionary) : Ti.UI.iOS.CoverFlowView; - export function createDocumentViewer (parameters?: Dictionary) : Ti.UI.iOS.DocumentViewer; - export function createNavigationWindow (parameters?: Dictionary) : Ti.UI.iOS.NavigationWindow; - export function createTabbedBar (parameters?: Dictionary) : Ti.UI.iOS.TabbedBar; - export function createToolbar (parameters?: Dictionary) : Ti.UI.iOS.Toolbar; - export function fireEvent (name: string, event: Dictionary) : void; - export function getBubbleParent () : boolean; - export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; - export function setBubbleParent (bubbleParent: boolean) : void; - export interface Toolbar extends Ti.UI.View { - barColor : string; - borderBottom : boolean; - borderTop : boolean; - items : Array; - translucent : boolean; - getBarColor () : string; - getBorderBottom () : boolean; - getBorderTop () : boolean; - getItems () : Array; - getTranslucent () : boolean; - setBarColor (barColor: string) : void; - setBorderBottom (borderBottom: boolean) : void; - setBorderTop (borderTop: boolean) : void; - setItems (items: Array) : void; - setTranslucent (translucent: boolean) : void; - } - export interface CoverFlowView extends Ti.UI.View { - images : any; - selected : number; - getImages () : any; - getSelected () : number; - setImage (index: number, image: string) : void; - setImage (image: Ti.Blob) : void; - setImage (image: Ti.Filesystem.File) : void; - setImage (index: number, image: CoverFlowImageType) : void; - setImages (images: Array) : void; - setImages (images: Array) : void; - setImages (images: Array) : void; - setImages (images: Array) : void; - setSelected (selected: number) : void; - } - export interface DocumentViewer extends Ti.UI.View { - name : string; - url : string; - getName () : string; - getUrl () : string; - hide (options?: DocumentViewerOptions) : void; - setUrl (url: string) : void; - show (options?: DocumentViewerOptions) : void; - } - export interface NavigationWindow extends Ti.UI.Window { - window : Ti.UI.Window; - closeWindow (window: Ti.UI.Window, options: Dictionary) : void; - getWindow () : Ti.UI.Window; - openWindow (window: Ti.UI.Window, options: Dictionary) : void; - } - export interface TabbedBar extends Ti.UI.View { - index : number; - labels : any; - style : number; - getIndex () : number; - getLabels () : any; - getStyle () : number; - setIndex (index: number) : void; - setLabels (labels: Array) : void; - setLabels (labels: Array) : void; - setStyle (style: number) : void; - } - export interface _3DMatrix extends Ti.Proxy { - m11 : number; - m12 : number; - m13 : number; - m14 : number; - m21 : number; - m22 : number; - m23 : number; - m24 : number; - m31 : number; - m32 : number; - m33 : number; - m34 : number; - m41 : number; - m42 : number; - m43 : number; - m44 : number; - getM11 () : number; - getM12 () : number; - getM13 () : number; - getM14 () : number; - getM21 () : number; - getM22 () : number; - getM23 () : number; - getM24 () : number; - getM31 () : number; - getM32 () : number; - getM33 () : number; - getM34 () : number; - getM41 () : number; - getM42 () : number; - getM43 () : number; - getM44 () : number; - invert () : Ti.UI._3DMatrix; - multiply (t2: Ti.UI._3DMatrix) : Ti.UI._3DMatrix; - rotate (angle: number, x: number, y: number, z: number) : Ti.UI._3DMatrix; - scale (sx: number, sy: number, sz: number) : Ti.UI._3DMatrix; - setM11 (m11: number) : void; - setM12 (m12: number) : void; - setM13 (m13: number) : void; - setM14 (m14: number) : void; - setM21 (m21: number) : void; - setM22 (m22: number) : void; - setM23 (m23: number) : void; - setM24 (m24: number) : void; - setM31 (m31: number) : void; - setM32 (m32: number) : void; - setM33 (m33: number) : void; - setM34 (m34: number) : void; - setM41 (m41: number) : void; - setM42 (m42: number) : void; - setM43 (m43: number) : void; - setM44 (m44: number) : void; - translate (tx: number, ty: number, tz: number) : Ti.UI._3DMatrix; - } - export interface AdView extends Ti.UI.View { - adSize : string; - cancelAction () : void; - getAdSize () : string; - setAdSize (adSize: string) : void; - } - } export interface _2DMatrix extends Ti.Proxy { a : number; b : number; @@ -1540,26 +1787,35 @@ declare module Ti { barImage : string; exitOnClose : boolean; extendEdges : Array; + flagSecure : boolean; fullscreen : boolean; + hideShadow : boolean; includeOpaqueBars : boolean; leftNavButton : Ti.UI.View; + leftNavButtons : Array; modal : boolean; navBarHidden : boolean; navTintColor : any; orientation : number; orientationModes : Array; rightNavButton : Ti.UI.View; + rightNavButtons : Array; + shadowImage : string; statusBarStyle : any; tabBarHidden : boolean; + theme : string; title : string; + titleAttributes : titleAttributesParams; titleControl : Ti.UI.View; titleImage : string; titlePrompt : string; titleid : string; titlepromptid : string; toolbar : Array; + transitionAnimation : Ti.Proxy; translucent : boolean; url : string; + windowFlags : number; windowPixelFormat : number; windowSoftInputMode : number; close (params?: Dictionary) : void; @@ -1572,28 +1828,38 @@ declare module Ti { getBarImage () : string; getExitOnClose () : boolean; getExtendEdges () : Array; + getFlagSecure () : boolean; getFullscreen () : boolean; + getHideShadow () : boolean; getIncludeOpaqueBars () : boolean; getLeftNavButton () : Ti.UI.View; + getLeftNavButtons () : Array; getModal () : boolean; getNavBarHidden () : boolean; getNavTintColor () : string; getOrientation () : number; getOrientationModes () : Array; getRightNavButton () : Ti.UI.View; + getRightNavButtons () : Array; + getShadowImage () : string; getStatusBarStyle () : number; getTabBarHidden () : boolean; + getTheme () : string; getTitle () : string; + getTitleAttributes () : titleAttributesParams; getTitleControl () : Ti.UI.View; getTitleImage () : string; getTitlePrompt () : string; getTitleid () : string; getTitlepromptid () : string; getToolbar () : Array; + getTransitionAnimation () : Ti.Proxy; getTranslucent () : boolean; getUrl () : string; + getWindowFlags () : number; getWindowPixelFormat () : number; getWindowSoftInputMode () : number; + hideNavBar (options?: Dictionary) : void; hideTabBar () : void; open (params?: openWindowParams) : void; setAutoAdjustScrollViewInsets (autoAdjustScrollViewInsets: boolean) : void; @@ -1602,29 +1868,39 @@ declare module Ti { setBackButtonTitleImage (backButtonTitleImage: Ti.Blob) : void; setBarColor (barColor: string) : void; setBarImage (barImage: string) : void; + setExitOnClose (exitOnClose: boolean) : void; setExtendEdges (extendEdges: Array) : void; setFullscreen (fullscreen: boolean) : void; + setHideShadow (hideShadow: boolean) : void; setIncludeOpaqueBars (includeOpaqueBars: boolean) : void; setLeftNavButton (leftNavButton: Ti.UI.View) : void; + setLeftNavButtons (leftNavButtons: Array) : void; setModal (modal: boolean) : void; setNavBarHidden (navBarHidden: boolean) : void; setNavTintColor (navTintColor: string) : void; setOrientationModes (orientationModes: Array) : void; setRightNavButton (rightNavButton: Ti.UI.View) : void; + setRightNavButtons (rightNavButtons: Array) : void; + setShadowImage (shadowImage: string) : void; setStatusBarStyle (statusBarStyle: number) : void; setTabBarHidden (tabBarHidden: boolean) : void; setTitle (title: string) : void; + setTitleAttributes (titleAttributes: titleAttributesParams) : void; setTitleControl (titleControl: Ti.UI.View) : void; setTitleImage (titleImage: string) : void; setTitlePrompt (titlePrompt: string) : void; setTitleid (titleid: string) : void; setTitlepromptid (titlepromptid: string) : void; setToolbar (items: Array, params?: windowToolbarParam) : void; + setTransitionAnimation (transitionAnimation: Ti.Proxy) : void; setTranslucent (translucent: boolean) : void; setWindowPixelFormat (windowPixelFormat: number) : void; + showNavBar (options?: Dictionary) : void; } export interface TextField extends Ti.UI.View { appearance : number; + attributedHintText : Ti.UI.iOS.AttributedString; + attributedString : Ti.UI.iOS.AttributedString; autoLink : number; autocapitalization : number; autocorrect : boolean; @@ -1653,6 +1929,7 @@ declare module Ti { rightButton : any; rightButtonMode : number; rightButtonPadding : number; + selection : textFieldSelectedParams; suppressReturn : boolean; textAlign : any; value : string; @@ -1660,6 +1937,8 @@ declare module Ti { blur () : void; focus () : void; getAppearance () : number; + getAttributedHintText () : Ti.UI.iOS.AttributedString; + getAttributedString () : Ti.UI.iOS.AttributedString; getAutoLink () : number; getAutocapitalization () : number; getAutocorrect () : boolean; @@ -1688,12 +1967,15 @@ declare module Ti { getRightButton () : any; getRightButtonMode () : number; getRightButtonPadding () : number; + getSelection () : textFieldSelectedParams; getSuppressReturn () : boolean; getTextAlign () : any; getValue () : string; getVerticalAlign () : any; hasText () : boolean; setAppearance (appearance: number) : void; + setAttributedHintText (attributedHintText: Ti.UI.iOS.AttributedString) : void; + setAttributedString (attributedString: Ti.UI.iOS.AttributedString) : void; setAutoLink (autoLink: number) : void; setAutocapitalization (autocapitalization: number) : void; setAutocorrect (autocorrect: boolean) : void; @@ -1791,11 +2073,13 @@ declare module Ti { data : any; disableBounce : boolean; enableZoomControls : boolean; + handlePlatformUrl : boolean; hideLoadIndicator : boolean; html : string; ignoreSslError : boolean; lightTouchEnabled : boolean; loading : boolean; + onCreateWindow : (...args : any[]) => any; overScrollMode : number; pluginState : number; scalesPageToFit : boolean; @@ -1811,11 +2095,13 @@ declare module Ti { getData () : any; getDisableBounce () : boolean; getEnableZoomControls () : boolean; + getHandlePlatformUrl () : boolean; getHideLoadIndicator () : boolean; getHtml () : string; getIgnoreSslError () : boolean; getLightTouchEnabled () : boolean; getLoading () : boolean; + getOnCreateWindow () : (...args : any[]) => any; getOverScrollMode () : number; getPluginState () : number; getScalesPageToFit () : boolean; @@ -1837,11 +2123,13 @@ declare module Ti { setData (data: Ti.Filesystem.File) : void; setDisableBounce (disableBounce: boolean) : void; setEnableZoomControls (enableZoomControls: boolean) : void; + setHandlePlatformUrl (handlePlatformUrl: boolean) : void; setHideLoadIndicator (hideLoadIndicator: boolean) : void; setHtml (html: any, options?: Dictionary) : void; setIgnoreSslError (ignoreSslError: boolean) : void; setLightTouchEnabled (lightTouchEnabled: boolean) : void; setLoading (loading: boolean) : void; + setOnCreateWindow (onCreateWindow: (...args : any[]) => any) : void; setOverScrollMode (overScrollMode: number) : void; setPluginState (pluginState: number) : void; setScalesPageToFit (scalesPageToFit: boolean) : void; @@ -1862,6 +2150,58 @@ declare module Ti { setData (type: string, data: any) : void; setText (text: string) : void; } + export interface ScrollableView extends Ti.UI.View { + cacheSize : number; + clipViews : boolean; + currentPage : number; + disableBounce : boolean; + hitRect : Dimension; + overScrollMode : number; + overlayEnabled : boolean; + pagingControlAlpha : number; + pagingControlColor : string; + pagingControlHeight : number; + pagingControlOnTop : boolean; + pagingControlTimeout : number; + scrollingEnabled : boolean; + showPagingControl : boolean; + views : Array; + addView (view: Ti.UI.View) : void; + getCacheSize () : number; + getClipViews () : boolean; + getCurrentPage () : number; + getDisableBounce () : boolean; + getHitRect () : Dimension; + getOverScrollMode () : number; + getOverlayEnabled () : boolean; + getPagingControlAlpha () : number; + getPagingControlColor () : string; + getPagingControlHeight () : number; + getPagingControlOnTop () : boolean; + getPagingControlTimeout () : number; + getScrollingEnabled () : boolean; + getShowPagingControl () : boolean; + getViews () : Array; + moveNext () : void; + movePrevious () : void; + removeView (view: number) : void; + removeView (view: Ti.UI.View) : void; + scrollToView (view: number) : void; + scrollToView (view: Ti.UI.View) : void; + setCacheSize (cacheSize: number) : void; + setCurrentPage (currentPage: number) : void; + setDisableBounce (disableBounce: boolean) : void; + setHitRect (hitRect: Dimension) : void; + setOverScrollMode (overScrollMode: number) : void; + setOverlayEnabled (overlayEnabled: boolean) : void; + setPagingControlAlpha (pagingControlAlpha: number) : void; + setPagingControlColor (pagingControlColor: string) : void; + setPagingControlHeight (pagingControlHeight: number) : void; + setPagingControlOnTop (pagingControlOnTop: boolean) : void; + setScrollingEnabled (scrollingEnabled: boolean) : void; + setShowPagingControl (showPagingControl: boolean) : void; + setViews (views: Array) : void; + } export interface ListSection extends Ti.Proxy { footerTitle : string; footerView : Ti.UI.View; @@ -1890,6 +2230,7 @@ declare module Ti { contentHeight : any; contentOffset : Dictionary; contentWidth : any; + decelerationRate : number; disableBounce : boolean; horizontalBounce : boolean; maxZoomScale : number; @@ -1907,6 +2248,7 @@ declare module Ti { getContentHeight () : any; getContentOffset () : Dictionary; getContentWidth () : any; + getDecelerationRate () : number; getDisableBounce () : boolean; getHorizontalBounce () : boolean; getMaxZoomScale () : number; @@ -1928,6 +2270,7 @@ declare module Ti { setContentOffset (contentOffset: Dictionary, animated?: contentOffsetOption) : void; setContentWidth (contentWidth: number) : void; setContentWidth (contentWidth: string) : void; + setDecelerationRate (decelerationRate: number) : void; setDisableBounce (disableBounce: boolean) : void; setHorizontalBounce (horizontalBounce: boolean) : void; setMaxZoomScale (maxZoomScale: number) : void; @@ -1947,13 +2290,16 @@ declare module Ti { caseInsensitiveSearch : boolean; defaultItemTemplate : any; editing : boolean; + footerDividersEnabled : boolean; footerTitle : string; footerView : Ti.UI.View; + headerDividersEnabled : boolean; headerTitle : string; headerView : Ti.UI.View; keepSectionsInSearch : boolean; pruneSectionsOnEdit : boolean; pullView : Ti.UI.View; + refreshControl : Ti.UI.RefreshControl; scrollIndicatorStyle : number; searchText : string; searchView : any; @@ -1961,6 +2307,7 @@ declare module Ti { sectionIndexTitles : Array; sections : Array; separatorColor : string; + separatorInsets : Dictionary; separatorStyle : number; showVerticalScrollIndicator : boolean; style : number; @@ -1975,20 +2322,24 @@ declare module Ti { getCaseInsensitiveSearch () : boolean; getDefaultItemTemplate () : any; getEditing () : boolean; + getFooterDividersEnabled () : boolean; getFooterTitle () : string; getFooterView () : Ti.UI.View; + getHeaderDividersEnabled () : boolean; getHeaderTitle () : string; getHeaderView () : Ti.UI.View; getKeepSectionsInSearch () : boolean; getPruneSectionsOnEdit () : boolean; getPullView () : Ti.UI.View; + getRefreshControl () : Ti.UI.RefreshControl; getScrollIndicatorStyle () : number; getSearchText () : string; - getSearchView () : Ti.UI.SearchBar; + getSearchView () : any; getSectionCount () : number; getSectionIndexTitles () : Array; getSections () : Array; getSeparatorColor () : string; + getSeparatorInsets () : Dictionary; getSeparatorStyle () : number; getShowVerticalScrollIndicator () : boolean; getStyle () : number; @@ -2014,12 +2365,15 @@ declare module Ti { setMarker (markerProps: ListViewMarkerProps) : void; setPruneSectionsOnEdit (pruneSectionsOnEdit: boolean) : void; setPullView (pullView: Ti.UI.View) : void; + setRefreshControl (refreshControl: Ti.UI.RefreshControl) : void; setScrollIndicatorStyle (scrollIndicatorStyle: number) : void; setSearchText (searchText: string) : void; setSearchView (searchView: Ti.UI.SearchBar) : void; + setSearchView (searchView: Ti.UI.Android.SearchView) : void; setSectionIndexTitles (sectionIndexTitles: Array) : void; setSections (sections: Array) : void; setSeparatorColor (separatorColor: string) : void; + setSeparatorInsets (separatorInsets: Dictionary) : void; setSeparatorStyle (separatorStyle: number) : void; setShowVerticalScrollIndicator (showVerticalScrollIndicator: boolean) : void; setWillScrollOnStatusTap (willScrollOnStatusTap: boolean) : void; @@ -2041,6 +2395,7 @@ declare module Ti { editButtonTitle : string; exitOnClose : boolean; navBarHidden : boolean; + navTintColor : any; shadowImage : string; tabDividerColor : string; tabDividerWidth : any; @@ -2056,6 +2411,9 @@ declare module Ti { tabsBackgroundSelectedColor : string; tabsBackgroundSelectedImage : string; tabsTintColor : any; + title : string; + titleAttributes : titleAttributesParams; + translucent : boolean; windowSoftInputMode : number; addTab (tab: Ti.UI.Tab) : void; close () : void; @@ -2075,6 +2433,7 @@ declare module Ti { getEditButtonTitle () : string; getExitOnClose () : boolean; getNavBarHidden () : boolean; + getNavTintColor () : string; getShadowImage () : string; getTabDividerColor () : string; getTabDividerWidth () : any; @@ -2090,6 +2449,9 @@ declare module Ti { getTabsBackgroundSelectedColor () : string; getTabsBackgroundSelectedImage () : string; getTabsTintColor () : string; + getTitle () : string; + getTitleAttributes () : titleAttributesParams; + getTranslucent () : boolean; getWindowSoftInputMode () : number; open () : void; removeTab (tab: Ti.UI.Tab) : void; @@ -2107,7 +2469,9 @@ declare module Ti { setAllowUserCustomization (allowUserCustomization: boolean) : void; setBarColor (barColor: string) : void; setEditButtonTitle (editButtonTitle: string) : void; + setExitOnClose (exitOnClose: boolean) : void; setNavBarHidden (navBarHidden: boolean) : void; + setNavTintColor (navTintColor: string) : void; setShadowImage (shadowImage: string) : void; setTabDividerColor (tabDividerColor: string) : void; setTabDividerWidth (tabDividerWidth: number) : void; @@ -2125,6 +2489,9 @@ declare module Ti { setTabsBackgroundSelectedColor (tabsBackgroundSelectedColor: string) : void; setTabsBackgroundSelectedImage (tabsBackgroundSelectedImage: string) : void; setTabsTintColor (tabsTintColor: string) : void; + setTitle (title: string) : void; + setTitleAttributes (titleAttributes: titleAttributesParams) : void; + setTranslucent (translucent: boolean) : void; } export interface TableView extends Ti.UI.View { allowsSelection : boolean; @@ -2132,10 +2499,13 @@ declare module Ti { data : any; editable : boolean; editing : boolean; + filterAnchored : boolean; filterAttribute : string; filterCaseInsensitive : boolean; + footerDividersEnabled : boolean; footerTitle : string; footerView : Ti.UI.View; + headerDividersEnabled : boolean; headerPullView : Ti.UI.View; headerTitle : string; headerView : Ti.UI.View; @@ -2146,6 +2516,7 @@ declare module Ti { moveable : boolean; moving : boolean; overScrollMode : number; + refreshControl : Ti.UI.RefreshControl; rowHeight : number; scrollIndicatorStyle : number; scrollable : boolean; @@ -2156,6 +2527,7 @@ declare module Ti { sectionCount : number; sections : Array; separatorColor : string; + separatorInsets : Dictionary; separatorStyle : number; showVerticalScrollIndicator : boolean; style : number; @@ -2176,10 +2548,13 @@ declare module Ti { getData () : any; getEditable () : boolean; getEditing () : boolean; + getFilterAnchored () : boolean; getFilterAttribute () : string; getFilterCaseInsensitive () : boolean; + getFooterDividersEnabled () : boolean; getFooterTitle () : string; getFooterView () : Ti.UI.View; + getHeaderDividersEnabled () : boolean; getHeaderPullView () : Ti.UI.View; getHeaderTitle () : string; getHeaderView () : Ti.UI.View; @@ -2190,6 +2565,7 @@ declare module Ti { getMoveable () : boolean; getMoving () : boolean; getOverScrollMode () : number; + getRefreshControl () : Ti.UI.RefreshControl; getRowHeight () : number; getScrollIndicatorStyle () : number; getScrollable () : boolean; @@ -2200,6 +2576,7 @@ declare module Ti { getSectionCount () : number; getSections () : Array; getSeparatorColor () : string; + getSeparatorInsets () : Dictionary; getSeparatorStyle () : number; getShowVerticalScrollIndicator () : boolean; getStyle () : number; @@ -2222,6 +2599,7 @@ declare module Ti { setData (data: Array, animation: TableViewAnimationProperties) : void; setEditable (editable: boolean) : void; setEditing (editing: boolean) : void; + setFilterAnchored (filterAnchored: boolean) : void; setFilterAttribute (filterAttribute: string) : void; setFilterCaseInsensitive (filterCaseInsensitive: boolean) : void; setFooterTitle (footerTitle: string) : void; @@ -2236,6 +2614,7 @@ declare module Ti { setMoveable (moveable: boolean) : void; setMoving (moving: boolean) : void; setOverScrollMode (overScrollMode: number) : void; + setRefreshControl (refreshControl: Ti.UI.RefreshControl) : void; setRowHeight (rowHeight: number) : void; setScrollIndicatorStyle (scrollIndicatorStyle: number) : void; setScrollable (scrollable: boolean) : void; @@ -2246,6 +2625,7 @@ declare module Ti { setSearchHidden (searchHidden: boolean) : void; setSections (sections: Array) : void; setSeparatorColor (separatorColor: string) : void; + setSeparatorInsets (separatorInsets: Dictionary) : void; setSeparatorStyle (separatorStyle: number) : void; setShowVerticalScrollIndicator (showVerticalScrollIndicator: boolean) : void; setStyle (style: number) : void; @@ -2254,9 +2634,13 @@ declare module Ti { } export interface Button extends Ti.UI.View { color : string; + disabledColor : string; font : Font; image : any; selectedColor : string; + shadowColor : string; + shadowOffset : Dictionary; + shadowRadius : number; style : number; systemButton : number; textAlign : any; @@ -2264,9 +2648,13 @@ declare module Ti { titleid : string; verticalAlign : any; getColor () : string; + getDisabledColor () : string; getFont () : Font; getImage () : any; getSelectedColor () : string; + getShadowColor () : string; + getShadowOffset () : Dictionary; + getShadowRadius () : number; getStyle () : number; getSystemButton () : number; getTextAlign () : any; @@ -2274,10 +2662,14 @@ declare module Ti { getTitleid () : string; getVerticalAlign () : any; setColor (color: string) : void; + setDisabledColor (disabledColor: string) : void; setFont (font: Font) : void; setImage (image: string) : void; setImage (image: Ti.Blob) : void; setSelectedColor (selectedColor: string) : void; + setShadowColor (shadowColor: string) : void; + setShadowOffset (shadowOffset: Dictionary) : void; + setShadowRadius (shadowRadius: number) : void; setStyle (style: number) : void; setSystemButton (systemButton: number) : void; setTextAlign (textAlign: string) : void; @@ -2292,6 +2684,7 @@ declare module Ti { buttonNames : Array; cancel : number; destructive : number; + opaquebackground : boolean; options : Array; persistent : boolean; selectedIndex : number; @@ -2301,6 +2694,7 @@ declare module Ti { getButtonNames () : Array; getCancel () : number; getDestructive () : number; + getOpaquebackground () : boolean; getOptions () : Array; getPersistent () : boolean; getSelectedIndex () : number; @@ -2309,22 +2703,21 @@ declare module Ti { hide (params?: hideParams) : void; setAndroidView (androidView: Ti.UI.View) : void; setCancel (cancel: number) : void; + setOpaquebackground (opaquebackground: boolean) : void; setPersistent (persistent: boolean) : void; setTitle (title: string) : void; setTitleid (titleid: string) : void; show (params?: showParams) : void; } - export interface ButtonBar extends Ti.UI.View { - index : number; - labels : any; - style : number; - getIndex () : number; - getLabels () : any; - getStyle () : number; - setIndex (index: number) : void; - setLabels (labels: Array) : void; - setLabels (labels: Array) : void; - setStyle (style: number) : void; + export interface RefreshControl extends Ti.Proxy { + tintColor : string; + title : Ti.UI.iOS.AttributedString; + beginRefreshing () : void; + endRefreshing () : void; + getTintColor () : string; + getTitle () : Ti.UI.iOS.AttributedString; + setTintColor (tintColor: string) : void; + setTitle (title: Ti.UI.iOS.AttributedString) : void; } export interface EmailDialog extends Ti.Proxy { CANCELLED : number; @@ -2460,10 +2853,12 @@ declare module Ti { setValue (value: number) : void; } export module MobileWeb { + export var apiName : string; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; export function createNavigationGroup (parameters?: Dictionary) : Ti.UI.MobileWeb.NavigationGroup; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; export enum TableViewSeparatorStyle { NONE, @@ -2480,6 +2875,7 @@ declare module Ti { } } export interface Label extends Ti.UI.View { + attributedString : Ti.UI.iOS.AttributedString; autoLink : number; backgroundPaddingBottom : number; backgroundPaddingLeft : number; @@ -2490,14 +2886,17 @@ declare module Ti { font : Font; highlightedColor : string; html : string; + includeFontPadding : boolean; minimumFontSize : number; shadowColor : string; - shadowOffset : any; + shadowOffset : Dictionary; + shadowRadius : number; text : string; textAlign : any; textid : string; verticalAlign : any; wordWrap : boolean; + getAttributedString () : Ti.UI.iOS.AttributedString; getAutoLink () : number; getBackgroundPaddingBottom () : number; getBackgroundPaddingLeft () : number; @@ -2508,14 +2907,17 @@ declare module Ti { getFont () : Font; getHighlightedColor () : string; getHtml () : string; + getIncludeFontPadding () : boolean; getMinimumFontSize () : number; getShadowColor () : string; - getShadowOffset () : any; + getShadowOffset () : Dictionary; + getShadowRadius () : number; getText () : string; getTextAlign () : any; getTextid () : string; getVerticalAlign () : any; getWordWrap () : boolean; + setAttributedString (attributedString: Ti.UI.iOS.AttributedString) : void; setAutoLink (autoLink: number) : void; setBackgroundPaddingBottom (backgroundPaddingBottom: number) : void; setBackgroundPaddingLeft (backgroundPaddingLeft: number) : void; @@ -2526,9 +2928,11 @@ declare module Ti { setFont (font: Font) : void; setHighlightedColor (highlightedColor: string) : void; setHtml (html: string) : void; + setIncludeFontPadding (includeFontPadding: boolean) : void; setMinimumFontSize (minimumFontSize: number) : void; setShadowColor (shadowColor: string) : void; - setShadowOffset (shadowOffset: any) : void; + setShadowOffset (shadowOffset: Dictionary) : void; + setShadowRadius (shadowRadius: number) : void; setText (text: string) : void; setTextAlign (textAlign: string) : void; setTextAlign (textAlign: number) : void; @@ -2608,55 +3012,6 @@ declare module Ti { setHeaderTitle (headerTitle: string) : void; setHeaderView (headerView: Ti.UI.View) : void; } - export interface ActivityIndicator extends Ti.Proxy { - bottom : any; - color : string; - font : Font; - height : string; - indicatorColor : string; - indicatorDiameter : string; - left : any; - message : string; - messageid : string; - right : any; - style : number; - top : any; - width : string; - add () : void; - getBottom () : any; - getColor () : string; - getFont () : Font; - getHeight () : string; - getIndicatorColor () : string; - getIndicatorDiameter () : string; - getLeft () : any; - getMessage () : string; - getMessageid () : string; - getRight () : any; - getStyle () : number; - getTop () : any; - getWidth () : string; - hide () : void; - remove () : void; - setBottom (bottom: number) : void; - setBottom (bottom: string) : void; - setColor (color: string) : void; - setFont (font: Font) : void; - setHeight (height: string) : void; - setIndicatorColor (indicatorColor: string) : void; - setIndicatorDiameter (indicatorDiameter: string) : void; - setLeft (left: number) : void; - setLeft (left: string) : void; - setMessage (message: string) : void; - setMessageid (messageid: string) : void; - setRight (right: number) : void; - setRight (right: string) : void; - setStyle (style: number) : void; - setTop (top: number) : void; - setTop (top: string) : void; - setWidth (width: string) : void; - show () : void; - } export interface Animation extends Ti.Proxy { anchorPoint : Point; autoreverse : boolean; @@ -2764,20 +3119,73 @@ declare module Ti { setYOffset (yOffset: number) : void; } export interface PickerColumn extends Ti.UI.View { + font : Font; rowCount : number; rows : Array; selectedRow : Ti.UI.PickerRow; addRow (row: Ti.UI.PickerRow) : void; + getFont () : Font; getRowCount () : number; getRows () : Array; getSelectedRow () : Ti.UI.PickerRow; removeRow (row: Ti.UI.PickerRow) : void; + setFont (font: Font) : void; setSelectedRow (selectedRow: Ti.UI.PickerRow) : void; } - export interface Picker extends Ti.Proxy { + export interface ActivityIndicator extends Ti.Proxy { + bottom : any; + color : string; + font : Font; + height : string; + indicatorColor : string; + indicatorDiameter : string; + left : any; + message : string; + messageid : string; + right : any; + style : number; + top : any; + width : string; + add () : void; + getBottom () : any; + getColor () : string; + getFont () : Font; + getHeight () : string; + getIndicatorColor () : string; + getIndicatorDiameter () : string; + getLeft () : any; + getMessage () : string; + getMessageid () : string; + getRight () : any; + getStyle () : number; + getTop () : any; + getWidth () : string; + hide () : void; + remove () : void; + setBottom (bottom: number) : void; + setBottom (bottom: string) : void; + setColor (color: string) : void; + setFont (font: Font) : void; + setHeight (height: string) : void; + setIndicatorColor (indicatorColor: string) : void; + setIndicatorDiameter (indicatorDiameter: string) : void; + setLeft (left: number) : void; + setLeft (left: string) : void; + setMessage (message: string) : void; + setMessageid (messageid: string) : void; + setRight (right: number) : void; + setRight (right: string) : void; + setStyle (style: number) : void; + setTop (top: number) : void; + setTop (top: string) : void; + setWidth (width: string) : void; + show () : void; + } + export interface Picker extends Ti.UI.View { calendarViewShown : boolean; columns : Array; countDownDuration : number; + font : Font; format24 : boolean; locale : string; maxDate : Date; @@ -2795,6 +3203,7 @@ declare module Ti { getCalendarViewShown () : boolean; getColumns () : Array; getCountDownDuration () : number; + getFont () : Font; getFormat24 () : boolean; getLocale () : string; getMaxDate () : Date; @@ -2810,6 +3219,7 @@ declare module Ti { setCalendarViewShown (calendarViewShown: boolean) : void; setColumns (columns: Array) : void; setCountDownDuration (countDownDuration: number) : void; + setFont (font: Font) : void; setFormat24 (format24: boolean) : void; setLocale (locale: string) : void; setMaxDate (maxDate: Date) : void; @@ -2828,7 +3238,7 @@ declare module Ti { export enum Module { } - export interface API { + export interface API { debug (message: Array) : void; debug (message: string) : void; error (message: Array) : void; @@ -2857,10 +3267,12 @@ declare module Ti { export var ACTIVITYTYPE_FITNESS : string; export var ACTIVITYTYPE_OTHER : string; export var ACTIVITYTYPE_OTHER_NAVIGATION : string; + export var AUTHORIZATION_ALWAYS : number; export var AUTHORIZATION_AUTHORIZED : number; export var AUTHORIZATION_DENIED : number; export var AUTHORIZATION_RESTRICTED : number; export var AUTHORIZATION_UNKNOWN : number; + export var AUTHORIZATION_WHEN_IN_USE : number; export var ERROR_DENIED : number; export var ERROR_HEADING_FAILURE : number; export var ERROR_LOCATION_UNKNOWN : number; @@ -2874,6 +3286,7 @@ declare module Ti { export var PROVIDER_PASSIVE : string; export var accuracy : number; export var activityType : number; + export var apiName : string; export var bubbleParent : boolean; export var distanceFilter : number; export var frequency : number; @@ -2893,6 +3306,7 @@ declare module Ti { export function forwardGeocoder (address: string, callback: (...args : any[]) => any) : void; export function getAccuracy () : number; export function getActivityType () : number; + export function getApiName () : string; export function getBubbleParent () : boolean; export function getCurrentHeading (callback: (...args : any[]) => any) : void; export function getCurrentPosition (callback: (...args : any[]) => any) : void; @@ -2923,6 +3337,7 @@ declare module Ti { export function setShowCalibration (showCalibration: boolean) : void; export function setTrackSignificantLocationChange (trackSignificantLocationChange: boolean) : void; export module Android { + export var apiName : string; export var bubbleParent : boolean; export var manualMode : boolean; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; @@ -2932,6 +3347,7 @@ declare module Ti { export function createLocationProvider (parameters?: Dictionary) : Ti.Geolocation.Android.LocationProvider; export function createLocationRule (parameters?: Dictionary) : Ti.Geolocation.Android.LocationRule; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBubbleParent () : boolean; export function getManualMode () : boolean; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; @@ -2984,16 +3400,149 @@ declare module Ti { } } export interface Proxy { + apiName : string; bubbleParent : boolean; addEventListener (name: string, callback: (...args : any[]) => any) : void; applyProperties (props: Dictionary) : void; fireEvent (name: string, event: Dictionary) : void; + getApiName () : string; getBubbleParent () : boolean; removeEventListener (name: string, callback: (...args : any[]) => any) : void; setBubbleParent (bubbleParent: boolean) : void; } + export module Map { + export var ANNOTATION_DRAG_STATE_CANCEL : number; + export var ANNOTATION_DRAG_STATE_DRAG : number; + export var ANNOTATION_DRAG_STATE_END : number; + export var ANNOTATION_DRAG_STATE_NONE : number; + export var ANNOTATION_DRAG_STATE_START : number; + export var ANNOTATION_GREEN : number; + export var ANNOTATION_PURPLE : number; + export var ANNOTATION_RED : number; + export var HYBRID_TYPE : number; + export var SATELLITE_TYPE : number; + export var STANDARD_TYPE : number; + export var TERRAIN_TYPE : number; + export var apiName : string; + export var bubbleParent : boolean; + export function addEventListener (name: string, callback: (...args : any[]) => any) : void; + export function applyProperties (props: Dictionary) : void; + export function createAnnotation (parameters?: Dictionary) : Ti.Map.Annotation; + export function createView (parameters?: Dictionary) : Ti.Map.View; + export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; + export function getBubbleParent () : boolean; + export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; + export function setBubbleParent (bubbleParent: boolean) : void; + export interface View extends Ti.UI.View { + animated : boolean; + annotations : Array; + hideAnnotationWhenTouchMap : boolean; + latitudeDelta : number; + longitudeDelta : number; + mapType : number; + region : MapRegionType; + regionFit : boolean; + userLocation : boolean; + addAnnotation (annotation: Dictionary) : void; + addAnnotation (annotation: Ti.Map.Annotation) : void; + addAnnotations (annotations: Array) : void; + addAnnotations (annotations: Array>) : void; + addRoute (route: MapRouteType) : void; + deselectAnnotation (annotation: string) : void; + deselectAnnotation (annotation: Ti.Map.Annotation) : void; + getAnimate () : boolean; + getAnimated () : boolean; + getAnnotations () : Array; + getHideAnnotationWhenTouchMap () : boolean; + getLatitudeDelta () : number; + getLongitudeDelta () : number; + getMapType () : number; + getRegion () : MapRegionType; + getRegionFit () : boolean; + getUserLocation () : boolean; + removeAllAnnotations () : void; + removeAnnotation (annotation: string) : void; + removeAnnotation (annotation: Ti.Map.Annotation) : void; + removeAnnotations (annotations: Array) : void; + removeAnnotations (annotations: Array) : void; + removeRoute (route: MapRouteType) : void; + selectAnnotation (annotation: string) : void; + selectAnnotation (annotation: Ti.Map.Annotation) : void; + setAnimate (animate: boolean) : void; + setAnimated (animated: boolean) : void; + setAnnotations (annotations: Array) : void; + setHideAnnotationWhenTouchMap (hideAnnotationWhenTouchMap: boolean) : void; + setLocation (location: MapLocationType) : void; + setMapType (mapType: number) : void; + setRegion (region: MapRegionType) : void; + setRegionFit (regionFit: boolean) : void; + setUserLocation (userLocation: boolean) : void; + zoom (level: number) : void; + } + export interface Annotation extends Ti.Proxy { + animate : boolean; + canShowCallout : boolean; + centerOffset : Point; + customView : Ti.UI.View; + draggable : boolean; + image : any; + latitude : number; + leftButton : any; + leftView : Ti.UI.View; + longitude : number; + pinImage : string; + pincolor : number; + rightButton : any; + rightView : Ti.UI.View; + subtitle : string; + subtitleid : string; + title : string; + titleid : string; + getAnimate () : boolean; + getCanShowCallout () : boolean; + getCenterOffset () : Point; + getCustomView () : Ti.UI.View; + getDraggable () : boolean; + getImage () : any; + getLatitude () : number; + getLeftButton () : any; + getLeftView () : Ti.UI.View; + getLongitude () : number; + getPinImage () : string; + getPincolor () : number; + getRightButton () : any; + getRightView () : Ti.UI.View; + getSubtitle () : string; + getSubtitleid () : string; + getTitle () : string; + getTitleid () : string; + setAnimate (animate: boolean) : void; + setCanShowCallout (canShowCallout: boolean) : void; + setCenterOffset (centerOffset: Point) : void; + setCustomView (customView: Ti.UI.View) : void; + setDraggable (draggable: boolean) : void; + setImage (image: string) : void; + setImage (image: Ti.Blob) : void; + setLatitude (latitude: number) : void; + setLeftButton (leftButton: number) : void; + setLeftButton (leftButton: string) : void; + setLeftView (leftView: Ti.UI.View) : void; + setLongitude (longitude: number) : void; + setPinImage (pinImage: string) : void; + setPincolor (pincolor: number) : void; + setRightButton (rightButton: number) : void; + setRightButton (rightButton: string) : void; + setRightView (rightView: Ti.UI.View) : void; + setSubtitle (subtitle: string) : void; + setSubtitleid (subtitleid: string) : void; + setTitle (title: string) : void; + setTitleid (titleid: string) : void; + } + } export module Cloud { export var accessToken : string; + export var apiName : string; export var bubbleParent : boolean; export var debug : boolean; export var expiresIn : number; @@ -3003,6 +3552,7 @@ declare module Ti { export var useSecure : boolean; export function applyProperties (props: Dictionary) : void; export function getAccessToken () : string; + export function getApiName () : string; export function getBubbleParent () : boolean; export function getDebug () : boolean; export function getExpiresIn () : number; @@ -3012,6 +3562,7 @@ declare module Ti { export function getUseSecure () : boolean; export function hasStoredSession () : boolean; export function retrieveStoredSession () : string; + export function sendRequest (parameters: Dictionary, callback: (...args : any[]) => any) : void; export function setAccessToken (accessToken: string) : void; export function setBubbleParent (bubbleParent: boolean) : void; export function setDebug (debug: boolean) : void; @@ -3026,13 +3577,6 @@ declare module Ti { show (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; update (parameters: Dictionary, callback: (...args : any[]) => any) : void; } - export interface Files { - create (parameters: Dictionary, callback: (...args : any[]) => any) : void; - query (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; - remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; - show (parameters: Dictionary, callback: (...args : any[]) => any) : void; - update (parameters: Dictionary, callback: (...args : any[]) => any) : void; - } export interface SocialIntegrations { externalAccountLink (parameters: Dictionary, callback: (...args : any[]) => any) : void; externalAccountLogin (parameters: Dictionary, callback: (...args : any[]) => any) : void; @@ -3042,10 +3586,16 @@ declare module Ti { export interface PushNotifications { notify (parameters: Dictionary, callback: (...args : any[]) => any) : void; notifyTokens (parameters: Dictionary, callback: (...args : any[]) => any) : void; + query (parameters: Dictionary, callback: (...args : any[]) => any) : void; + queryChannels (parameters: Dictionary, callback: (...args : any[]) => any) : void; + resetBadge (parameters: Dictionary, callback: (...args : any[]) => any) : void; + setBadge (parameters: Dictionary, callback: (...args : any[]) => any) : void; + showChannels (parameters: Dictionary, callback: (...args : any[]) => any) : void; subscribe (parameters: Dictionary, callback: (...args : any[]) => any) : void; subscribeToken (parameters: Dictionary, callback: (...args : any[]) => any) : void; unsubscribe (parameters: Dictionary, callback: (...args : any[]) => any) : void; unsubscribeToken (parameters: Dictionary, callback: (...args : any[]) => any) : void; + updateSubscription (parameters: Dictionary, callback: (...args : any[]) => any) : void; } export interface Clients { geolocate (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; @@ -3066,6 +3616,7 @@ declare module Ti { query (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; requestResetPassword (parameters: Dictionary, callback: (...args : any[]) => any) : void; + resendConfirmation (parameters: Dictionary, callback: (...args : any[]) => any) : void; search (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; secureCreate (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; secureLogin (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; @@ -3107,6 +3658,8 @@ declare module Ti { create (parameters: Dictionary, callback: (...args : any[]) => any) : void; getChatGroups (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; query (parameters: Dictionary, callback: (...args : any[]) => any) : void; + queryChatGroups (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; + remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; } export interface KeyValues { append (parameters: Dictionary, callback: (...args : any[]) => any) : void; @@ -3115,6 +3668,12 @@ declare module Ti { remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; set (parameters: Dictionary, callback: (...args : any[]) => any) : void; } + export interface GeoFences { + create (parameters: Dictionary, callback: (...args : any[]) => any) : void; + query (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; + remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; + update (parameters: Dictionary, callback: (...args : any[]) => any) : void; + } export interface Checkins { create (parameters: Dictionary, callback: (...args : any[]) => any) : void; query (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; @@ -3128,6 +3687,22 @@ declare module Ti { requests (parameters: Dictionary, callback: (...args : any[]) => any) : void; search (parameters: Dictionary, callback: (...args : any[]) => any) : void; } + export interface Files { + create (parameters: Dictionary, callback: (...args : any[]) => any) : void; + query (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; + remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; + show (parameters: Dictionary, callback: (...args : any[]) => any) : void; + update (parameters: Dictionary, callback: (...args : any[]) => any) : void; + } + export interface PushSchedules { + create (parameters: Dictionary, callback: (...args : any[]) => any) : void; + query (parameters: Dictionary, callback: (...args : any[]) => any) : void; + remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; + } + export interface Likes { + create (parameters: Dictionary, callback: (...args : any[]) => any) : void; + remove (parameters: Dictionary, callback: (...args : any[]) => any) : void; + } export interface Photos { create (parameters: Dictionary, callback: (...args : any[]) => any) : void; query (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; @@ -3138,8 +3713,11 @@ declare module Ti { } export interface Statuses { create (parameters: Dictionary, callback: (...args : any[]) => any) : void; + delete (parameters: Dictionary, callback: (...args : any[]) => any) : void; query (parameters?: Dictionary, callback?: (...args : any[]) => any) : void; search (parameters: Dictionary, callback: (...args : any[]) => any) : void; + show (parameters: Dictionary, callback: (...args : any[]) => any) : void; + update (parameters: Dictionary, callback: (...args : any[]) => any) : void; } export interface PhotoCollections { create (parameters: Dictionary, callback: (...args : any[]) => any) : void; @@ -3234,11 +3812,13 @@ declare module Ti { export var EVENT_ACCESSIBILITY_CHANGED : string; export var accessibilityEnabled : boolean; export var analytics : boolean; + export var apiName : string; export var bubbleParent : boolean; export var copyright : string; export var deployType : string; export var description : string; export var disableNetworkActivityIndicator : boolean; + export var forceSplashAsSnapshot : boolean; export var guid : string; export var id : string; export var idleTimerDisabled : boolean; @@ -3257,12 +3837,14 @@ declare module Ti { export function fireSystemEvent (eventName: string, param?: any) : void; export function getAccessibilityEnabled () : boolean; export function getAnalytics () : boolean; + export function getApiName () : string; export function getArguments () : launchOptions; export function getBubbleParent () : boolean; export function getCopyright () : string; export function getDeployType () : string; export function getDescription () : string; export function getDisableNetworkActivityIndicator () : boolean; + export function getForceSplashAsSnapshot () : boolean; export function getGuid () : string; export function getId () : string; export function getIdleTimerDisabled () : boolean; @@ -3278,29 +3860,87 @@ declare module Ti { export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; export function setBubbleParent (bubbleParent: boolean) : void; export function setDisableNetworkActivityIndicator (disableNetworkActivityIndicator: boolean) : void; + export function setForceSplashAsSnapshot (forceSplashAsSnapshot: boolean) : void; export function setIdleTimerDisabled (idleTimerDisabled: boolean) : void; export function setProximityDetection (proximityDetection: boolean) : void; - export enum Android { - R + export module Android { + export var R : Ti.App.Android.R; + export var apiName : string; + export var appVersionCode : number; + export var appVersionName : string; + export var bubbleParent : boolean; + export var launchIntent : Ti.Android.Intent; + export function addEventListener (name: string, callback: (...args : any[]) => any) : void; + export function applyProperties (props: Dictionary) : void; + export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; + export function getAppVersionCode () : number; + export function getAppVersionName () : string; + export function getBubbleParent () : boolean; + export function getLaunchIntent () : Ti.Android.Intent; + export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; + export function setBubbleParent (bubbleParent: boolean) : void; + export interface R { + + } } export module iOS { + export var BACKGROUNDFETCHINTERVAL_MIN : number; + export var BACKGROUNDFETCHINTERVAL_NEVER : number; export var EVENT_ACCESSIBILITY_LAYOUT_CHANGED : string; export var EVENT_ACCESSIBILITY_SCREEN_CHANGED : string; + export var USER_NOTIFICATION_ACTIVATION_MODE_BACKGROUND : number; + export var USER_NOTIFICATION_ACTIVATION_MODE_FOREGROUND : number; + export var USER_NOTIFICATION_TYPE_ALERT : number; + export var USER_NOTIFICATION_TYPE_BADGE : number; + export var USER_NOTIFICATION_TYPE_NONE : number; + export var USER_NOTIFICATION_TYPE_SOUND : number; + export var apiName : string; + export var applicationOpenSettingsURL : string; export var bubbleParent : boolean; + export var currentUserNotificationSettings : UserNotificationSettings; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; export function cancelAllLocalNotifications () : void; export function cancelLocalNotification (id: number) : void; - export function createLocalNotification (parameters?: Dictionary) : Ti.App.iOS.LocalNotification; + export function cancelLocalNotification (id: string) : void; + export function createUserNotificationAction (parameters?: Dictionary) : Ti.App.iOS.UserNotificationAction; + export function createUserNotificationCategory (parameters?: Dictionary) : Ti.App.iOS.UserNotificationCategory; + export function endBackgroundHandler (handlerID: string) : void; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; + export function getApplicationOpenSettingsURL () : string; export function getBubbleParent () : boolean; + export function getCurrentUserNotificationSettings () : UserNotificationSettings; export function registerBackgroundService (params: Dictionary) : Ti.App.iOS.BackgroundService; + export function registerUserNotificationSettings (params: UserNotificationSettings) : void; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; - export function scheduleLocalNotification (params: Dictionary) : Ti.App.iOS.LocalNotification; + export function scheduleLocalNotification (params: NotificationParams) : Ti.App.iOS.LocalNotification; export function setBubbleParent (bubbleParent: boolean) : void; + export function setMinimumBackgroundFetchInterval (fetchInterval: number) : void; + export interface UserNotificationAction extends Ti.Proxy { + activationMode : number; + authenticationRequired : boolean; + destructive : boolean; + identifier : string; + title : string; + getActivationMode () : number; + getAuthenticationRequired () : boolean; + getDestructive () : boolean; + getIdentifier () : string; + getTitle () : string; + } export interface LocalNotification extends Ti.Proxy { cancel () : void; } + export interface UserNotificationCategory extends Ti.Proxy { + actionsForDefaultContext : Array; + actionsForMinimalContext : Array; + identifier : string; + getActionsForDefaultContext () : Array; + getActionsForMinimalContext () : Array; + getIdentifier () : string; + } export interface BackgroundService extends Ti.Proxy { url : string; getUrl () : string; @@ -3534,6 +4174,7 @@ declare module Ti { export var STREAM_SYSTEM : number; export var STREAM_VOICE_CALL : number; export var URI_INTENT_SCHEME : number; + export var apiName : string; export var bubbleParent : boolean; export var currentActivity : Ti.Android.Activity; export var currentService : Ti.Android.Service; @@ -3549,6 +4190,7 @@ declare module Ti { export function createService (intent: Ti.Android.Intent) : Ti.Android.Service; export function createServiceIntent (options: ServiceIntentOptions) : Ti.Android.Intent; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBubbleParent () : boolean; export function getCurrentActivity () : Ti.Android.Activity; export function getCurrentService () : Ti.Android.Service; @@ -3587,29 +4229,6 @@ declare module Ti { putExtraUri (name: string, value: string) : void; setFlags (flags: number) : void; } - export interface Activity extends Ti.Proxy { - actionBar : Ti.Android.ActionBar; - intent : Ti.Android.Intent; - onCreateOptionsMenu : (...args : any[]) => any; - onPrepareOptionsMenu : (...args : any[]) => any; - requestedOrientation : number; - finish () : void; - getActionBar () : Ti.Android.ActionBar; - getIntent () : Ti.Android.Intent; - getOnCreateOptionsMenu () : (...args : any[]) => any; - getOnPrepareOptionsMenu () : (...args : any[]) => any; - getString (resourceId: number, format: any) : string; - invalidateOptionsMenu () : void; - openOptionsMenu () : void; - sendBroadcast (intent: Ti.Android.Intent) : void; - sendBroadcastWithPermission (intent: Ti.Android.Intent, receiverPermission?: string) : void; - setOnCreateOptionsMenu (onCreateOptionsMenu: (...args : any[]) => any) : void; - setOnPrepareOptionsMenu (onPrepareOptionsMenu: (...args : any[]) => any) : void; - setRequestedOrientation (orientation: number) : void; - setResult (resultCode: number, intent?: Ti.Android.Intent) : void; - startActivity (intent: Ti.Android.Intent) : void; - startActivityForResult (intent: Ti.Android.Intent, callback: (...args : any[]) => any) : void; - } export interface Notification extends Ti.Proxy { audioStreamType : number; contentIntent : Ti.Android.PendingIntent; @@ -3679,6 +4298,7 @@ declare module Ti { export var VISIBILITY_PUBLIC : number; export var allAlerts : Array; export var allCalendars : Array; + export var apiName : string; export var bubbleParent : boolean; export var selectableCalendars : Array; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; @@ -3686,6 +4306,7 @@ declare module Ti { export function fireEvent (name: string, event: Dictionary) : void; export function getAllAlerts () : Array; export function getAllCalendars () : Array; + export function getApiName () : string; export function getBubbleParent () : boolean; export function getCalendarById (id: number) : Ti.Android.Calendar.Calendar; export function getSelectableCalendars () : Array; @@ -3837,20 +4458,27 @@ declare module Ti { export interface ActionBar extends Ti.Proxy { backgroundImage : string; displayHomeAsUp : boolean; + homeButtonEnabled : boolean; icon : string; logo : string; navigationMode : number; onHomeIconItemSelected : (...args : any[]) => any; + subtitle : string; title : string; getNavigationMode () : number; + getSubtitle () : string; getTitle () : string; hide () : void; setBackgroundImage (backgroundImage: string) : void; setDisplayHomeAsUp (displayHomeAsUp: boolean) : void; + setDisplayShowHomeEnabled (show: boolean) : void; + setDisplayShowTitleEnabled (show: boolean) : void; + setHomeButtonEnabled (homeButtonEnabled: boolean) : void; setIcon (icon: string) : void; setLogo (logo: string) : void; setNavigationMode (navigationMode: number) : void; setOnHomeIconItemSelected (onHomeIconItemSelected: (...args : any[]) => any) : void; + setSubtitle (subtitle: string) : void; setTitle (title: string) : void; show () : void; } @@ -3878,6 +4506,50 @@ declare module Ti { setGroupVisible (groupId: number, visible: boolean) : void; size () : number; } + export interface Activity extends Ti.Proxy { + actionBar : Ti.Android.ActionBar; + intent : Ti.Android.Intent; + onCreate : (...args : any[]) => any; + onCreateOptionsMenu : (...args : any[]) => any; + onDestroy : (...args : any[]) => any; + onPause : (...args : any[]) => any; + onPrepareOptionsMenu : (...args : any[]) => any; + onRestart : (...args : any[]) => any; + onResume : (...args : any[]) => any; + onStart : (...args : any[]) => any; + onStop : (...args : any[]) => any; + requestedOrientation : number; + finish () : void; + getActionBar () : Ti.Android.ActionBar; + getIntent () : Ti.Android.Intent; + getOnCreate () : (...args : any[]) => any; + getOnCreateOptionsMenu () : (...args : any[]) => any; + getOnDestroy () : (...args : any[]) => any; + getOnPause () : (...args : any[]) => any; + getOnPrepareOptionsMenu () : (...args : any[]) => any; + getOnRestart () : (...args : any[]) => any; + getOnResume () : (...args : any[]) => any; + getOnStart () : (...args : any[]) => any; + getOnStop () : (...args : any[]) => any; + getString (resourceId: number, format: any) : string; + invalidateOptionsMenu () : void; + openOptionsMenu () : void; + sendBroadcast (intent: Ti.Android.Intent) : void; + sendBroadcastWithPermission (intent: Ti.Android.Intent, receiverPermission?: string) : void; + setOnCreate (onCreate: (...args : any[]) => any) : void; + setOnCreateOptionsMenu (onCreateOptionsMenu: (...args : any[]) => any) : void; + setOnDestroy (onDestroy: (...args : any[]) => any) : void; + setOnPause (onPause: (...args : any[]) => any) : void; + setOnPrepareOptionsMenu (onPrepareOptionsMenu: (...args : any[]) => any) : void; + setOnRestart (onRestart: (...args : any[]) => any) : void; + setOnResume (onResume: (...args : any[]) => any) : void; + setOnStart (onStart: (...args : any[]) => any) : void; + setOnStop (onStop: (...args : any[]) => any) : void; + setRequestedOrientation (orientation: number) : void; + setResult (resultCode: number, intent?: Ti.Android.Intent) : void; + startActivity (intent: Ti.Android.Intent) : void; + startActivityForResult (intent: Ti.Android.Intent, callback: (...args : any[]) => any) : void; + } export interface Service extends Ti.Proxy { intent : Ti.Android.Intent; serviceInstanceId : number; @@ -3919,10 +4591,12 @@ declare module Ti { export var FIELD_TYPE_FLOAT : number; export var FIELD_TYPE_INT : number; export var FIELD_TYPE_STRING : number; + export var apiName : string; export var bubbleParent : boolean; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getBubbleParent () : boolean; export function install (path: string, dbName: string) : Ti.Database.DB; export function open (dbName: string) : Ti.Database.DB; @@ -3972,6 +4646,7 @@ declare module Ti { export var CONTACTS_KIND_PERSON : number; export var CONTACTS_SORT_FIRST_NAME : number; export var CONTACTS_SORT_LAST_NAME : number; + export var apiName : string; export var bubbleParent : boolean; export var contactsAuthorization : number; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; @@ -3981,6 +4656,7 @@ declare module Ti { export function fireEvent (name: string, event: Dictionary) : void; export function getAllGroups () : Array; export function getAllPeople (limit: number) : Array; + export function getApiName () : string; export function getBubbleParent () : boolean; export function getContactsAuthorization () : number; export function getGroupByID (id: number) : Ti.Contacts.Group; @@ -3995,10 +4671,12 @@ declare module Ti { export function setBubbleParent (bubbleParent: boolean) : void; export function showContacts (params: showContactsParams) : void; export module Tizen { + export var apiName : string; export function addEventListener (name: string, callback: (...args : any[]) => any) : void; export function applyProperties (props: Dictionary) : void; export function fireEvent (name: string, event: Dictionary) : void; export function getAllPeople (callback: (...args : any[]) => any) : void; + export function getApiName () : string; export function getPeopleWithName (name: string, callback: (...args : any[]) => any) : void; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; export interface Group { @@ -4100,6 +4778,11 @@ declare module Ti { } } export interface CloudPush { + SERVICE_DISABLED : number; + SERVICE_INVALID : number; + SERVICE_MISSING : number; + SERVICE_VERSION_UPDATE_REQUIRED : number; + SUCCESS : number; enabled : boolean; focusAppOnPush : boolean; showAppOnTrayClick : boolean; @@ -4113,6 +4796,7 @@ declare module Ti { getShowTrayNotification () : boolean; getShowTrayNotificationsWhenFocused () : boolean; getSingleCallback () : boolean; + isGooglePlayServicesAvailable () : number; retrieveDeviceToken (config: CloudPushNotificationConfig) : void; setEnabled (enabled: boolean) : void; setFocusAppOnPush (focusAppOnPush: boolean) : void; @@ -4145,14 +4829,38 @@ declare module Ti { export var AUDIO_MICROPHONE : number; export var AUDIO_MUTED : number; export var AUDIO_RECEIVER_AND_MIC : number; + export var AUDIO_SESSION_CATEGORY_AMBIENT : string; + export var AUDIO_SESSION_CATEGORY_PLAYBACK : string; + export var AUDIO_SESSION_CATEGORY_PLAY_AND_RECORD : string; + export var AUDIO_SESSION_CATEGORY_RECORD : string; + export var AUDIO_SESSION_CATEGORY_SOLO_AMBIENT : string; export var AUDIO_SESSION_MODE_AMBIENT : number; export var AUDIO_SESSION_MODE_PLAYBACK : number; export var AUDIO_SESSION_MODE_PLAY_AND_RECORD : number; export var AUDIO_SESSION_MODE_RECORD : number; export var AUDIO_SESSION_MODE_SOLO_AMBIENT : number; + export var AUDIO_SESSION_OVERRIDE_ROUTE_NONE : number; + export var AUDIO_SESSION_OVERRIDE_ROUTE_SPEAKER : number; + export var AUDIO_SESSION_PORT_AIRPLAY : string; + export var AUDIO_SESSION_PORT_BLUETOOTHA2DP : string; + export var AUDIO_SESSION_PORT_BLUETOOTHHFP : string; + export var AUDIO_SESSION_PORT_BLUETOOTHLE : string; + export var AUDIO_SESSION_PORT_BUILTINMIC : string; + export var AUDIO_SESSION_PORT_BUILTINRECEIVER : string; + export var AUDIO_SESSION_PORT_BUILTINSPEAKER : string; + export var AUDIO_SESSION_PORT_CARAUDIO : string; + export var AUDIO_SESSION_PORT_HDMI : string; + export var AUDIO_SESSION_PORT_HEADPHONES : string; + export var AUDIO_SESSION_PORT_HEADSETMIC : string; + export var AUDIO_SESSION_PORT_LINEIN : string; + export var AUDIO_SESSION_PORT_LINEOUT : string; + export var AUDIO_SESSION_PORT_USBAUDIO : string; export var AUDIO_SPEAKER : number; export var AUDIO_UNAVAILABLE : number; export var AUDIO_UNKNOWN : number; + export var CAMERA_FLASH_AUTO : number; + export var CAMERA_FLASH_OFF : number; + export var CAMERA_FLASH_ON : number; export var CAMERA_FRONT : number; export var CAMERA_REAR : number; export var DEVICE_BUSY : number; @@ -4224,9 +4932,11 @@ declare module Ti { export var VIDEO_SOURCE_TYPE_UNKNOWN : number; export var VIDEO_TIME_OPTION_EXACT : number; export var VIDEO_TIME_OPTION_NEAREST_KEYFRAME : number; + export var apiName : string; export var appMusicPlayer : Ti.Media.MusicPlayer; export var audioLineType : number; export var audioPlaying : boolean; + export var audioSessionCategory : number; export var audioSessionMode : number; export var availableCameraMediaTypes : Array; export var availableCameras : Array; @@ -4234,7 +4944,9 @@ declare module Ti { export var availablePhotoMediaTypes : Array; export var averageMicrophonePower : number; export var bubbleParent : boolean; + export var cameraFlashMode : number; export var canRecord : boolean; + export var currentRoute : RouteDescription; export var isCameraSupported : boolean; export var peakMicrophonePower : number; export var systemMusicPlayer : Ti.Media.MusicPlayer; @@ -4249,9 +4961,11 @@ declare module Ti { export function createSound (parameters?: Dictionary) : Ti.Media.Sound; export function createVideoPlayer (parameters?: Dictionary) : Ti.Media.VideoPlayer; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getAppMusicPlayer () : Ti.Media.MusicPlayer; export function getAudioLineType () : number; export function getAudioPlaying () : boolean; + export function getAudioSessionCategory () : number; export function getAudioSessionMode () : number; export function getAvailableCameraMediaTypes () : Array; export function getAvailableCameras () : Array; @@ -4259,7 +4973,9 @@ declare module Ti { export function getAvailablePhotoMediaTypes () : Array; export function getAverageMicrophonePower () : number; export function getBubbleParent () : boolean; + export function getCameraFlashMode () : number; export function getCanRecord () : boolean; + export function getCurrentRoute () : RouteDescription; export function getIsCameraSupported () : boolean; export function getPeakMicrophonePower () : number; export function getSystemMusicPlayer () : Ti.Media.MusicPlayer; @@ -4275,12 +4991,15 @@ declare module Ti { export function requestAuthorization (callback: (...args : any[]) => any) : void; export function saveToPhotoGallery (media: Ti.Blob, callbacks: any) : void; export function saveToPhotoGallery (media: Ti.Filesystem.File, callbacks: any) : void; + export function setAudioSessionCategory (audioSessionCategory: number) : void; export function setAudioSessionMode (audioSessionMode: number) : void; export function setAvailableCameraMediaTypes (availableCameraMediaTypes: Array) : void; export function setAvailablePhotoGalleryMediaTypes (availablePhotoGalleryMediaTypes: Array) : void; export function setAvailablePhotoMediaTypes (availablePhotoMediaTypes: Array) : void; export function setAverageMicrophonePower (averageMicrophonePower: number) : void; export function setBubbleParent (bubbleParent: boolean) : void; + export function setCameraFlashMode (cameraFlashMode: number) : void; + export function setOverrideAudioRoute (route: number) : void; export function showCamera (options: CameraOptionsType) : void; export function startMicrophoneMonitor () : void; export function stopMicrophoneMonitor () : void; @@ -4289,6 +5008,15 @@ declare module Ti { export function takeScreenshot (callback: (...args : any[]) => any) : void; export function vibrate (pattern?: Array) : void; export interface Sound extends Ti.Proxy { + STATE_BUFFERING : number; + STATE_INITIALIZED : number; + STATE_PAUSED : number; + STATE_PLAYING : number; + STATE_STARTING : number; + STATE_STOPPED : number; + STATE_STOPPING : number; + STATE_WAITING_FOR_DATA : number; + STATE_WAITING_FOR_QUEUE : number; allowBackground : boolean; duration : number; looping : boolean; @@ -4315,64 +5043,6 @@ declare module Ti { setVolume (volume: number) : void; stop () : void; } - export interface AudioRecorder extends Ti.Proxy { - compression : number; - format : number; - paused : boolean; - recording : boolean; - stopped : boolean; - getCompression () : number; - getFormat () : number; - getPaused () : boolean; - getRecording () : boolean; - getStopped () : boolean; - pause () : void; - resume () : void; - setCompression (compression: number) : void; - setFormat (format: number) : void; - start () : void; - stop () : Ti.Filesystem.File; - } - export interface Item extends Ti.Proxy { - albumArtist : string; - albumTitle : string; - albumTrackCount : number; - albumTrackNumber : number; - artist : string; - artwork : Ti.Blob; - composer : string; - discCount : number; - discNumber : number; - genre : string; - isCompilation : boolean; - lyrics : string; - mediaType : number; - playCount : number; - playbackDuration : number; - podcastTitle : string; - rating : number; - skipCount : number; - title : string; - getAlbumArtist () : string; - getAlbumTitle () : string; - getAlbumTrackCount () : number; - getAlbumTrackNumber () : number; - getArtist () : string; - getArtwork () : Ti.Blob; - getComposer () : string; - getDiscCount () : number; - getDiscNumber () : number; - getGenre () : string; - getIsCompilation () : boolean; - getLyrics () : string; - getMediaType () : number; - getPlayCount () : number; - getPlaybackDuration () : number; - getPodcastTitle () : string; - getRating () : number; - getSkipCount () : number; - getTitle () : string; - } export interface VideoPlayer extends Ti.UI.View { allowsAirPlay : boolean; autoplay : boolean; @@ -4450,6 +5120,64 @@ declare module Ti { stop () : void; thumbnailImageAtTime (time: number, option: number) : Ti.Blob; } + export interface AudioRecorder extends Ti.Proxy { + compression : number; + format : number; + paused : boolean; + recording : boolean; + stopped : boolean; + getCompression () : number; + getFormat () : number; + getPaused () : boolean; + getRecording () : boolean; + getStopped () : boolean; + pause () : void; + resume () : void; + setCompression (compression: number) : void; + setFormat (format: number) : void; + start () : void; + stop () : Ti.Filesystem.File; + } + export interface Item extends Ti.Proxy { + albumArtist : string; + albumTitle : string; + albumTrackCount : number; + albumTrackNumber : number; + artist : string; + artwork : Ti.Blob; + composer : string; + discCount : number; + discNumber : number; + genre : string; + isCompilation : boolean; + lyrics : string; + mediaType : number; + playCount : number; + playbackDuration : number; + podcastTitle : string; + rating : number; + skipCount : number; + title : string; + getAlbumArtist () : string; + getAlbumTitle () : string; + getAlbumTrackCount () : number; + getAlbumTrackNumber () : number; + getArtist () : string; + getArtwork () : Ti.Blob; + getComposer () : string; + getDiscCount () : number; + getDiscNumber () : number; + getGenre () : string; + getIsCompilation () : boolean; + getLyrics () : string; + getMediaType () : number; + getPlayCount () : number; + getPlaybackDuration () : number; + getPodcastTitle () : string; + getRating () : number; + getSkipCount () : number; + getTitle () : string; + } export interface MusicPlayer extends Ti.Proxy { currentPlaybackTime : number; nowPlaying : Ti.Media.Item; @@ -4494,11 +5222,13 @@ declare module Ti { autoplay : boolean; bitRate : number; bufferSize : number; + duration : number; idle : boolean; paused : boolean; playing : boolean; progress : number; state : number; + time : number; url : string; volume : number; waiting : boolean; @@ -4506,11 +5236,13 @@ declare module Ti { getAutoplay () : boolean; getBitRate () : number; getBufferSize () : number; + getDuration () : number; getIdle () : boolean; getPaused () : boolean; getPlaying () : boolean; getProgress () : number; getState () : number; + getTime () : number; getUrl () : string; getVolume () : number; getWaiting () : boolean; @@ -4522,6 +5254,7 @@ declare module Ti { setBitRate (bitRate: number) : void; setBufferSize (bufferSize: number) : void; setPaused (paused: boolean) : void; + setTime (time: number) : void; setUrl (url: string) : void; setVolume (volume: number) : void; start () : void; @@ -4533,274 +5266,13 @@ declare module Ti { setSystemWallpaper (image: Ti.Blob, scale: boolean) : void; } } - export module Network { - export var INADDR_ANY : string; - export var NETWORK_LAN : number; - export var NETWORK_MOBILE : number; - export var NETWORK_NONE : number; - export var NETWORK_UNKNOWN : number; - export var NETWORK_WIFI : number; - export var NOTIFICATION_TYPE_ALERT : number; - export var NOTIFICATION_TYPE_BADGE : number; - export var NOTIFICATION_TYPE_NEWSSTAND : number; - export var NOTIFICATION_TYPE_SOUND : number; - export var READ_MODE : number; - export var READ_WRITE_MODE : number; - export var SOCKET_CLOSED : number; - export var SOCKET_CONNECTED : number; - export var SOCKET_ERROR : number; - export var SOCKET_INITIALIZED : number; - export var SOCKET_LISTENING : number; - export var TLS_VERSION_1_0 : number; - export var TLS_VERSION_1_1 : number; - export var TLS_VERSION_1_2 : number; - export var WRITE_MODE : number; - export var bubbleParent : boolean; - export var httpURLFormatter : (...args : any[]) => any; - export var networkType : number; - export var networkTypeName : string; - export var online : boolean; - export var remoteDeviceUUID : string; - export var remoteNotificationTypes : Array; - export var remoteNotificationsEnabled : boolean; - export function addConnectivityListener (callback: (...args : any[]) => any) : void; - export function addEventListener (name: string, callback: (...args : any[]) => any) : void; - export function applyProperties (props: Dictionary) : void; - export function createBonjourBrowser (serviceType: string, domain: string, parameters?: Dictionary) : Ti.Network.BonjourBrowser; - export function createBonjourService (name: string, type: string, domain: string, parameters?: Dictionary) : Ti.Network.BonjourService; - export function createHTTPClient (parameters?: Dictionary) : Ti.Network.HTTPClient; - export function createTCPSocket (hostName: string, port: number, mode: number, parameters: Dictionary) : Ti.Network.TCPSocket; - export function decodeURIComponent (value: string) : string; - export function encodeURIComponent (value: string) : string; - export function fireEvent (name: string, event: Dictionary) : void; - export function getBubbleParent () : boolean; - export function getHttpURLFormatter () : (...args : any[]) => any; - export function getNetworkType () : number; - export function getNetworkTypeName () : string; - export function getOnline () : boolean; - export function getRemoteDeviceUUID () : string; - export function getRemoteNotificationTypes () : Array; - export function getRemoteNotificationsEnabled () : boolean; - export function registerForPushNotifications (config: PushNotificationConfig) : void; - export function removeConnectivityListener (callback: (...args : any[]) => any) : void; - export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; - export function setBubbleParent (bubbleParent: boolean) : void; - export function setHttpURLFormatter (httpURLFormatter: (...args : any[]) => any) : void; - export function unregisterForPushNotifications () : void; - export module Socket { - export var CLOSED : number; - export var CONNECTED : number; - export var ERROR : number; - export var INITIALIZED : number; - export var LISTENING : number; - export var bubbleParent : boolean; - export function addEventListener (name: string, callback: (...args : any[]) => any) : void; - export function applyProperties (props: Dictionary) : void; - export function createTCP (params?: Dictionary) : Ti.Network.Socket.TCP; - export function createUDP (params?: Dictionary) : Ti.Network.Socket.UDP; - export function fireEvent (name: string, event: Dictionary) : void; - export function getBubbleParent () : boolean; - export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; - export function setBubbleParent (bubbleParent: boolean) : void; - export interface UDP extends Ti.IOStream { - data : (...args : any[]) => any; - error : (...args : any[]) => any; - port : number; - started : (...args : any[]) => any; - getData () : (...args : any[]) => any; - getError () : (...args : any[]) => any; - getPort () : number; - getStarted () : (...args : any[]) => any; - sendBytes (port: number, host: string, data: Array) : void; - sendString (port: number, host: string, data: string) : void; - setData (data: (...args : any[]) => any) : void; - setError (error: (...args : any[]) => any) : void; - setPort (port: number) : void; - setStarted (started: (...args : any[]) => any) : void; - start (port: number) : void; - stop () : void; - } - export interface TCP extends Ti.IOStream { - accepted : (...args : any[]) => any; - connected : (...args : any[]) => any; - error : (...args : any[]) => any; - host : string; - listenQueueSize : number; - port : number; - state : number; - timeout : number; - accept (options: AcceptDict) : void; - connect () : void; - getAccepted () : (...args : any[]) => any; - getConnected () : (...args : any[]) => any; - getError () : (...args : any[]) => any; - getHost () : string; - getListenQueueSize () : number; - getPort () : number; - getState () : number; - getTimeout () : number; - listen () : void; - setAccepted (accepted: (...args : any[]) => any) : void; - setConnected (connected: (...args : any[]) => any) : void; - setError (error: (...args : any[]) => any) : void; - setHost (host: string) : void; - setListenQueueSize (listenQueueSize: number) : void; - setPort (port: number) : void; - setTimeout (timeout: number) : void; - } - } - export interface TCPSocket extends Ti.Proxy { - hostName : string; - isValid : boolean; - mode : number; - port : number; - stripTerminator : boolean; - close () : void; - connect () : void; - getHostName () : string; - getIsValid () : boolean; - getMode () : number; - getPort () : number; - getStripTerminator () : boolean; - listen () : void; - setHostName (hostName: string) : void; - setIsValid (isValid: boolean) : void; - setMode (mode: number) : void; - setPort (port: number) : void; - setStripTerminator (stripTerminator: boolean) : void; - write (data: any, sendTo: number) : void; - write (data: string, sendTo: number) : void; - } - export interface BonjourService extends Ti.Proxy { - domain : string; - isLocal : boolean; - name : string; - socket : any; - type : string; - getDomain () : string; - getIsLocal () : boolean; - getName () : string; - getSocket () : any; - getType () : string; - publish (socket: any) : void; - resolve (timeout: number) : void; - setDomain (domain: string) : void; - setIsLocal (isLocal: boolean) : void; - setName (name: string) : void; - setSocket (socket: any) : void; - setType (type: string) : void; - stop () : void; - } - export interface HTTPClient extends Ti.Proxy { - DONE : number; - HEADERS_RECEIVED : number; - LOADING : number; - OPENED : number; - UNSENT : number; - allResponseHeaders : string; - autoEncodeUrl : boolean; - autoRedirect : boolean; - cache : boolean; - connected : boolean; - connectionType : string; - domain : string; - enableKeepAlive : boolean; - file : string; - location : string; - ondatastream : (...args : any[]) => any; - onerror : (...args : any[]) => any; - onload : (...args : any[]) => any; - onreadystatechange : (...args : any[]) => any; - onsendstream : (...args : any[]) => any; - password : string; - readyState : number; - responseData : Ti.Blob; - responseText : string; - responseXML : Ti.XML.Document; - status : number; - statusText : string; - timeout : number; - tlsVersion : number; - username : string; - validatesSecureCertificate : boolean; - withCredentials : boolean; - abort () : void; - addAuthFactory (scheme: string, factory: any) : void; - addKeyManager (X509KeyManager: any) : void; - addTrustManager (X509TrustManager: any) : void; - clearCookies (host: string) : void; - getAllResponseHeaders () : string; - getAutoEncodeUrl () : boolean; - getAutoRedirect () : boolean; - getCache () : boolean; - getConnected () : boolean; - getConnectionType () : string; - getDomain () : string; - getEnableKeepAlive () : boolean; - getFile () : string; - getLocation () : string; - getOndatastream () : (...args : any[]) => any; - getOnerror () : (...args : any[]) => any; - getOnload () : (...args : any[]) => any; - getOnreadystatechange () : (...args : any[]) => any; - getOnsendstream () : (...args : any[]) => any; - getPassword () : string; - getReadyState () : number; - getResponseData () : Ti.Blob; - getResponseHeader (name: string) : string; - getResponseText () : string; - getResponseXML () : Ti.XML.Document; - getStatus () : number; - getStatusText () : string; - getTimeout () : number; - getTlsVersion () : number; - getUsername () : string; - getValidatesSecureCertificate () : boolean; - getWithCredentials () : boolean; - open (method: string, url: string, async?: boolean) : void; - send (data?: any) : void; - send (data?: string) : void; - send (data?: Ti.Filesystem.File) : void; - send (data?: Ti.Blob) : void; - setAutoEncodeUrl (autoEncodeUrl: boolean) : void; - setAutoRedirect (autoRedirect: boolean) : void; - setCache (cache: boolean) : void; - setDomain (domain: string) : void; - setEnableKeepAlive (enableKeepAlive: boolean) : void; - setFile (file: string) : void; - setOndatastream (ondatastream: (...args : any[]) => any) : void; - setOnerror (onerror: (...args : any[]) => any) : void; - setOnload (onload: (...args : any[]) => any) : void; - setOnreadystatechange (onreadystatechange: (...args : any[]) => any) : void; - setOnsendstream (onsendstream: (...args : any[]) => any) : void; - setPassword (password: string) : void; - setRequestHeader (name: string, value: string) : void; - setTimeout (timeout: number) : void; - setTlsVersion (tlsVersion: number) : void; - setUsername (username: string) : void; - setValidatesSecureCertificate (validatesSecureCertificate: boolean) : void; - setWithCredentials (withCredentials: boolean) : void; - } - export interface BonjourBrowser extends Ti.Proxy { - domain : string; - isSearching : boolean; - serviceType : string; - getDomain () : string; - getIsSearching () : boolean; - getServiceType () : string; - search () : void; - setDomain (domain: string) : void; - setIsSearching (isSearching: boolean) : void; - setServiceType (serviceType: string) : void; - stopSearch () : void; - } - } export module Platform { export var BATTERY_STATE_CHARGING : number; export var BATTERY_STATE_FULL : number; export var BATTERY_STATE_UNKNOWN : number; export var BATTERY_STATE_UNPLUGGED : number; export var address : string; + export var apiName : string; export var architecture : string; export var availableMemory : number; export var batteryLevel : number; @@ -4827,6 +5299,7 @@ declare module Ti { export function createUUID () : string; export function fireEvent (name: string, event: Dictionary) : void; export function getAddress () : string; + export function getApiName () : string; export function getArchitecture () : string; export function getAvailableMemory () : number; export function getBatteryLevel () : number; @@ -4867,13 +5340,6 @@ declare module Ti { getPlatformWidth () : number; getXdpi () : number; getYdpi () : number; - setDensity (density: string) : void; - setDpi (dpi: number) : void; - setLogicalDensityFactor (logicalDensityFactor: number) : void; - setPlatformHeight (platformHeight: number) : void; - setPlatformWidth (platformWidth: number) : void; - setXdpi (xdpi: number) : void; - setYdpi (ydpi: number) : void; } export interface Android { API_LEVEL : number; @@ -4943,6 +5409,7 @@ declare module Ti { export var allAlerts : Array; export var allCalendars : Array; export var allEditableCalendars : Array; + export var apiName : string; export var bubbleParent : boolean; export var defaultCalendar : Ti.Calendar.Calendar; export var eventsAuthorization : number; @@ -4953,8 +5420,9 @@ declare module Ti { export function getAllAlerts () : Array; export function getAllCalendars () : Array; export function getAllEditableCalendars () : Array; + export function getApiName () : string; export function getBubbleParent () : boolean; - export function getCalendarById (id: number) : Ti.Calendar.Calendar; + export function getCalendarById (id: string) : Ti.Calendar.Calendar; export function getDefaultCalendar () : Ti.Calendar.Calendar; export function getEventsAuthorization () : number; export function getSelectableCalendars () : Array; @@ -5087,138 +5555,11 @@ declare module Ti { setRelativeOffset (relativeOffset: number) : void; } } - export module Map { - export var ANNOTATION_DRAG_STATE_CANCEL : number; - export var ANNOTATION_DRAG_STATE_DRAG : number; - export var ANNOTATION_DRAG_STATE_END : number; - export var ANNOTATION_DRAG_STATE_NONE : number; - export var ANNOTATION_DRAG_STATE_START : number; - export var ANNOTATION_GREEN : number; - export var ANNOTATION_PURPLE : number; - export var ANNOTATION_RED : number; - export var HYBRID_TYPE : number; - export var SATELLITE_TYPE : number; - export var STANDARD_TYPE : number; - export var TERRAIN_TYPE : number; - export var bubbleParent : boolean; - export function addEventListener (name: string, callback: (...args : any[]) => any) : void; - export function applyProperties (props: Dictionary) : void; - export function createAnnotation (parameters?: Dictionary) : Ti.Map.Annotation; - export function createView (parameters?: Dictionary) : Ti.Map.View; - export function fireEvent (name: string, event: Dictionary) : void; - export function getBubbleParent () : boolean; - export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; - export function setBubbleParent (bubbleParent: boolean) : void; - export interface View extends Ti.UI.View { - animated : boolean; - annotations : Array; - hideAnnotationWhenTouchMap : boolean; - latitudeDelta : number; - longitudeDelta : number; - mapType : number; - region : MapRegionType; - regionFit : boolean; - userLocation : boolean; - addAnnotation (annotation: Dictionary) : void; - addAnnotation (annotation: Ti.Map.Annotation) : void; - addAnnotations (annotations: Array) : void; - addAnnotations (annotations: Array>) : void; - addRoute (route: MapRouteType) : void; - deselectAnnotation (annotation: string) : void; - deselectAnnotation (annotation: Ti.Map.Annotation) : void; - getAnimate () : boolean; - getAnimated () : boolean; - getAnnotations () : Array; - getHideAnnotationWhenTouchMap () : boolean; - getLatitudeDelta () : number; - getLongitudeDelta () : number; - getMapType () : number; - getRegion () : MapRegionType; - getRegionFit () : boolean; - getUserLocation () : boolean; - removeAllAnnotations () : void; - removeAnnotation (annotation: string) : void; - removeAnnotation (annotation: Ti.Map.Annotation) : void; - removeAnnotations (annotations: Array) : void; - removeAnnotations (annotations: Array) : void; - removeRoute (route: MapRouteType) : void; - selectAnnotation (annotation: string) : void; - selectAnnotation (annotation: Ti.Map.Annotation) : void; - setAnimate (animate: boolean) : void; - setAnimated (animated: boolean) : void; - setAnnotations (annotations: Array) : void; - setHideAnnotationWhenTouchMap (hideAnnotationWhenTouchMap: boolean) : void; - setLocation (location: MapLocationType) : void; - setMapType (mapType: number) : void; - setRegion (region: MapRegionType) : void; - setRegionFit (regionFit: boolean) : void; - setUserLocation (userLocation: boolean) : void; - zoom (level: number) : void; - } - export interface Annotation extends Ti.Proxy { - animate : boolean; - canShowCallout : boolean; - centerOffset : Point; - customView : Ti.UI.View; - draggable : boolean; - image : any; - latitude : number; - leftButton : any; - leftView : Ti.UI.View; - longitude : number; - pinImage : string; - pincolor : number; - rightButton : any; - rightView : Ti.UI.View; - subtitle : string; - subtitleid : string; - title : string; - titleid : string; - getAnimate () : boolean; - getCanShowCallout () : boolean; - getCenterOffset () : Point; - getCustomView () : Ti.UI.View; - getDraggable () : boolean; - getImage () : any; - getLatitude () : number; - getLeftButton () : any; - getLeftView () : Ti.UI.View; - getLongitude () : number; - getPinImage () : string; - getPincolor () : number; - getRightButton () : any; - getRightView () : Ti.UI.View; - getSubtitle () : string; - getSubtitleid () : string; - getTitle () : string; - getTitleid () : string; - setAnimate (animate: boolean) : void; - setCanShowCallout (canShowCallout: boolean) : void; - setCenterOffset (centerOffset: Point) : void; - setCustomView (customView: Ti.UI.View) : void; - setDraggable (draggable: boolean) : void; - setImage (image: string) : void; - setImage (image: Ti.Blob) : void; - setLatitude (latitude: number) : void; - setLeftButton (leftButton: number) : void; - setLeftButton (leftButton: string) : void; - setLeftView (leftView: Ti.UI.View) : void; - setLongitude (longitude: number) : void; - setPinImage (pinImage: string) : void; - setPincolor (pincolor: number) : void; - setRightButton (rightButton: number) : void; - setRightButton (rightButton: string) : void; - setRightView (rightView: Ti.UI.View) : void; - setSubtitle (subtitle: string) : void; - setSubtitleid (subtitleid: string) : void; - setTitle (title: string) : void; - setTitleid (titleid: string) : void; - } - } export module Filesystem { export var MODE_APPEND : number; export var MODE_READ : number; export var MODE_WRITE : number; + export var apiName : string; export var applicationCacheDirectory : string; export var applicationDataDirectory : string; export var applicationDirectory : string; @@ -5235,20 +5576,21 @@ declare module Ti { export function createTempDirectory () : Ti.Filesystem.File; export function createTempFile () : Ti.Filesystem.File; export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; export function getApplicationCacheDirectory () : string; export function getApplicationDataDirectory () : string; export function getApplicationDirectory () : string; export function getApplicationSupportDirectory () : string; export function getBubbleParent () : boolean; export function getExternalStorageDirectory () : string; - export function getFile (path: string) : Ti.Filesystem.File; + export function getFile (path: string, ...extraPaths: string[]) : Ti.Filesystem.File; export function getLineEnding () : string; export function getResRawDirectory () : string; export function getResourcesDirectory () : string; export function getSeparator () : string; export function getTempDirectory () : string; export function isExternalStoragePresent () : boolean; - export function openStream (mode: number, path: string) : Ti.Filesystem.FileStream; + export function openStream (mode: number, path: string, ...extraPaths: string[]) : Ti.Filesystem.FileStream; export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; export function setBubbleParent (bubbleParent: boolean) : void; export interface File extends Ti.Proxy { @@ -5305,6 +5647,320 @@ declare module Ti { } } + export module Network { + export var INADDR_ANY : string; + export var NETWORK_LAN : number; + export var NETWORK_MOBILE : number; + export var NETWORK_NONE : number; + export var NETWORK_UNKNOWN : number; + export var NETWORK_WIFI : number; + export var NOTIFICATION_TYPE_ALERT : number; + export var NOTIFICATION_TYPE_BADGE : number; + export var NOTIFICATION_TYPE_NEWSSTAND : number; + export var NOTIFICATION_TYPE_SOUND : number; + export var PROGRESS_UNKNOWN : number; + export var READ_MODE : number; + export var READ_WRITE_MODE : number; + export var SOCKET_CLOSED : number; + export var SOCKET_CONNECTED : number; + export var SOCKET_ERROR : number; + export var SOCKET_INITIALIZED : number; + export var SOCKET_LISTENING : number; + export var TLS_VERSION_1_0 : number; + export var TLS_VERSION_1_1 : number; + export var TLS_VERSION_1_2 : number; + export var WRITE_MODE : number; + export var allHTTPCookies : Array; + export var apiName : string; + export var bubbleParent : boolean; + export var httpURLFormatter : (...args : any[]) => any; + export var networkType : number; + export var networkTypeName : string; + export var online : boolean; + export var remoteDeviceUUID : string; + export var remoteNotificationTypes : Array; + export var remoteNotificationsEnabled : boolean; + export function addConnectivityListener (callback: (...args : any[]) => any) : void; + export function addEventListener (name: string, callback: (...args : any[]) => any) : void; + export function addHTTPCookie (cookie: Ti.Network.Cookie) : void; + export function addSystemCookie (cookie: Ti.Network.Cookie) : void; + export function applyProperties (props: Dictionary) : void; + export function createBonjourBrowser (serviceType: string, domain: string, parameters?: Dictionary) : Ti.Network.BonjourBrowser; + export function createBonjourService (name: string, type: string, domain: string, parameters?: Dictionary) : Ti.Network.BonjourService; + export function createCookie (parameters?: Dictionary) : Ti.Network.Cookie; + export function createHTTPClient (parameters?: Dictionary) : Ti.Network.HTTPClient; + export function createTCPSocket (hostName: string, port: number, mode: number, parameters: Dictionary) : Ti.Network.TCPSocket; + export function decodeURIComponent (value: string) : string; + export function encodeURIComponent (value: string) : string; + export function fireEvent (name: string, event: Dictionary) : void; + export function getAllHTTPCookies () : Array; + export function getApiName () : string; + export function getBubbleParent () : boolean; + export function getHTTPCookies (domain: string, path: string, name: string) : Array; + export function getHTTPCookiesForDomain (domain: string) : Array; + export function getHttpURLFormatter () : (...args : any[]) => any; + export function getNetworkType () : number; + export function getNetworkTypeName () : string; + export function getOnline () : boolean; + export function getRemoteDeviceUUID () : string; + export function getRemoteNotificationTypes () : Array; + export function getRemoteNotificationsEnabled () : boolean; + export function getSystemCookies (domain: string, path: string, name: string) : Array; + export function registerForPushNotifications (config: PushNotificationConfig) : void; + export function removeAllHTTPCookies () : void; + export function removeAllSystemCookies () : void; + export function removeConnectivityListener (callback: (...args : any[]) => any) : void; + export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; + export function removeHTTPCookie (domain: string, path: string, name: string) : void; + export function removeHTTPCookiesForDomain (domain: string) : void; + export function removeSystemCookie (domain: string, path: string, name: string) : void; + export function setBubbleParent (bubbleParent: boolean) : void; + export function setHttpURLFormatter (httpURLFormatter: (...args : any[]) => any) : void; + export function unregisterForPushNotifications () : void; + export interface TCPSocket extends Ti.Proxy { + hostName : string; + isValid : boolean; + mode : number; + port : number; + stripTerminator : boolean; + close () : void; + connect () : void; + getHostName () : string; + getIsValid () : boolean; + getMode () : number; + getPort () : number; + getStripTerminator () : boolean; + listen () : void; + setHostName (hostName: string) : void; + setIsValid (isValid: boolean) : void; + setMode (mode: number) : void; + setPort (port: number) : void; + setStripTerminator (stripTerminator: boolean) : void; + write (data: any, sendTo: number) : void; + write (data: string, sendTo: number) : void; + } + export module Socket { + export var CLOSED : number; + export var CONNECTED : number; + export var ERROR : number; + export var INITIALIZED : number; + export var LISTENING : number; + export var apiName : string; + export var bubbleParent : boolean; + export function addEventListener (name: string, callback: (...args : any[]) => any) : void; + export function applyProperties (props: Dictionary) : void; + export function createTCP (params?: Dictionary) : Ti.Network.Socket.TCP; + export function createUDP (params?: Dictionary) : Ti.Network.Socket.UDP; + export function fireEvent (name: string, event: Dictionary) : void; + export function getApiName () : string; + export function getBubbleParent () : boolean; + export function removeEventListener (name: string, callback: (...args : any[]) => any) : void; + export function setBubbleParent (bubbleParent: boolean) : void; + export interface UDP extends Ti.IOStream { + data : (...args : any[]) => any; + error : (...args : any[]) => any; + port : number; + started : (...args : any[]) => any; + getData () : (...args : any[]) => any; + getError () : (...args : any[]) => any; + getPort () : number; + getStarted () : (...args : any[]) => any; + sendBytes (port: number, host: string, data: Array) : void; + sendString (port: number, host: string, data: string) : void; + setData (data: (...args : any[]) => any) : void; + setError (error: (...args : any[]) => any) : void; + setPort (port: number) : void; + setStarted (started: (...args : any[]) => any) : void; + start (port: number) : void; + stop () : void; + } + export interface TCP extends Ti.IOStream { + accepted : (...args : any[]) => any; + connected : (...args : any[]) => any; + error : (...args : any[]) => any; + host : string; + listenQueueSize : number; + port : number; + state : number; + timeout : number; + accept (options: AcceptDict) : void; + connect () : void; + getAccepted () : (...args : any[]) => any; + getConnected () : (...args : any[]) => any; + getError () : (...args : any[]) => any; + getHost () : string; + getListenQueueSize () : number; + getPort () : number; + getState () : number; + getTimeout () : number; + listen () : void; + setAccepted (accepted: (...args : any[]) => any) : void; + setConnected (connected: (...args : any[]) => any) : void; + setError (error: (...args : any[]) => any) : void; + setHost (host: string) : void; + setListenQueueSize (listenQueueSize: number) : void; + setPort (port: number) : void; + setTimeout (timeout: number) : void; + } + } + export interface BonjourService extends Ti.Proxy { + domain : string; + isLocal : boolean; + name : string; + socket : any; + type : string; + getDomain () : string; + getIsLocal () : boolean; + getName () : string; + getSocket () : any; + getType () : string; + publish (socket: any) : void; + resolve (timeout: number) : void; + setDomain (domain: string) : void; + setIsLocal (isLocal: boolean) : void; + setName (name: string) : void; + setSocket (socket: any) : void; + setType (type: string) : void; + stop () : void; + } + export interface HTTPClient extends Ti.Proxy { + DONE : number; + HEADERS_RECEIVED : number; + LOADING : number; + OPENED : number; + UNSENT : number; + allResponseHeaders : string; + autoEncodeUrl : boolean; + autoRedirect : boolean; + cache : boolean; + connected : boolean; + connectionType : string; + domain : string; + enableKeepAlive : boolean; + file : string; + location : string; + ondatastream : (...args : any[]) => any; + onerror : (...args : any[]) => any; + onload : (...args : any[]) => any; + onreadystatechange : (...args : any[]) => any; + onsendstream : (...args : any[]) => any; + password : string; + readyState : number; + responseData : Ti.Blob; + responseText : string; + responseXML : Ti.XML.Document; + securityManager : SecurityManagerProtocol; + status : number; + statusText : string; + timeout : number; + tlsVersion : number; + username : string; + validatesSecureCertificate : boolean; + withCredentials : boolean; + abort () : void; + addAuthFactory (scheme: string, factory: any) : void; + addKeyManager (X509KeyManager: any) : void; + addTrustManager (X509TrustManager: any) : void; + clearCookies (host: string) : void; + getAllResponseHeaders () : string; + getAutoEncodeUrl () : boolean; + getAutoRedirect () : boolean; + getCache () : boolean; + getConnected () : boolean; + getConnectionType () : string; + getDomain () : string; + getEnableKeepAlive () : boolean; + getFile () : string; + getLocation () : string; + getOndatastream () : (...args : any[]) => any; + getOnerror () : (...args : any[]) => any; + getOnload () : (...args : any[]) => any; + getOnreadystatechange () : (...args : any[]) => any; + getOnsendstream () : (...args : any[]) => any; + getPassword () : string; + getReadyState () : number; + getResponseData () : Ti.Blob; + getResponseHeader (name: string) : string; + getResponseText () : string; + getResponseXML () : Ti.XML.Document; + getSecurityManager () : SecurityManagerProtocol; + getStatus () : number; + getStatusText () : string; + getTimeout () : number; + getTlsVersion () : number; + getUsername () : string; + getValidatesSecureCertificate () : boolean; + getWithCredentials () : boolean; + open (method: string, url: string, async?: boolean) : void; + send (data?: any) : void; + send (data?: string) : void; + send (data?: Ti.Filesystem.File) : void; + send (data?: Ti.Blob) : void; + setAutoEncodeUrl (autoEncodeUrl: boolean) : void; + setAutoRedirect (autoRedirect: boolean) : void; + setCache (cache: boolean) : void; + setDomain (domain: string) : void; + setEnableKeepAlive (enableKeepAlive: boolean) : void; + setFile (file: string) : void; + setOndatastream (ondatastream: (...args : any[]) => any) : void; + setOnerror (onerror: (...args : any[]) => any) : void; + setOnload (onload: (...args : any[]) => any) : void; + setOnreadystatechange (onreadystatechange: (...args : any[]) => any) : void; + setOnsendstream (onsendstream: (...args : any[]) => any) : void; + setPassword (password: string) : void; + setRequestHeader (name: string, value: string) : void; + setTimeout (timeout: number) : void; + setTlsVersion (tlsVersion: number) : void; + setUsername (username: string) : void; + setValidatesSecureCertificate (validatesSecureCertificate: boolean) : void; + setWithCredentials (withCredentials: boolean) : void; + } + export interface BonjourBrowser extends Ti.Proxy { + domain : string; + isSearching : boolean; + serviceType : string; + getDomain () : string; + getIsSearching () : boolean; + getServiceType () : string; + search () : void; + setDomain (domain: string) : void; + setIsSearching (isSearching: boolean) : void; + setServiceType (serviceType: string) : void; + stopSearch () : void; + } + export interface Cookie extends Ti.Proxy { + comment : string; + domain : string; + expiryDate : string; + httponly : boolean; + name : string; + originalUrl : string; + path : string; + secure : boolean; + value : string; + version : number; + getComment () : string; + getDomain () : string; + getExpiryDate () : string; + getHttponly () : boolean; + getName () : string; + getOriginalUrl () : string; + getPath () : string; + getSecure () : boolean; + getValue () : string; + getVersion () : number; + isValid () : boolean; + setComment (comment: string) : void; + setDomain (domain: string) : void; + setExpiryDate (expiryDate: string) : void; + setHttponly (httponly: boolean) : void; + setOriginalUrl (originalUrl: string) : void; + setPath (path: string) : void; + setSecure (secure: boolean) : void; + setValue (value: string) : void; + setVersion (version: number) : void; + } + } export interface Yahoo { yql (yql: string, callback: (...args : any[]) => any) : void; } @@ -5334,6 +5990,7 @@ declare module Ti { export var BUTTON_STYLE_NORMAL : number; export var BUTTON_STYLE_WIDE : number; export var accessToken : string; + export var apiName : string; export var appid : string; export var bubbleParent : boolean; export var expirationDate : Date; @@ -5348,6 +6005,7 @@ declare module Ti { export function dialog (action: string, params: any, callback: (...args : any[]) => any) : void; export function fireEvent (name: string, event: Dictionary) : void; export function getAccessToken () : string; + export function getApiName () : string; export function getAppid () : string; export function getBubbleParent () : boolean; export function getExpirationDate () : Date; @@ -5381,6 +6039,7 @@ declare module Ti { base64decode (obj: Ti.Blob) : Ti.Blob; base64encode (obj: string) : Ti.Blob; base64encode (obj: Ti.Blob) : Ti.Blob; + base64encode (obj: Ti.Filesystem.File) : Ti.Blob; md5HexDigest (obj: string) : string; md5HexDigest (obj: Ti.Blob) : string; sha1 (obj: string) : string; @@ -5437,6 +6096,12 @@ declare class FacebookRESTResponsev1 { success : boolean; } +declare class titleAttributesParams { + color : string; + font : Font; + shadow : shadowDict; +} + declare class MapRegionType { latitude : number; latitudeDelta : number; @@ -5462,8 +6127,8 @@ declare class ErrorResponse { success : boolean; } -declare enum CloudPushNotificationsResponse { - +declare class CloudPushNotificationsQueryResponse extends CloudResponse { + subscriptions : Array>; } declare class CloudResponse { @@ -5474,6 +6139,15 @@ declare class CloudResponse { success : boolean; } +declare enum CloudPushNotificationsResponse { + +} + +declare class textFieldSelectedParams { + length : number; + location : number; +} + declare class recurrenceEndDictionary { endDate : Date; occurrenceCount : number; @@ -5513,6 +6187,10 @@ declare module Global { } } +declare class CloudGeoFenceResponse extends CloudResponse { + geo_fences : Array>; +} + declare class ServiceIntentOptions { startMode : number; url : string; @@ -5609,6 +6287,10 @@ declare class ListViewAnimationProperties { position : number; } +declare class CloudPushSchedulesResponse extends CloudResponse { + push_schedules : Array; +} + declare class DataCallbackArgs { address : string; bytesData : Array; @@ -5650,13 +6332,19 @@ declare class CloudEventsResponse extends CloudResponse { events : Array>; } +declare class ReadyStatePayload { + readyState : number; +} + declare class ErrorCallbackArgs { errorCode : number; socket : Ti.Network.Socket.TCP; } -declare enum FailureResponse { - +declare class FailureResponse { + code: Number; + error: string; + success: boolean; } declare class WriteCallbackArgs extends ErrorResponse { @@ -5691,6 +6379,11 @@ declare class ListViewContentInsetOption { duration : number; } +declare class RouteDescription { + inputs : Array; + outputs : Array; +} + declare class CreateStreamArgs { mode : number; source : any; @@ -5772,6 +6465,12 @@ declare class MusicLibraryOptionsType { success : (...args : any[]) => any; } +declare class shadowDict { + blurRadius : number; + color : string; + offset : Dictionary; +} + declare class launchOptions { launchOptionsLocationKey : boolean; source : string; @@ -5813,11 +6512,21 @@ declare class CloudObjectsResponse extends CloudResponse { classname : Array>; } +declare class PopoverParams { + animated : boolean; + rect : Dimension; + view : Ti.UI.View; +} + declare class MediaScannerResponse { path : string; uri : string; } +declare class CloudPushNotificationsQueryChannelResponse extends CloudResponse { + push_channels : Array; +} + declare class CloudPostsResponse extends CloudResponse { posts : Array>; } @@ -5826,11 +6535,16 @@ declare class CloudSocialIntegrationsResponse extends CloudResponse { users : Array>; } +declare class APSConnectionDelegate { + +} + declare class CameraOptionsType { allowEditing : boolean; animated : boolean; arrowDirection : number; autohide : boolean; + autorotate : boolean; cancel : (...args : any[]) => any; error : (...args : any[]) => any; inPopOver : boolean; @@ -6004,6 +6718,7 @@ declare class NotificationParams { alertBody : string; alertLaunchImage : string; badge : number; + category : string; date : Date; repeat : string; sound : string; @@ -6024,11 +6739,24 @@ declare class Modules { } +declare class ReferenceInsets { + bottom : number; + left : number; + right : number; + top : number; +} + declare class hideStatusBarParams { animated : boolean; animationStyle : number; } +declare class PreviewImageOptions { + error : (...args : any[]) => any; + image : Ti.Blob; + success : (...args : any[]) => any; +} + declare class ListDataItem { properties : Dictionary; template : any; @@ -6062,6 +6790,12 @@ declare class ListViewEdgeInsets { top : number; } +declare class BoundaryIdentifier { + identifier : string; + point1 : Point; + point2 : Point; +} + declare enum CloudEmailsResponse { } @@ -6076,6 +6810,7 @@ declare class Font { fontSize : any; fontStyle : string; fontWeight : string; + textStyle : string; } declare class CloudPlacesResponse extends CloudResponse { @@ -6119,6 +6854,13 @@ declare class hideParams { animated : boolean; } +declare class SecurityManagerProtocol { + connectionDelegateForUrl (url: any) : APSConnectionDelegate; + getKeyManagers (proxy: any) : Array; + getTrustManagers (proxy: any) : Array; + willHandleURL (url: any) : boolean; +} + declare class openWindowParams { activityEnterAnimation : number; activityExitAnimation : number; @@ -6153,6 +6895,12 @@ declare class showStatusBarParams { animationStyle : number; } +declare class transitionAnimationParam { + duration : number; + tranistionTo : Ti.UI.Animation; + transitionFrom : Ti.UI.Animation; +} + declare class MapPointType { latitude : number; longitude : number; @@ -6173,6 +6921,16 @@ declare class ReverseGeocodeResponse extends ErrorResponse { places : Array; } +declare class contentOffsetOption { + animated : boolean; +} + +declare class Attribute { + range : Array; + type : number; + value : number; +} + declare class PushNotificationSuccessArg { deviceToken : string; type : string; @@ -6189,9 +6947,13 @@ declare class closeWindowParams { animated : boolean; } +declare class CloudLikesResponse extends CloudResponse { + likes : Array>; +} + declare class showParams { animated : boolean; - rect : Dictionary; + rect : Dimension; view : Ti.UI.View; } @@ -6203,6 +6965,10 @@ declare class CloudMessagesResponse extends CloudResponse { messages : Array>; } +declare class CloudPushNotificationsShowChannelResponse extends CloudResponse { + devices : Dictionary; +} + declare class ImageAsCroppedDict { height : number; width : number; @@ -6210,14 +6976,9 @@ declare class ImageAsCroppedDict { y : number; } -declare class PreviewImageOptions { - error : (...args : any[]) => any; - image : Ti.Blob; - success : (...args : any[]) => any; -} - -declare class contentOffsetOption { - animated : boolean; +declare class UserNotificationSettings { + categories : Array; + types : Array; } declare class TableViewAnimationProperties { @@ -6237,4 +6998,4 @@ declare class EncodeStringDict { source : string; sourceLength : number; sourcePosition : number; -} \ No newline at end of file +} diff --git a/typescript-deferred/typescript-deferred-tests.ts b/typescript-deferred/typescript-deferred-tests.ts new file mode 100644 index 0000000000..0bfa825825 --- /dev/null +++ b/typescript-deferred/typescript-deferred-tests.ts @@ -0,0 +1,61 @@ +/// + +import tsd = require('typescript-deferred'); + +var t1: tsd.PromiseInterface = tsd.when(10) + .then(() => tsd.when('foo')); + +var t2: tsd. PromiseInterface = tsd.when(10) + .then(() => 'foo'); + +var t3: tsd.PromiseInterface = tsd.when(10) + .then(() => 'foo', () => tsd.when('bar')); + +var t4: tsd.PromiseInterface = tsd.when(10) + .then(() => 'foo', () => 'bar'); + +var t5: tsd.PromiseInterface = tsd.when(10) + .then(() => tsd.when('foo'), () => 'bar'); + +var t6: tsd.PromiseInterface = tsd.when(10) + .then(() => tsd.when('foo'), () => tsd.when('bar')); + +var t7: tsd.PromiseInterface = tsd.when(10) + .always(() => 'foo'); + +var t8: tsd.PromiseInterface = tsd.when(10) + .always(() => tsd.when('foo')); + +var t9: tsd.PromiseInterface = tsd.when(10) + .otherwise(() => 11); + +var t10: tsd.PromiseInterface = tsd.when(10) + .otherwise(() => tsd.when(11)); + +var t11: tsd.PromiseInterface = tsd.when('foo'); + +var t12: tsd.PromiseInterface = tsd.when(tsd.when('foo')); + +var t13: tsd.PromiseInterface = tsd.create() + .promise; + +var t14: tsd.DeferredInterface = tsd.create(); + +var t15: tsd.ThenableInterface = tsd.when('foo'); + +var t16: tsd.PromiseInterface = tsd.when( >tsd.when('foo')); + +var t17: tsd.PromiseInterface = tsd.when(10) + .then(() => >tsd.when('foo'), () => >tsd.when('bar')); + +var t18: tsd.PromiseInterface = tsd.create() + .resolve('foo') + .promise; + +var t19: tsd.PromiseInterface = tsd.create() + .resolve(tsd.when('foo')) + .promise; + +var t20: tsd.PromiseInterface = tsd.create() + .reject(new Error('foo')) + .promise; diff --git a/typescript-deferred/typescript-deferred.d.ts b/typescript-deferred/typescript-deferred.d.ts new file mode 100644 index 0000000000..bffc65b70f --- /dev/null +++ b/typescript-deferred/typescript-deferred.d.ts @@ -0,0 +1,47 @@ +// Type definitions for typescript-deferred v0.1.5 +// Project: https://github.com/DirtyHairy/typescript-deferred +// Definitions by: Christian Speckner +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "typescript-deferred" { + + export interface ImmediateSuccessCB { + (value: T): TP; + } + export interface ImmediateErrorCB { + (err: any): TP; + } + export interface DeferredSuccessCB { + (value: T): ThenableInterface; + } + export interface DeferredErrorCB { + (error: any): ThenableInterface; + } + export interface ThenableInterface { + then(successCB?: DeferredSuccessCB, errorCB?: DeferredErrorCB): ThenableInterface; + then(successCB?: DeferredSuccessCB, errorCB?: ImmediateErrorCB): ThenableInterface; + then(successCB?: ImmediateSuccessCB, errorCB?: DeferredErrorCB): ThenableInterface; + then(successCB?: ImmediateSuccessCB, errorCB?: ImmediateErrorCB): ThenableInterface; + } + export interface PromiseInterface extends ThenableInterface { + then(successCB?: DeferredSuccessCB, errorCB?: DeferredErrorCB): PromiseInterface; + then(successCB?: DeferredSuccessCB, errorCB?: ImmediateErrorCB): PromiseInterface; + then(successCB?: ImmediateSuccessCB, errorCB?: DeferredErrorCB): PromiseInterface; + then(successCB?: ImmediateSuccessCB, errorCB?: ImmediateErrorCB): PromiseInterface; + otherwise(errorCB?: DeferredErrorCB): PromiseInterface; + otherwise(errorCB?: ImmediateErrorCB): PromiseInterface; + always(errorCB?: DeferredErrorCB): PromiseInterface; + always(errorCB?: ImmediateErrorCB): PromiseInterface; + } + export interface DeferredInterface { + resolve(value?: ThenableInterface): DeferredInterface; + resolve(value?: T): DeferredInterface; + reject(error?: any): DeferredInterface; + promise: PromiseInterface; + } + export function create(): DeferredInterface; + export function when(value?: ThenableInterface): PromiseInterface; + export function when(value?: T): PromiseInterface; + + +} diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 9f49bc47aa..7ff9aa5eb7 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -278,7 +278,7 @@ interface UnderscoreStatic { findIndex( list: _.List, iterator: _.ListIterator, - context?: any): T; + context?: any): number; /** diff --git a/vex-js/vex-js.d.ts b/vex-js/vex-js.d.ts new file mode 100644 index 0000000000..118c618672 --- /dev/null +++ b/vex-js/vex-js.d.ts @@ -0,0 +1,45 @@ +// Type definitions for Vex v2.3.2 +// Project: https://github.com/HubSpot/vex +// Definitions by: Greg Cohan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module vex { + + interface ICSSAttributes { + [property: string]: string | number; + } + + interface IVexOptions { + afterClose?: (() => void); + afterOpen?: ((vexContent: JQuery) => void); + content?: string; + showCloseButton?: boolean; + escapeButtonCloses?: boolean; + overlayClosesOnClick?: boolean; + appendLocation?: HTMLElement | JQuery | string; + className?: string; + css?: ICSSAttributes; + overlayClassName?: string; + overlayCSS?: ICSSAttributes; + contentClassName?: string; + contentCSS?: ICSSAttributes; + closeClassName?: string; + closeCSS?: ICSSAttributes; + } + + interface Vex { + open(options: IVexOptions): JQuery; + close(id?: number): boolean; + closeAll(): boolean; + closeByID(id: number): boolean; + } + +} + +declare module "vex" { + export = vex; +} + +declare var vex: vex.Vex; diff --git a/vex-js/vex-tests.ts b/vex-js/vex-tests.ts new file mode 100644 index 0000000000..ea1778d610 --- /dev/null +++ b/vex-js/vex-tests.ts @@ -0,0 +1,26 @@ +/// +/// + +var vexContent = vex.open({ + afterClose: (() => null), + afterOpen: ((vexContent: JQuery) => null), + content: "

Modal

", + showCloseButton: false, + escapeButtonCloses: true, + overlayClosesOnClick: false, + appendLocation: "body", + className: "vex-dialog", + css: {background: "blue"}, + overlayClassName: "vex-overlay", + overlayCSS: {border: 0}, + contentClassName: "vex-content", + contentCSS: {margin: "0 auto"}, + closeClassName: "vex-close", + closeCSS: {margin: 0} +}); + +var id = vexContent.data().vex.id; + +vex.close(id); +vex.closeByID(id); +vex.closeAll(); diff --git a/webcomponents.js/webcomponents.js-tests.ts b/webcomponents.js/webcomponents.js-tests.ts new file mode 100644 index 0000000000..316f9dd8e5 --- /dev/null +++ b/webcomponents.js/webcomponents.js-tests.ts @@ -0,0 +1,39 @@ +/// + +/* + * Custom Elements + */ +var fooProto = Object.create(HTMLElement.prototype, { + createdCallback() { + // `this` should be the created element + this.getElementsByTagName("a"); + } +}); + +document.registerElement("x-foo", { + prototype: fooProto +}); + +window.CustomElements.hasNative; +window.CustomElements.flags; +window.CustomElements.ready; +window.CustomElements.useNative; + +/* + * HTMLImports + */ + +window.HTMLImports.isIE; +window.HTMLImports.rootDocument.querySelectorAll("div"); +window.HTMLImports.useNative; +window.HTMLImports.whenReady(() => { + return window.HTMLImports.ready === true; +}); + +document.querySelectorAll(`link[type=${window.HTMLImports.IMPORT_LINK_TYPE}`); + +/* + * Web Components + */ +window.WebComponents.flags; + diff --git a/webcomponents.js/webcomponents.js.d.ts b/webcomponents.js/webcomponents.js.d.ts new file mode 100644 index 0000000000..43e85373fc --- /dev/null +++ b/webcomponents.js/webcomponents.js.d.ts @@ -0,0 +1,48 @@ +// Type definitions for webcomponents.js 0.6.0 +// Project: https://github.com/webcomponents/webcomponentsjs +// Definitions by: Adi Dahiya +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module webcomponents { + + export interface CustomElementInit { + prototype: HTMLElement; + extends?: string; + } + + export interface CustomElementsPolyfill { + hasNative: boolean; + flags: any; + ready: boolean; + useNative: boolean; + } + + export interface HTMLImportsPolyfill { + IMPORT_LINK_TYPE: string; + isIE: boolean; + flags: any; + ready: boolean; + rootDocument: Document; + useNative: boolean; + whenReady(callback: () => void): void; + } + + export interface Polyfill { + flags: any; + } + +} + +declare module "webcomponents.js" { + export = webcomponents; +} + +interface Document { + registerElement(name: string, prototype: webcomponents.CustomElementInit): void; +} + +interface Window { + CustomElements: webcomponents.CustomElementsPolyfill; + HTMLImports: webcomponents.HTMLImportsPolyfill; + WebComponents: webcomponents.Polyfill; +} diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index cc3e6320af..5248f5d1dd 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -11,6 +11,16 @@ function test_fetchUrlWithOptions() { handlePromise(window.fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions)); } +function test_fetchUrlWithHeadersObject() { + var requestOptions: RequestInit = { + method: "POST", + headers: { + 'Content-Type': 'application/json' + } + }; + handlePromise(window.fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions)); +} + function test_fetchUrl() { handlePromise(window.fetch("http://www.andlabs.net/html5/uCOR.php")); } @@ -21,4 +31,4 @@ function handlePromise(promise: Promise) { }).then((text) => { console.log(text); }); -} \ No newline at end of file +} diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index d847463bdf..4a4a9612c3 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -19,7 +19,7 @@ declare class Request { interface RequestInit { method?: string; - headers?: HeaderInit; + headers?: HeaderInit|{ [index: string]: string }; body?: BodyInit; mode?: RequestMode; credentials?: RequestCredentials; @@ -81,4 +81,4 @@ declare type RequestInfo = Request|string; interface Window { fetch(url: string, init?: RequestInit): Promise; -} \ No newline at end of file +} diff --git a/winrt/winrt.d.ts b/winrt/winrt.d.ts index 91c0a28013..883860b000 100644 --- a/winrt/winrt.d.ts +++ b/winrt/winrt.d.ts @@ -12203,8 +12203,8 @@ declare module Windows { createWithId(tileId: string): Windows.UI.StartScreen.SecondaryTile; } export class SecondaryTile implements Windows.UI.StartScreen.ISecondaryTile { - constructor(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri); - constructor(tileId: string, shortName: string, displayName: string, arguments: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri, wideLogoReference: Windows.Foundation.Uri); + constructor(tileId: string, shortName: string, displayName: string, args: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri); + constructor(tileId: string, shortName: string, displayName: string, args: string, tileOptions: Windows.UI.StartScreen.TileOptions, logoReference: Windows.Foundation.Uri, wideLogoReference: Windows.Foundation.Uri); constructor(tileId: string); constructor(); arguments: string; diff --git a/xrm/clientglobalcontext.d.ts b/xrm/clientglobalcontext.d.ts new file mode 100644 index 0000000000..ae7bcc219c --- /dev/null +++ b/xrm/clientglobalcontext.d.ts @@ -0,0 +1,14 @@ +// Type definitions for Microsoft Dynamics xRM ClientGlobalContext.js.aspx +// Project: http://msdn.microsoft.com/en-us/library/gg328255.aspx +// Definitions by: David Berry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** + * Gets the xRM application context, for HTML web resources + * @returns {Xrm.Context} The application context for the user's current session. + * @remarks The ClientGlobalContext.js.aspx page will include some global event handlers. These event handlers will + * cancel the onselectstart, contextmenu, and ondragstart events. + */ +declare function GetGlobalContext(): Xrm.Context; \ No newline at end of file diff --git a/xrm/parature.d.ts b/xrm/parature.d.ts new file mode 100644 index 0000000000..030c97b680 --- /dev/null +++ b/xrm/parature.d.ts @@ -0,0 +1,143 @@ +// Type definitions for Microsoft Parature extentions to Xrm.Page - available for CRM Online Only +// Project: http://msdn.microsoft.com/en-us/library/gg328255.aspx +// Definitions by: David Berry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Xrm.Page +{ + /** + * Interface for Parature's knowledge base search control. + * + * @sa Control + */ + export interface KbSearchControl extends Control + { + /** + * Use this method to add an event handler to the OnResultOpened event. + * + * @param {Function} handler The handler. + */ + addOnResultOpened( handler: () => void ): void; + + /** + * Use this method to add an event handler to the OnSelection event. + * + * @param {Function} handler The handler. + */ + addOnSelection( handler: () => void ): void; + + /** + * Use this method to get the text used as the search criteria for the knowledge base management control. + * + * @return The search query. + */ + getSearchQuery(): string; + + /** + * Use this method to get the currently selected result of the search control. The currently selected result also + * represents the result that is currently open. + * + * @return The selected result. + */ + getSelectedResult(): KbSearchResult; + + /** + * Use this method to remove an event handler from the OnResultOpened event. + * + * @param {Function} handler The handler. + */ + removeOnResultOpened( handler: () => void ): void; + + /** + * Use this method to remove an event handler from the OnSelection event. + * + * @param {Function} handler The handler. + */ + removeOnSelection( handler: () => void ): void; + + /** + * Use this method to set the text used as the search criteria for the knowledge base management control. + * + * @param {string} query The text for the search query. + */ + setSearchQuery( query: string ): void; + } + + /** + * Interface for a Parature knowledge base search result. + */ + export interface KbSearchResult + { + /** + * The HTML markup containing the content of the article. + */ + answer: string; + + /** + * The Article ID in a Parature department + */ + articleId: string; + + /** + * Unique Article ID for the Parature system. + */ + articleUid: string; + + /** + * The date the article was created. + */ + createdOn: Date; + + /** + * The date the article was or will be expired. + */ + expiredDate: Date; + + /** + * Whether the article is associated with the parent record or not + */ + isAssociated: boolean; + + /** + * Date on which the article was last modified. + */ + lastModifiedOn: Date; + + /** + * Support Portal URL of the article. + */ + publicUrl: string; + + /** + * Whether the Article is in published or draft state. + */ + published: boolean; + + /** + * The title of the article. + */ + question: string; + + /** + * The rating of the article. + */ + rating: number; + + /** + * A short snippet of article content which contains the areas where the search query was hit. + */ + searchBlurb: string; + + /** + * Link to the article in the Parature service desk. + */ + serviceDeskUri: string; + + /** + * The number of times an article is viewed on the Parature portal by customers. + */ + timesViewed: number; + } +} diff --git a/xrm/xrm-6.d.ts b/xrm/xrm-6.d.ts new file mode 100644 index 0000000000..f2a88eb44c --- /dev/null +++ b/xrm/xrm-6.d.ts @@ -0,0 +1,2071 @@ +// Type definitions for Microsoft Dynamics xRM API v6 +// Project: http://msdn.microsoft.com/en-us/library/gg328255.aspx +// Definitions by: David Berry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Xrm +{ + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): string; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): string; + } + + /** + * Interface for the xRM application context. + */ + export interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): string; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Interface for success callbacks. + */ + export interface SuccessCallbackDelegate + { + /** + * Called when the operation is successful. + */ + (): void; + } + + /** + * Interface for error callbacks. + */ + export interface ErrorCallbackDelegate + { + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + ( errorCode: number, message: string ): void; + } + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Xrm.Page.Attribute | Xrm.Page.Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a string. + * + * @remarks You must use parseInt to convert this value to a number before you can use it to + * set the value of an OptionSetAttribute. + */ + value: string; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): string; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): string; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets required level. + * + * @param {"none"} requirementLevel Not required. + */ + setRequiredLevel( requirementLevel: "none" ): void; + + /** + * Sets required level. + * + * @param {"required"} requirementLevel Required. + */ + setRequiredLevel( requirementLevel: "required" ): void; + + /** + * Sets required level. + * + * @param {"recommended"} requirementLevel Recommended. + */ + setRequiredLevel( requirementLevel: "recommended" ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel( requirementLevel: string ): void; + + /** + * Sets submit mode. + * + * @param {"always"} submitMode Always submit this attribute. + */ + setSubmitMode( submitMode: "always" ): void; + + /** + * Sets submit mode. + * + * @param {"never"} submitMode Never submit this attribute. + */ + setSubmitMode( submitMode: "never" ): void; + + /** + * Sets submit mode. + * + * @param {"dirty"} submitMode Submit this attribute when changed. + */ + setSubmitMode( submitMode: "dirty" ): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode( submitMode: string ): void; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandclose"} saveMode Saves the record, and closes the form. + */ + save( saveMode: "saveandclose" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandnew"} saveMode Saves the record, and opens a blank form. + */ + save( saveMode: "saveandnew" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: string ): void; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Interface for the Xrm.Page.data API. + */ + export interface Data + { + /** + * The record context of the form. + */ + entity: Entity; + + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh + * + * @return An Async.XrmPromise. + */ + refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + save(): Async.XrmPromise; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: () => void ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
; + + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): string; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): Ui; + + /** + * Sets display state of the tab. + * + * @param {"collapsed"} displayState Collapsed tab. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the tab. + * + * @param {"expanded"} displayState Expanded tab. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + } + + /** + * Interface for Xrm.Page.ui API. + */ + export interface Ui + { + /** + * A reference to the collection of controls on the form. + */ + controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + formSelector: FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + navigation: Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + tabs: Collection.ItemCollection; + + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + getFormType(): FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + refreshRibbon(): void; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"ERROR"} level An error message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"WARNING"} level A warning message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"INFO"} level An informational message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, otherwise false. + */ + setFormNotification( message: string, level: string, uniqueId: string ): boolean; + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + + /** + * A reference to the xRM application context. + */ + export var context: Context; + + /** + * A reference to the form's user interface API. + */ + export var ui: Ui; + + /** + * A reference to the form's data API. + */ + export var data: Data; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + export function getAttribute(): Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + export function getAttribute( index: number ): Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + export function getAttribute( delegateFunction: Collection.MatchingDelegate ): Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + export function getControl(): Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + export function getControl( index: number ): Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + export function getControl( delegateFunction: Collection.MatchingDelegate ): Control[]; + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: string; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + export function alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + export function confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + export function isActivityType( entityType: string ): boolean; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) Options for controlling the operation. + */ + export function openEntityForm( name: string, id?: string, parameters?: FormOpenParameters ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + export function openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } +} diff --git a/xrm/xrm-6.tests.ts b/xrm/xrm-6.tests.ts new file mode 100644 index 0000000000..a791d861e3 --- /dev/null +++ b/xrm/xrm-6.tests.ts @@ -0,0 +1,69 @@ +/// +/// + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.refresh(); +}); + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === Xrm.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === Xrm.Page.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); diff --git a/xrm/xrm-7.0.d.ts b/xrm/xrm-7.0.d.ts new file mode 100644 index 0000000000..42814382d8 --- /dev/null +++ b/xrm/xrm-7.0.d.ts @@ -0,0 +1,2350 @@ +// Type definitions for Microsoft Dynamics xRM API v7.0 +// Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 +// Definitions by: David Berry , Matt Ngan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Xrm +{ + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): string; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): string; + } + + /** + * Interface for the xRM application context. + */ + export interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): string; + + /** + * Gets whether automatic save is enabled. + * + * @return true if automatic saving is enabled, otherwise false. + */ + getIsAutoSaveEnabled(): boolean; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Called when the operation is successful. + */ + export type SuccessCallbackDelegate = () => void; + + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + export type ErrorCallbackDelegate = ( errorCode: number, message: string ) => void; + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Enumeration of stage categories. + */ + export const enum StageCategory + { + Qualify = 0, + Develop = 1, + Propose = 2, + Close = 3, + Identify = 4, + Research = 5, + Resolve = 6 + } + + export interface Process + { + /** + * Returns the unique identifier of the process. + * + * @return The identifier for this process, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the process. + * + * @return The name. + */ + getName(): string; + + /** + * Returns an collection of stages in the process. + * + * @return The stages. + */ + getStages(): Collection.ItemCollection; + + /** + * Returns a boolean value to indicate if the process is rendered. + * + * @return true if the process is rendered, false if not. + */ + isRendered(): boolean; + } + + /** + * Interface for CRM Business Process Flow stages. + */ + export interface Stage + { + /** + * Returns an object with a getValue method which will return the integer value of the business process flow + * category. + * + * @return The stage category. + */ + getCategory(): { getValue(): StageCategory }; + + /** + * Returns the logical name of the entity associated with the stage. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns the unique identifier of the stage. + * + * @return The identifier of the Stage, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the stage. + * + * @return The name. + */ + getName(): string; + + /** + * Returns the status of the stage. + * + * @return The status. + * + * @remarks This method will return either "active" or "inactive". + */ + getStatus(): string; + + /** + * Returns a collection of steps in the stage. + * + * @return An array of Step. + */ + getSteps(): Step[]; + } + + export interface Step + { + /** + * Returns the logical name of the attribute associated to the step. + * + * @return The attribute. + * + * @remarks Some steps don’t contain an attribute value. + */ + getAttribute(): string; + + /** + * Returns the name of the step. + * + * @return The name. + */ + getName(): string; + + /** + * Returns whether the step is required in the business process flow. + * + * @return true if required, false if not. + * + * @remarks Returns true if the step is marked as required in the Business Process Flow editor; otherwise, false. + * There is no connection between this value and the values you can change in the Xrm.Page.data.entity + * attribute RequiredLevel methods. + */ + isRequired(): boolean; + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Xrm.Page.Attribute | Xrm.Page.Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a string. + * + * @remarks You must use parseInt to convert this value to a number before you can use it to + * set the value of an OptionSetAttribute. + */ + value: string; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): string; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): string; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets required level. + * + * @param {"none"} requirementLevel Not required. + */ + setRequiredLevel( requirementLevel: "none" ): void; + + /** + * Sets required level. + * + * @param {"required"} requirementLevel Required. + */ + setRequiredLevel( requirementLevel: "required" ): void; + + /** + * Sets required level. + * + * @param {"recommended"} requirementLevel Recommended. + */ + setRequiredLevel( requirementLevel: "recommended" ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel( requirementLevel: string ): void; + + /** + * Sets submit mode. + * + * @param {"always"} submitMode Always submit this attribute. + */ + setSubmitMode( submitMode: "always" ): void; + + /** + * Sets submit mode. + * + * @param {"never"} submitMode Never submit this attribute. + */ + setSubmitMode( submitMode: "never" ): void; + + /** + * Sets submit mode. + * + * @param {"dirty"} submitMode Submit this attribute when changed. + */ + setSubmitMode( submitMode: "dirty" ): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode( submitMode: string ): void; + + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandclose"} saveMode Saves the record, and closes the form. + */ + save( saveMode: "saveandclose" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandnew"} saveMode Saves the record, and opens a blank form. + */ + save( saveMode: "saveandnew" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: string ): void; + + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Module for the Xrm.Page.data API. + */ + export module data + { + /** + * Interface for the Xrm.Page.data.process API. + */ + export interface ProcessManager + { + /** + * Returns a Process object representing the active process. + * + * @return current active process. + */ + getActiveProcess(): Process; + + /** + * Set a Process as the active process. + * + * @param {string} processId the Id of the process to make the active process. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveProcess( processId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Returns a Stage object representing the active stage. + * + * @return current active stage. + */ + getActiveStage(): Stage; + + /** + * Set a stage as the active stage. + * + * @param {string} stageId the Id of the stage to make the active stage. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveStage( stageId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Use this method to get a collection of stages currently in the active path with methods to interact with the + * stages displayed in the business process flow control. The active path represents stages currently rendered in + * the process control based on the branching rules and current data in the record. + * + * @return A collection of all completed stages, the currently active stage, and the predicted set of future stages + * based on satisfied conditions in the branching rule. This may be a subset of the stages returned with + * Xrm.Page.data.process.getActiveProcess because it will only include those stages which represent a valid + * transition from the current stage based on branching that has occurred in the process. + */ + getActivePath(): Collection.ItemCollection; + + /** + * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an + * entity. + * + * @param {Function} callbackFunction The callback function must accept a parameter + * that contains an object with dictionary + * properties where the name of the property is the + * Id of the business process flow and the value of + * the property is the name of the business process + * flow. + * + * The enabled processes are filtered according to + * the user’s privileges. The list of enabled + * processes is the same ones a user can see in the + * UI if they want to change the process manually. + */ + getEnabledProcesses( callbackFunction: ( enabledProcesses: ProcessDictionary ) => void ): void; + + /** + * Use this to add a function as an event handler for the OnStageChange event so that it will be called when the + * business process flow stage changes. + * + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event handler + * pipeline. The execution context is automatically set to be the first + * parameter passed to the event handler. + */ + addOnStageChange( handler: ContextSensitiveHandler ): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageSelected( handler: ContextSensitiveHandler ): void; + + /** + * Progresses to the next stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + moveNext( callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Moves to the previous stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + movePrevious( callbackFunction?: ProcessCallbackDelegate ): void; + } + + /** + * Called when process change methods have completed. + * + * @param {string} status The result of the process change operation. + * @remarks Values returned are: success (The operation succeeded.) + * crossEntity (The previous stage is for a different entity.) + * beginning (The active stage is the first stage of the active path.) + * invalid (The operation failed because the selected stage isn’t the same + * as the active stage.) + * unreachable (The stage exists on a different path.) + */ + export type ProcessCallbackDelegate = ( status: string ) => void; + + /** + * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. + */ + export type ProcessDictionary = { [index: string]: string }; + + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh. + * + * @return An Async.XrmPromise. + */ + export function refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + export function save(): Async.XrmPromise; + + /** + * The record context of the form. + */ + export var entity: Entity; + + /** + * The process API for Xrm.Page.data. + * + * @remarks This member may be undefined when Process Flows are not used by the current entity. + */ + export var process: ProcessManager; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: () => void ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): string; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): typeof ui; + + /** + * Sets display state of the tab. + * + * @param {"collapsed"} displayState Collapsed tab. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the tab. + * + * @param {"expanded"} displayState Expanded tab. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + } + + /** + * Module for Xrm.Page.ui API. + */ + export module ui + { + /** + * Interface for Xrm.Page.ui.process API + */ + export interface ProcessManager + { + /** + * Sets display state of the process flow control. + * + * @param {"collapsed"} displayState Collapsed process flow control. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {"expanded"} displayState Expanded process flow control. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {string} displayState Display state of the process flow control, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + export function clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + export function close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + export function getFormType(): FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function refreshRibbon(): void; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"ERROR"} level An error message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"WARNING"} level A warning message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"INFO"} level An informational message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, otherwise false. + */ + export function setFormNotification( message: string, level: string, uniqueId: string ): boolean; + + export var process: ProcessManager; + + /** + * A reference to the collection of controls on the form. + */ + export var controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var formSelector: FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var navigation: Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + export var tabs: Collection.ItemCollection; + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + + /** + * A reference to the xRM application context. + */ + export var context: Context; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + export function getAttribute(): Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + export function getAttribute( index: number ): Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + export function getAttribute( delegateFunction: Collection.MatchingDelegate ): Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + export function getControl(): Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + export function getControl( index: number ): Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + export function getControl( delegateFunction: Collection.MatchingDelegate ): Control[]; + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: string; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + export interface OpenParameters + { + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters extends OpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + } + + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + export function alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + export function confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + export function isActivityType( entityType: string ): boolean; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + */ + export function openEntityForm( name: string, id?: string, parameters?: FormOpenParameters ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + export function openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } +} diff --git a/xrm/xrm-7.0.tests.ts b/xrm/xrm-7.0.tests.ts new file mode 100644 index 0000000000..cb648e585e --- /dev/null +++ b/xrm/xrm-7.0.tests.ts @@ -0,0 +1,72 @@ +/// +/// + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.refresh(); +}); + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +if (Xrm.Page.data.process != null) + Xrm.Page.data.process.moveNext(( status ) => { alert( `Process moved forward with status: ${status}` ) }); + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === Xrm.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === Xrm.Page.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); diff --git a/xrm/xrm-tests.ts b/xrm/xrm-tests.ts new file mode 100644 index 0000000000..610662c7df --- /dev/null +++ b/xrm/xrm-tests.ts @@ -0,0 +1,103 @@ +/// +/// +/// + +/// Demonstrate clientglobalcontext.d.ts + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +/// Demonstrate iterator typing + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +/// Demonstrate iterator typing with v7.1 additions + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.getGrid().getSelectedRows().forEach(( row ) => + { + selectedGridReferences.push( row.getData().getEntity().getEntityReference() ); + }) +}); + +/// Demonstrate generic overload vs typecast + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); +var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); + +/// Demonstrate ES6 String literal syntax + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +/// Demonstrate strong-typed attribute association with strong-typed control + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +/// Demonstrate v7.0 BPF API + +if (Xrm.Page.data.process != null) + Xrm.Page.data.process.moveNext(( status ) => { alert( `Process moved forward with status: ${status}` ) }); + +/// Demonstrate v7.1 Quick Create form + +Xrm.Utility.openQuickCreate(( newRecord ) => { alert( `Newly created record Id: ${newRecord.id}` ); }, "account" ); + +/// Make all controls visible. + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +/// Make all tabs and sections visible. + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +/// Demonstrate OnSave event context. + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === Xrm.Page.SaveMode.AutoSave || eventArgs.getSaveMode() === Xrm.Page.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +/// Demonstrate ES6 String literal with templates + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts new file mode 100644 index 0000000000..8b82136a4a --- /dev/null +++ b/xrm/xrm.d.ts @@ -0,0 +1,2586 @@ +// Type definitions for Microsoft Dynamics xRM API v7.1 +// Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 +// Definitions by: David Berry , Matt Ngan +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Xrm +{ + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): string; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): string; + } + + /** + * Interface for the xRM application context. + */ + export interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): string; + + /** + * Gets whether automatic save is enabled. + * + * @return true if automatic saving is enabled, otherwise false. + */ + getIsAutoSaveEnabled(): boolean; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Returns the difference between the local time and Coordinated Universal Time (UTC). + * + * @return The time zone offset, in minutes. + */ + getTimeZoneOffsetMinutes(): number; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Called when the operation is successful. + */ + export type SuccessCallbackDelegate = () => void; + + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + export type ErrorCallbackDelegate = ( errorCode: number, message: string ) => void; + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Enumeration of stage categories. + */ + export const enum StageCategory + { + Qualify = 0, + Develop = 1, + Propose = 2, + Close = 3, + Identify = 4, + Research = 5, + Resolve = 6 + } + + /** + * Enumeration of grid control context resolutions. + */ + export const enum GridControlContext + { + Unknown = 0, + RibbonContextForm = 1, + RibbonContextListing = 2, + FormContextUnrelated = 3, + FormContextRelated = 4 + } + + /** + * Interface for a CRM Business Process Flow instance. + */ + export interface Process + { + /** + * Returns the unique identifier of the process. + * + * @return The identifier for this process, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the process. + * + * @return The name. + */ + getName(): string; + + /** + * Returns an collection of stages in the process. + * + * @return The stages. + */ + getStages(): Collection.ItemCollection; + + /** + * Returns a boolean value to indicate if the process is rendered. + * + * @return true if the process is rendered, false if not. + */ + isRendered(): boolean; + } + + /** + * Interface for CRM Business Process Flow stages. + */ + export interface Stage + { + /** + * Returns an object with a getValue method which will return the integer value of the business process flow + * category. + * + * @return The stage category. + */ + getCategory(): { getValue(): StageCategory }; + + /** + * Returns the logical name of the entity associated with the stage. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns the unique identifier of the stage. + * + * @return The identifier of the Stage, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the stage. + * + * @return The name. + */ + getName(): string; + + /** + * Returns the status of the stage. + * + * @return The status. + * + * @remarks This method will return either "active" or "inactive". + */ + getStatus(): string; + + /** + * Returns a collection of steps in the stage. + * + * @return An array of Step. + */ + getSteps(): Step[]; + } + + export interface Step + { + /** + * Returns the logical name of the attribute associated to the step. + * + * @return The attribute. + * + * @remarks Some steps don’t contain an attribute value. + */ + getAttribute(): string; + + /** + * Returns the name of the step. + * + * @return The name. + */ + getName(): string; + + /** + * Returns whether the step is required in the business process flow. + * + * @return true if required, false if not. + * + * @remarks Returns true if the step is marked as required in the Business Process Flow editor; otherwise, false. + * There is no connection between this value and the values you can change in the Xrm.Page.data.entity + * attribute RequiredLevel methods. + */ + isRequired(): boolean; + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Xrm.Page.Attribute | Xrm.Page.Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a string. + * + * @remarks You must use parseInt to convert this value to a number before you can use it to + * set the value of an OptionSetAttribute. + */ + value: string; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): string; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): string; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets required level. + * + * @param {"none"} requirementLevel Not required. + */ + setRequiredLevel( requirementLevel: "none" ): void; + + /** + * Sets required level. + * + * @param {"required"} requirementLevel Required. + */ + setRequiredLevel( requirementLevel: "required" ): void; + + /** + * Sets required level. + * + * @param {"recommended"} requirementLevel Recommended. + */ + setRequiredLevel( requirementLevel: "recommended" ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel( requirementLevel: string ): void; + + /** + * Sets submit mode. + * + * @param {"always"} submitMode Always submit this attribute. + */ + setSubmitMode( submitMode: "always" ): void; + + /** + * Sets submit mode. + * + * @param {"never"} submitMode Never submit this attribute. + */ + setSubmitMode( submitMode: "never" ): void; + + /** + * Sets submit mode. + * + * @param {"dirty"} submitMode Submit this attribute when changed. + */ + setSubmitMode( submitMode: "dirty" ): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode( submitMode: string ): void; + + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandclose"} saveMode Saves the record, and closes the form. + */ + save( saveMode: "saveandclose" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {"saveandnew"} saveMode Saves the record, and opens a blank form. + */ + save( saveMode: "saveandnew" ): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: string ): void; + + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Module for the Xrm.Page.data API. + */ + export module data + { + /** + * Interface for the Xrm.Page.data.process API. + */ + export interface ProcessManager + { + /** + * Returns a Process object representing the active process. + * + * @return current active process. + */ + getActiveProcess(): Process; + + /** + * Set a Process as the active process. + * + * @param {string} processId the Id of the process to make the active process. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveProcess( processId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Returns a Stage object representing the active stage. + * + * @return current active stage. + */ + getActiveStage(): Stage; + + /** + * Set a stage as the active stage. + * + * @param {string} stageId the Id of the stage to make the active stage. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveStage( stageId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Use this method to get a collection of stages currently in the active path with methods to interact with the + * stages displayed in the business process flow control. The active path represents stages currently rendered in + * the process control based on the branching rules and current data in the record. + * + * @return A collection of all completed stages, the currently active stage, and the predicted set of future stages + * based on satisfied conditions in the branching rule. This may be a subset of the stages returned with + * Xrm.Page.data.process.getActiveProcess because it will only include those stages which represent a valid + * transition from the current stage based on branching that has occurred in the process. + */ + getActivePath(): Collection.ItemCollection; + + /** + * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an + * entity. + * + * @param {Function} callbackFunction The callback function must accept a parameter + * that contains an object with dictionary + * properties where the name of the property is the + * Id of the business process flow and the value of + * the property is the name of the business process + * flow. + * + * The enabled processes are filtered according to + * the user’s privileges. The list of enabled + * processes is the same ones a user can see in the + * UI if they want to change the process manually. + */ + getEnabledProcesses( callbackFunction: ( enabledProcesses: ProcessDictionary ) => void ): void; + + /** + * Use this to add a function as an event handler for the OnStageChange event so that it will be called when the + * business process flow stage changes. + * + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event handler + * pipeline. The execution context is automatically set to be the first + * parameter passed to the event handler. + */ + addOnStageChange( handler: ContextSensitiveHandler ): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageSelected( handler: ContextSensitiveHandler ): void; + + /** + * Progresses to the next stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + moveNext( callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Moves to the previous stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + movePrevious( callbackFunction?: ProcessCallbackDelegate ): void; + } + + /** + * Called when process change methods have completed. + * + * @param {string} status The result of the process change operation. + * @remarks Values returned are: success (The operation succeeded.) + * crossEntity (The previous stage is for a different entity.) + * beginning (The active stage is the first stage of the active path.) + * invalid (The operation failed because the selected stage isn’t the same + * as the active stage.) + * unreachable (The stage exists on a different path.) + */ + export type ProcessCallbackDelegate = ( status: string ) => void; + + /** + * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. + */ + export type ProcessDictionary = { [index: string]: string }; + + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh. + * + * @return An Async.XrmPromise. + */ + export function refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + export function save(): Async.XrmPromise; + + /** + * The record context of the form. + */ + export var entity: Entity; + + /** + * The process API for Xrm.Page.data. + * + * @remarks This member may be undefined when Process Flows are not used by the current entity. + */ + export var process: ProcessManager; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + * kbsearch (CRM Online Only, use parature.d.ts) + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Gets the status of the time-of-day component of the Date control. + * + * @return true if the time is shown, otherwise false. + */ + getShowTime(): boolean; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: () => void ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Use this method to add event handlers to the GridControl's OnLoad event. + * + * @param {Function} handler The event handler. + */ + addOnLoad( handler: () => void ): void; + + /** + * This method returns context information about the GridControl. + * + * @return The context type. + */ + getContextType(): GridControlContext; + + /** + * Use this method to get the logical name of the entity data displayed in the grid. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Use this method to get access to the Grid available in the GridControl. + * + * @return The grid. + */ + getGrid(): ui.Grid; + + /** + * Use this method to get access to the ViewSelector available for the GridControl when it is configured to display views. + * + * @return The view selector. + */ + getViewSelector(): ui.ViewSelector; + + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + + /** + * Use this method to remove event handlers from the GridControl's OnLoad event. + * + * @param {Function} handler The handler. + */ + removeOnLoad( handler: () => void ): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): string; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): typeof ui; + + /** + * Sets display state of the tab. + * + * @param {"collapsed"} displayState Collapsed tab. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the tab. + * + * @param {"expanded"} displayState Expanded tab. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + } + + /** + * Module for Xrm.Page.ui API. + */ + export module ui + { + /** + * Interface for Xrm.Page.ui.process API + */ + export interface ProcessManager + { + /** + * Sets display state of the process flow control. + * + * @param {"collapsed"} displayState Collapsed process flow control. + */ + setDisplayState( displayState: "collapsed" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {"expanded"} displayState Expanded process flow control. + */ + setDisplayState( displayState: "expanded" ): void; + + /** + * Sets display state of the process flow control. + * + * @param {string} displayState Display state of the process flow control, as either "expanded" or "collapsed" + */ + setDisplayState( displayState: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for a grid. Use Grid methods to access information about data in the grid. Grid is returned by the + * GridControl.getGrid method. + */ + export interface Grid + { + /** + * Returns a collection of every GridRow in the Grid. + * + * @return The rows. + */ + getRows(): Collection.ItemCollection; + + /** + * Returns a collection of every selected GridRow in the Grid. + * + * @return The selected rows. + */ + getSelectedRows(): Collection.ItemCollection; + + /** + * Returns the total number of records in the Grid. + * + * @return The total record count. + */ + getTotalRecordCount(): number; + } + + /** + * Interface for a grid row. Use the GridRow.getData method to access the GridRowData. A collection of GridRow is + * returned by Grid.getRows and Grid.getSelectedRows methods. + */ + export interface GridRow + { + /** + * Returns the GridRowData for the GridRow. + * + * @return The data. + */ + getData(): GridRowData; + } + + /** + * Interface for grid row data. Use the GridRowData.getEntity method to access the GridEntity. GridRowData is + * returned by the GridRow.getData method. + */ + export interface GridRowData + { + /** + * Returns the GridEntity for the GridRowData. + * + * @return The entity. + */ + getEntity(): GridEntity; + } + + /** + * Interface for a grid entity. Use the GridEntity methods to access data about the specific records in the rows. + * GridEntity is returned by the GridRowData.getEntity method. + */ + export interface GridEntity + { + /** + * Returns the logical name for the record in the row. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns a LookupValue that references this record. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + + /** + * Returns the id for the record in the row. + * + * @return The identifier of the GridEntity, in GUID format. + * + * @remarks Example return: "{00000000-0000-0000-0000-000000000000}" + */ + getId(): string; + + /** + * Returns the primary attribute value for the record in the row. (Commonly the name.) + * + * @return The primary attribute value. + */ + getPrimaryAttributeValue(): string; + } + + /** + * Interface for the view selector. Use the ViewSelector methods to get or set information about the view selector + * of the grid control. + */ + export interface ViewSelector + { + /** + * Use this method to get a reference to the current view. + * + * @return The current view. + */ + getCurrentView(): ViewSelectorItem; + + /** + * Use this method to determine whether the view selector is visible. + * + * @return true if visible, false if not. + */ + isVisible(): boolean; + + /** + * Use this method to set the current view. + * + * @param {ViewSelectorItem} viewSelectorItem The view selector item. + */ + setCurrentView( viewSelectorItem: ViewSelectorItem ): void; + } + + /** + * Interface for a view selector item. This object contains data that identifies a view. Use this as a parameter to + * the ViewSelector.setCurrentView method. + */ + export interface ViewSelectorItem + { + /** + * Returns a LookupValue that references this view. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + } + + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + export function clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + export function close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + export function getFormType(): FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + export function refreshRibbon(): void; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"ERROR"} level An error message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "ERROR", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"WARNING"} level A warning message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "WARNING", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {"INFO"} level An informational message. + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, false if it fails. + */ + export function setFormNotification( message: string, level: "INFO", uniqueId: string ): boolean; + + /** + * Sets a form-level notification. + * + * @param {string} message The message. + * @param {string} level The level, as either "ERROR", "WARNING", or "INFO". + * @param {string} uniqueId A unique identifier for the message. + * + * @return true if it succeeds, otherwise false. + */ + export function setFormNotification( message: string, level: string, uniqueId: string ): boolean; + + export var process: ProcessManager; + + /** + * A reference to the collection of controls on the form. + */ + export var controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var formSelector: FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + export var navigation: Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + export var tabs: Collection.ItemCollection; + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + + /** + * A reference to the xRM application context. + */ + export var context: Context; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + export function getAttribute(): Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + export function getAttribute( attributeName: string ): Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + export function getAttribute( index: number ): Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + export function getAttribute( delegateFunction: Collection.MatchingDelegate ): Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + export function getControl(): Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + export function getControl( controlName: string ): Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + export function getControl( index: number ): Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + export function getControl( delegateFunction: Collection.MatchingDelegate ): Control[]; + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: string; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + export interface OpenParameters + { + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters extends OpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: string; + } + + /** + * Interface for window options. + */ + export interface WindowOptions + { + /** + * Direct the form to open in a new window. + */ + openInNewWindow: boolean; + } + + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + export function alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + export function confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + export function isActivityType( entityType: string ): boolean; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. + */ + export function openEntityForm( name: string, id?: string, parameters?: FormOpenParameters, windowOptions?: WindowOptions ): void; + + /** + * Opens quick create. + * + * @param {Function} callback The function that will be called when a record is created. This + * function is passed a LookupValue object as a parameter. + * @param {string} entityLogicalName The logical name of the entity to create. + * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values + * based on mapped attribute values. + * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string + * parameters to the form. Invalid query string parameters will cause an + * error. + */ + export function openQuickCreate( callback: ( recordReference: Page.LookupValue ) => void, + entityLogicalName: string, + createFromEntity?: Page.LookupValue, + parameters?: OpenParameters ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + export function openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } +} diff --git a/xss-filters/xss-filters-tests.ts b/xss-filters/xss-filters-tests.ts new file mode 100644 index 0000000000..49a566efc5 --- /dev/null +++ b/xss-filters/xss-filters-tests.ts @@ -0,0 +1,37 @@ +/// + +import xssFilters = require('xss-filters'); + +var s = ''; + +xssFilters.inHTMLComment(s); +xssFilters.inHTMLData(s); +xssFilters.inDoubleQuotedAttr(s); +xssFilters.inSingleQuotedAttr(s); +xssFilters.inUnQuotedAttr(s); +xssFilters.uriInHTMLComment(s); +xssFilters.uriInHTMLData(s); +xssFilters.uriInDoubleQuotedAttr(s); +xssFilters.uriInSingleQuotedAttr(s); +xssFilters.uriInUnQuotedAttr(s); +xssFilters.uriPathInHTMLComment(s); +xssFilters.uriPathInHTMLData(s); +xssFilters.uriPathInDoubleQuotedAttr(s); +xssFilters.uriPathInSingleQuotedAttr(s); +xssFilters.uriPathInUnQuotedAttr(s); +xssFilters.uriQueryInHTMLComment(s); +xssFilters.uriQueryInHTMLData(s); +xssFilters.uriQueryInDoubleQuotedAttr(s); +xssFilters.uriQueryInSingleQuotedAttr(s); +xssFilters.uriQueryInUnQuotedAttr(s); +xssFilters.uriComponentInHTMLComment(s); +xssFilters.uriComponentInHTMLData(s); +xssFilters.uriComponentInDoubleQuotedAttr(s); +xssFilters.uriComponentInSingleQuotedAttr(s); +xssFilters.uriComponentInUnQuotedAttr(s); +xssFilters.uriFragmentInHTMLComment(s); +xssFilters.uriFragmentInHTMLData(s); +xssFilters.uriFragmentInDoubleQuotedAttr(s); +xssFilters.uriFragmentInSingleQuotedAttr(s); +xssFilters.uriFragmentInUnQuotedAttr(s); + diff --git a/xss-filters/xss-filters.d.ts b/xss-filters/xss-filters.d.ts new file mode 100644 index 0000000000..3ac33d4f3b --- /dev/null +++ b/xss-filters/xss-filters.d.ts @@ -0,0 +1,43 @@ +// Type definitions for Yahoo XSS Filters +// Project: https://github.com/yahoo/xss-filters +// Definitions by: Dave Taylor +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface XSSFilters { + inHTMLComment(s:string):string; + inHTMLData(s:string):string; + inDoubleQuotedAttr(s:string):string; + inSingleQuotedAttr(s:string):string; + inUnQuotedAttr(s:string):string; + uriInHTMLComment(s:string):string; + uriInHTMLData(s:string):string; + uriInDoubleQuotedAttr(s:string):string; + uriInSingleQuotedAttr(s:string):string; + uriInUnQuotedAttr(s:string):string; + uriPathInHTMLComment(s:string):string; + uriPathInHTMLData(s:string):string; + uriPathInDoubleQuotedAttr(s:string):string; + uriPathInSingleQuotedAttr(s:string):string; + uriPathInUnQuotedAttr(s:string):string; + uriQueryInHTMLComment(s:string):string; + uriQueryInHTMLData(s:string):string; + uriQueryInDoubleQuotedAttr(s:string):string; + uriQueryInSingleQuotedAttr(s:string):string; + uriQueryInUnQuotedAttr(s:string):string; + uriComponentInHTMLComment(s:string):string; + uriComponentInHTMLData(s:string):string; + uriComponentInDoubleQuotedAttr(s:string):string; + uriComponentInSingleQuotedAttr(s:string):string; + uriComponentInUnQuotedAttr(s:string):string; + uriFragmentInHTMLComment(s:string):string; + uriFragmentInHTMLData(s:string):string; + uriFragmentInDoubleQuotedAttr(s:string):string; + uriFragmentInSingleQuotedAttr(s:string):string; + uriFragmentInUnQuotedAttr(s:string):string; +} + +declare var xssFilters:XSSFilters; + +declare module 'xss-filters' { + export = xssFilters; +} diff --git a/yamljs/yamljs-tests.ts b/yamljs/yamljs-tests.ts new file mode 100644 index 0000000000..9780c504d4 --- /dev/null +++ b/yamljs/yamljs-tests.ts @@ -0,0 +1,13 @@ +/// + +import yamljs = require('yamljs'); + +yamljs.load('yaml-testfile.yml'); + +yamljs.parse('this_is_no_ymlstring'); + +yamljs.stringify({ a : 'val', b : { ba : 123, bb : 'nothing' }}); + +yamljs.stringify({ a : 'val', b : { ba : 123, bb : 'nothing' }}, 1); + +yamljs.stringify({ a : 'val', b : { ba : 123, bb : 'nothing' }}, 1, 2); \ No newline at end of file diff --git a/yamljs/yamljs.d.ts b/yamljs/yamljs.d.ts new file mode 100644 index 0000000000..65d2fd9239 --- /dev/null +++ b/yamljs/yamljs.d.ts @@ -0,0 +1,14 @@ +// Type definitions for yamljs 0.2.1 +// Project: https://github.com/jeremyfa/yaml.js +// Definitions by: Tim Jonischkat +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "yamljs" { + + export function load(path : string) : any; + + export function stringify(nativeObject : any, inline? : number, spaces? : number) : string; + + export function parse(yamlString : string) : any; + +} \ No newline at end of file diff --git a/youtube/youtube.d.ts b/youtube/youtube.d.ts index cfdba0efb0..85f96b22f8 100644 --- a/youtube/youtube.d.ts +++ b/youtube/youtube.d.ts @@ -146,7 +146,7 @@ declare module YT { getPlaylistIndex(): number; // Event Listener - addEventListener(event: string, listener: string): void; + addEventListener(event: string, handler: EventHandler): void; } export enum PlayerState {