diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e4d96e5b4..650078833 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -92,6 +92,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](chrome/chrome.d.ts) [Chrome extension development](http://developer.chrome.com/extensions) by [Matthew Kimber](https://github.com/matthewkimber), [otiai10](https://github.com/otiai10) * [:link:](chrome/chrome-app.d.ts) [Chrome packaged application development](http://developer.chrome.com/apps) by [Adam Lay](https://github.com/AdamLay), [MIZUNE Pine](https://github.com/pine613), [MIZUSHIMA Junki](https://github.com/mzsm) * [:link:](ckeditor/ckeditor.d.ts) [CKEditor](http://ckeditor.com) by [Ondrej Sevcik](https://github.com/ondrejsevcik) +* [:link:](cli-color/cli-color.d.ts) [cli-color](https://github.com/medikoo/cli-color) by [Joel Spadin](https://github.com/ChaosinaCan) * [:link:](clone/clone.d.ts) [clone](https://github.com/pvorb/node-clone) by [Kieran Simpson](https://github.com/kierans/DefinitelyTyped) * [:link:](codemirror/codemirror.d.ts) [CodeMirror](https://github.com/marijnh/CodeMirror) by [mihailik](https://github.com/mihailik) * [:link:](colors/colors.d.ts) [Colors.js 0.6.0-1](https://github.com/Marak/colors.js) by [Bart van der Schoor](https://github.com/Bartvds) @@ -172,7 +173,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](findup-sync/findup-sync.d.ts) [findup-sync](https://github.com/cowboy/node-findup-sync) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](fingerprintjs/fingerprint.d.ts) [fingerprintjs](https://github.com/Valve/fingerprintjs) by [Shunsuke Ohtani](https://github.com/zaneli) * [:link:](state-machine/state-machine.d.ts) [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) by [Boris Yankov](https://github.com/borisyankov), [Maarten Docter](https://github.com/mdocter), [William Sears](https://github.com/MrBigDog2U) -* [:link:](firebase/firebase.d.ts) [Firebase API](https://www.firebase.com/docs/javascript/firebase) by [Vincent Botone](https://github.com/vbortone) +* [:link:](firebase/firebase.d.ts) [Firebase API](https://www.firebase.com/docs/javascript/firebase) by [Vincent Botone](https://github.com/vbortone), [Shin1 Kashimura](https://github.com/in-async) * [:link:](firebase/firebase-simplelogin.d.ts) [Firebase Simple Login](https://www.firebase.com/docs/security/simple-login-overview.html) by [Wilker Lucio](http://github.com/wilkerlucio) * [:link:](flexSlider/flexSlider.d.ts) [FlexSlider 2 jquery plugin](https://github.com/woothemes/FlexSlider) by [Diullei Gomes](https://github.com/diullei) * [:link:](flight/flight.d.ts) [Flight](http://flightjs.github.com/flight) by [Jonathan Hedrén](https://github.com/jonathanhedren) @@ -197,6 +198,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](glob/glob.d.ts) [Glob](https://github.com/isaacs/node-glob) by [vvakame](https://github.com/vvakame) * [:link:](glob-stream/glob-stream.d.ts) [glob-stream](http://github.com/wearefractal/glob-stream) by [Bart van der Schoor](https://github.com/Bartvds) * [:link:](globalize/globalize.d.ts) [Globalize](https://github.com/jquery/globalize) by [Boris Yankov](https://github.com/borisyankov) +* [:link:](gm/gm.d.ts) [gm](https://github.com/aheckmann/gm) by [Joel Spadin](https://github.com/ChaosinaCan) * [:link:](goJS/goJS.d.ts) [GoJS](http://gojs.net) by [Barbara Duckworth](https://github.com/barbara42) * [:link:](google.analytics/ga.d.ts) [Google Analytics (Classic and Universal)](https://developers.google.com/analytics/devguides/collection/gajs) by [Ronnie Haakon Hegelund](http://ronniehegelund.blogspot.dk), [Pat Kujawa](http://patkujawa.com) * [:link:](gapi/gapi.d.ts) [Google API Client](https://code.google.com/p/google-api-javascript-client) by [Frank M](https://github.com/sgtfrankieboy) @@ -216,7 +218,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](gruntjs/gruntjs.d.ts) [Grunt 0.4.x](http://gruntjs.com) by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) * [:link:](gulp/gulp.d.ts) [Gulp v3.8.x](http://gulpjs.com) by [Drew Noakes](https://drewnoakes.com) * [:link:](gulp-util/gulp-util.d.ts) [gulp-util v3.0.x](https://github.com/gulpjs/gulp-util) by [jedmao](https://github.com/jedmao) -* [:link:](hammerjs/hammerjs.d.ts) [Hammer.js](http://eightmedia.github.com/hammer.js) by [Boris Yankov](https://github.com/borisyankov), [Drew Noakes](https://drewnoakes.com) +* [:link:](hammerjs/hammerjs.d.ts) [Hammer.js](http://hammerjs.github.io) by [Philip Bulley](https://github.com/milkisevil) * [:link:](handlebars/handlebars.d.ts) [Handlebars](http://handlebarsjs.com) by [Boris Yankov](https://github.com/borisyankov) * [:link:](hapi/hapi.d.ts) [hapi](http://github.com/spumko/hapi) by [Hakubo](http://github.com/hakubo) * [:link:](hashmap/hashmap.d.ts) [HashMap](https://github.com/flesler/hashmap) by [Rafał Wrzeszcz](http://wrzasq.pl) @@ -228,6 +230,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](highlightjs/highlightjs.d.ts) [highlight.js](https://github.com/isagalaev/highlight.js) by [Niklas Mollenhauer](https://github.com/nikeee), [Jeremy Hull](https://github.com/sourrust) * [:link:](history/history.d.ts) [History.js](https://github.com/browserstate/history.js) by [Boris Yankov](https://github.com/borisyankov), [Gidon Junge](https://github.com/gjunge) * [:link:](howlerjs/howler.d.ts) [howler.js](https://github.com/goldfire/howler.js) by [Pedro Casaubon](https://github.com/xperiments) +* [:link:](touch-events/touch-events.d.ts) [HTML Touch Events](http://www.w3.org/TR/touch-events) by [Kevin Barabash](https://github.com/kevinb7) * [:link:](html2canvas/html2canvas.d.ts) [html2canvas.js](https://github.com/niklasvh/html2canvas) by [Richard Hepburn](https://github.com/rwhepburn) * [:link:](htmlparser2/htmlparser2.d.ts) [htmlparser2 v3.7.x](https://github.com/fb55/htmlparser2) by [James Roland Cabresos](https://github.com/staticfunction) * [:link:](http-string-parser/http-string-parser.d.ts) [http-string-parser](https://github.com/apiaryio/http-string-parser) by [MIZUNE Pine](https://github.com/pine613) @@ -373,10 +376,11 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](libxmljs/libxmljs.d.ts) [Libxmljs](https://github.com/polotek/libxmljs) by [François de Campredon](https://github.com/fdecampredon) * [:link:](dustjs-linkedin/dustjs-linkedin.d.ts) [linkedin dustjs](https://github.com/linkedin/dustjs) by [Marcelo Dezem](http://github.com/mdezem) * [:link:](linq/linq.jquery.d.ts) [linq.jquery (from linq.js)](http://linqjs.codeplex.com) by [neuecc](http://www.codeplex.com/site/users/view/neuecc) -* [:link:](linq/linq.d.ts) [linq.js](http://linqjs.codeplex.com) by [Marcin Najder](https://github.com/marcinnajder) +* [:link:](linq/linq.d.ts) [linq.js](http://linqjs.codeplex.com) by [Marcin Najder](https://github.com/marcinnajder), [Sebastiaan Dammann](https://github.com/Sebazzz) * [:link:](jquery.livestampjs/jquery.livestampjs.d.ts) [Livestamp.js](http://mattbradley.github.com/livestampjs) by [Vincent Bortone](https://github.com/vbortone) * [:link:](lodash/lodash.d.ts) [Lo-Dash](http://lodash.com) by [Brian Zengel](https://github.com/bczengel) * [:link:](lockfile/lockfile.d.ts) [lockfile](https://github.com/isaacs/lockfile) by [Bart van der Schoor](https://github.com/Bartvds) +* [:link:](log4javascript/log4javascript.d.ts) [log4javascript](http://log4javascript.org) by [Markus Wagner](https://github.com/Ritzlgrmft) * [:link:](logg/logg.d.ts) [logg](https://github.com/dpup/node-logg) by [Bret Little](https://github.com/blittle) * [:link:](long/long.d.ts) [Long.js](https://github.com/dcodeIO/Long.js) by [Toshihide Hara](https://github.com/kerug) * [:link:](lru-cache/lru-cache.d.ts) [lru-cache](https://github.com/isaacs/node-lru-cache) by [Bart van der Schoor](https://github.com/Bartvds) @@ -428,6 +432,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](ngprogress-lite/ngprogress-lite.d.ts) [ngprogress-lite](https://github.com/voronianski/ngprogress-lite) by [Luke Forder](https://github.com/LukeForder) * [:link:](noble/noble.d.ts) [noble](https://github.com/sandeepmistry/noble) by [Seon-Wook Park](https://github.com/swook) * [:link:](nock/nock.d.ts) [nock](https://github.com/pgte/nock) by [bonnici](https://github.com/bonnici) +* [:link:](node-imap/imap.d.ts) [node imap](https://github.com/mscdex/node-imap) by [Steve Fenton](https://github.com/Steve-Fenton) * [:link:](bunyan/bunyan.d.ts) [node-bunyan](https://github.com/trentm/node-bunyan) by [Alex Mikhalev](https://github.com/amikhalev) * [:link:](bunyan-logentries/bunyan-logentries.d.ts) [node-bunyan-logentries](https://github.com/nemtsov/node-bunyan-logentries) by [Aymeric Beaumet](http://aymericbeaumet.me) * [:link:](node-ffi/node-ffi.d.ts) [node-ffi](https://github.com/rbranson/node-ffi) by [Paul Loyd](https://github.com/loyd) @@ -481,6 +486,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [: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) * [:link:](platform/platform.d.ts) [Platform](https://github.com/bestiejs/platform.js) by [Jake Hickman](https://github.com/JakeH) +* [:link:](playerframework/playerFramework.d.ts) [Player Framework (MMPPF)](https://playerframework.codeplex.com) by [Ricardo Sabino](https://github.com/ricardosabino) * [:link:](podcast/podcast.d.ts) [podcast](http://github.com/maxnowack/node-podcast) by [Niklas Mollenhauer](https://github.com/nikeee) * [: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) @@ -520,6 +526,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](rtree/rtree.d.ts) [rtree](https://github.com/leaflet-extras/RTree) by [Omede Firouz](https://github.com/oefirouz) * [:link:](rx/rx.d.ts) [RxJS](http://rx.codeplex.com) by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek) * [:link:](rx/rx.aggregates.d.ts) [RxJS-Aggregates](http://rx.codeplex.com) by [Carl de Billy](http://carl.debilly.net), [Igor Oleinikov](https://github.com/Igorbek) +* [:link:](rx/rx.all.d.ts) [RxJS-All](http://rx.codeplex.com) by [Carl de Billy](http://carl.debilly.net), [Igor Oleinikov](https://github.com/Igorbek) * [:link:](rx/rx.async.d.ts) [RxJS-Async](http://rx.codeplex.com) by [zoetrope](https://github.com/zoetrope), [Igor Oleinikov](https://github.com/Igorbek) * [:link:](rx/rx.backpressure.d.ts) [RxJS-BackPressure](http://rx.codeplex.com) by [Igor Oleinikov](https://github.com/Igorbek) * [:link:](rx/rx.binding.d.ts) [RxJS-Binding](http://rx.codeplex.com) by [Carl de Billy](http://carl.debilly.net), [Igor Oleinikov](https://github.com/Igorbek) @@ -552,6 +559,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [: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) +* [:link:](snapsvg/snapsvg.d.ts) [Snap-SVG](https://github.com/adobe-webplatform/Snap.svg) by [Lars Klein](https://github.com/lhk) * [:link:](socket.io/socket.io.d.ts) [socket.io](http://socket.io) by [PROGRE](https://github.com/progre) * [:link:](socket.io-client/socket.io-client.d.ts) [socket.io-client](http://socket.io) by [PROGRE](https://github.com/progre) * [:link:](sockjs/sockjs.d.ts) [SockJS 0.3.x](https://github.com/sockjs/sockjs-client) by [Emil Ivanov](https://github.com/vladev) @@ -642,6 +650,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](jquery.watermark/jquery.watermark.d.ts) [Watermark plugin for jQuery](http://jquery-watermark.googlecode.com) by [Anwar Javed](https://github.com/anwarjaved) * [:link:](webaudioapi/waa.d.ts) [Web Audio API](http://www.w3.org/TR/webaudio) by [Baruch Berger](https://github.com/bbss), [Kon](http://phyzkit.net) * [:link:](webaudioapi/waa-nightly.d.ts) [Web Audio API (nightly)](http://www.w3.org/TR/2012/WD-webaudio-20120802) by [Baruch Berger](https://github.com/bbss) +* [:link:](webmidi/webmidi.d.ts) [Web MIDI API](http://www.w3.org/TR/webmidi) by [Toshiya Nakakura](https://github.com/nakakura) * [:link:](devextreme/dx.webappjs.d.ts) [WebAppJS](http://js.devexpress.com/WebDevelopment) by [DevExpress Inc.](http://devexpress.com) * [:link:](webcrypto/WebCrypto.d.ts) [WebCrypto](http://www.w3.org/TR/WebCryptoAPI) by [Lucas Dixon](https://github.com/iislucas) * [:link:](webrtc/MediaStream.d.ts) [WebRTC](http://dev.w3.org/2011/webrtc) by [Ken Smith](https://github.com/smithkl42) diff --git a/angular-ui/angular-ui-router-tests.ts b/angular-ui/angular-ui-router-tests.ts index 971a47cd2..8b9027564 100644 --- a/angular-ui/angular-ui-router-tests.ts +++ b/angular-ui/angular-ui-router-tests.ts @@ -17,7 +17,7 @@ myApp.config(( var concat: ng.ui.IUrlMatcher = matcher.concat('/test'); var str: string = matcher.format({ id:'bob', q:'yes' }); var arr: string[] = matcher.parameters(); - + $urlRouterProvider .when('/test', '/list') .when('/test', '/list') @@ -34,7 +34,11 @@ myApp.config(( $stateProvider .state('state1', { url: "/state1", - templateUrl: "partials/state1.html" + templateUrl: "partials/state1.html", + params: { + param1: "defaultValue", + param2: undefined + } }) .state('state1.list', { url: "/list", @@ -135,7 +139,7 @@ myApp.service("urlLocatorTest", UrlLocatorTestService); module UiViewScrollProviderTests { var app = angular.module("uiViewScrollProviderTests", ["ui.router"]); - + app.config(['$uiViewScrollProvider', function($uiViewScrollProvider: ng.ui.IUiViewScrollProvider) { // This prevents unwanted scrolling to the active nested state view. // Use this when you have nested states, but you don't want the browser to scroll down the page diff --git a/angular-ui/angular-ui-router.d.ts b/angular-ui/angular-ui-router.d.ts index eb9296dbd..54f3c4de2 100644 --- a/angular-ui/angular-ui-router.d.ts +++ b/angular-ui/angular-ui-router.d.ts @@ -17,7 +17,7 @@ declare module ng.ui { controllerProvider?: any; resolve?: {}; url?: string; - params?: any[]; + params?: any; views?: {}; abstract?: boolean; onEnter?: any; @@ -108,10 +108,10 @@ declare module ng.ui { */ sync(): void; } - + interface IUiViewScrollProvider { /* - * Reverts back to using the core $anchorScroll service for scrolling + * Reverts back to using the core $anchorScroll service for scrolling * based on the url anchor. */ useAnchorScroll(): void; diff --git a/angularfire/angularfire.d.ts b/angularfire/angularfire.d.ts index 0bebb23c5..e4129e4ba 100644 --- a/angularfire/angularfire.d.ts +++ b/angularfire/angularfire.d.ts @@ -20,8 +20,8 @@ interface AngularFire { $remove(key?: string): ng.IPromise; $update(key: string, data: Object): ng.IPromise; $update(data: any): ng.IPromise; - $transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; - $transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; + $transaction(updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; + $transaction(key:string, updateFn: (currentData: any) => any, applyLocally?: boolean): ng.IPromise; } interface AngularFireObject extends AngularFireSimpleObject { diff --git a/async/async.d.ts b/async/async.d.ts index 1efa5046b..5f558c384 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -3,12 +3,14 @@ // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface AsyncMultipleResultsCallback { (err: Error, results: T[]): any; } -interface AsyncSingleResultCallback { (err: Error, result: T): void; } -interface AsyncTimesCallback { (n: number, callback: AsyncMultipleResultsCallback): void; } +interface ErrorCallback { (err?: Error): void; } +interface AsyncResultsCallback { (err: Error, results: T[]): void; } +interface AsyncResultCallback { (err: Error, result: T): void; } +interface AsyncTimesCallback { (n: number, callback: AsyncResultsCallback): void; } -interface AsyncIterator { (item: T, callback: AsyncSingleResultCallback): void; } -interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncSingleResultCallback): void; } +interface AsyncIterator { (item: T, callback: ErrorCallback): void; } +interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } +interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } interface AsyncWorker { (task: T, callback: Function): void; } @@ -17,10 +19,10 @@ interface AsyncQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T, callback?: AsyncMultipleResultsCallback): void; - push(task: T[], callback?: AsyncMultipleResultsCallback): void; - unshift(task: T, callback?: AsyncMultipleResultsCallback): void; - unshift(task: T[], callback?: AsyncMultipleResultsCallback): void; + push(task: T, callback?: AsyncResultsCallback): void; + push(task: T[], callback?: AsyncResultsCallback): void; + unshift(task: T, callback?: AsyncResultsCallback): void; + unshift(task: T[], callback?: AsyncResultsCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -36,8 +38,8 @@ interface AsyncPriorityQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T, priority: number, callback?: AsyncMultipleResultsCallback): void; - push(task: T[], priority: number, callback?: AsyncMultipleResultsCallback): void; + push(task: T, priority: number, callback?: AsyncResultsCallback): void; + push(task: T[], priority: number, callback?: AsyncResultsCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -51,47 +53,48 @@ interface AsyncPriorityQueue { interface Async { // Collections - each(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - eachSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): void; - map(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - mapSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - filter(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - select(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - filterSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - selectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - reject(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - rejectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; - inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; - foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; - reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; - foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncSingleResultCallback): any; - detect(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - detectSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - sortBy(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - some(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - any(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - every(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any): any; - all(arr: T[], iterator: AsyncIterator, callback: (result: boolean) => any): any; - concat(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; - concatSeries(arr: T[], iterator: AsyncIterator, callback: AsyncMultipleResultsCallback): any; + each(arr: T[], iterator: AsyncIterator, callback: ErrorCallback): void; + eachSeries(arr: T[], iterator: AsyncIterator, callback: ErrorCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: ErrorCallback): void; + map(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + mapSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + filter(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; + select(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; + filterSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; + selectSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; + reject(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; + rejectSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + detect(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + detectSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + sortBy(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + some(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + any(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + every(arr: T[], iterator: AsyncResultIterator, callback: (result: boolean) => any): any; + all(arr: T[], iterator: AsyncResultIterator, callback: (result: boolean) => any): any; + concat(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; + concatSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultsCallback): any; // Control Flow - series(tasks: T[], callback?: AsyncMultipleResultsCallback): void; - series(tasks: T, callback?: AsyncMultipleResultsCallback): void; - parallel(tasks: T[], callback?: AsyncMultipleResultsCallback): void; - parallel(tasks: T, callback?: AsyncMultipleResultsCallback): void; - parallelLimit(tasks: T[], limit: number, callback?: AsyncMultipleResultsCallback): void; - parallelLimit(tasks: T, limit: number, callback?: AsyncMultipleResultsCallback): void; + series(tasks: T[], callback?: AsyncResultsCallback): void; + series(tasks: T, callback?: AsyncResultsCallback): void; + parallel(tasks: T[], callback?: AsyncResultsCallback): void; + parallel(tasks: T, callback?: AsyncResultsCallback): void; + parallelLimit(tasks: T[], limit: number, callback?: AsyncResultsCallback): void; + parallelLimit(tasks: T, limit: number, callback?: AsyncResultsCallback): void; whilst(test: Function, fn: Function, callback: Function): void; until(test: Function, fn: Function, callback: Function): void; - waterfall(tasks: T[], callback?: AsyncMultipleResultsCallback): void; - waterfall(tasks: T, callback?: AsyncMultipleResultsCallback): void; + waterfall(tasks: T[], callback?: AsyncResultsCallback): void; + waterfall(tasks: T, callback?: AsyncResultsCallback): void; queue(worker: AsyncWorker, concurrency: number): AsyncQueue; priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; - // auto(tasks: any[], callback?: AsyncMultipleResultsCallback): void; - auto(tasks: any, callback?: AsyncMultipleResultsCallback): void; + // auto(tasks: any[], callback?: AsyncResultsCallback): void; + auto(tasks: any, callback?: AsyncResultsCallback): void; iterator(tasks: Function[]): Function; apply(fn: Function, ...arguments: any[]): void; nextTick(callback: Function): void; diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 5f8b3c3ac..3a500bbbb 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -18,7 +18,81 @@ declare module "aws-sdk" { accessKeyId: string; } - export interface ClientConfig { + export interface Logger { + write?: (chunk: any, encoding?: string, callback?: () => void) => void; + log?: (...messages: any[]) => void; + } + + export interface HttpOptions { + proxy?: string; + agent?: any; + timeout?: number; + xhrAsync?: boolean; + xhrWithCredentials?: boolean; + } + + export interface Services { + autoscaling?: any; + cloudformation?: any; + cloudfront?: any; + cloudsearch?: any; + cloudsearchdomain?: any; + cloudtrail?: any; + cloudwatch?: any; + cloudwatchlogs?: any; + cognitoidentity?: any; + cognitosync?: any; + datapipeline?: any; + directconnect?: any; + dynamodb?: any; + ec2?: any; + elasticache?: any; + elasticbeanstalk?: any; + elastictranscoder?: any; + elb?: any; + emr?: any; + glacier?: any; + httpOptions?: HttpOptions; + iam?: any; + importexport?: any; + kinesis?: any; + opsworks?: any; + rds?: any; + redshift?: any; + route53?: any; + route53domains?: any; + s3?: any; + ses?: any; + simpledb?: any; + sns?: any; + sqs?: any; + storagegateway?: any; + sts?: any; + support?: any; + swf?: any; + } + + export interface ClientConfigPartial extends Services { + credentials?: Credentials; + region?: string; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + logger?: Logger; + maxRedirects?: number; + maxRetries?: number; + paramValidation?: boolean; + s3ForcePathStyle?: boolean; + apiVersion?: any; + apiVersions?: Services; + signatureVersion?: string; + sslEnabled?: boolean; + systemClockOffset?: number; + } + + export interface ClientConfig extends ClientConfigPartial { + update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; + getCredentials?: (callback: (err?: any) => void) => void ; + loadFromPath?: (path: string) => void; credentials: Credentials; region: string; } diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 270b949aa..8e2637604 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -241,7 +241,7 @@ declare module Backbone { last(): TModel; last(n: number): TModel[]; lastIndexOf(element: TModel, fromIndex?: number): number; - map(iterator: (element: TModel, index: number, context?: any) => any[], context?: any): any[]; + map(iterator: (element: TModel, index: number, context?: any) => any, context?: any): any[]; max(iterator?: (element: TModel, index: number) => any, context?: any): TModel; min(iterator?: (element: TModel, index: number) => any, context?: any): TModel; reduce(iterator: (memo: any, element: TModel, index: number) => any, initialMemo: any, context?: any): any; @@ -279,6 +279,7 @@ declare module Backbone { constructor(options?: RouterOptions); initialize(options?: RouterOptions): void; route(route: string, name: string, callback?: Function): Router; + route(route: RegExp, name: string, callback?: Function): Router; navigate(fragment: string, options?: NavigateOptions): Router; navigate(fragment: string, trigger?: boolean): Router; diff --git a/cli-color/cli-color-tests.ts b/cli-color/cli-color-tests.ts new file mode 100644 index 000000000..627377b47 --- /dev/null +++ b/cli-color/cli-color-tests.ts @@ -0,0 +1,55 @@ +/// +/// + +import clc = require('cli-color'); +import ansiTrim = require('cli-color/trim'); +import setupThrobber = require('cli-color/throbber'); + +var text: string; +var color: number; +var x: number; +var y: number; +var n: number; +var period: number; + +// Test cli-color +text = clc('foo'); +text = clc('foo', 42, { toString: () => 'bar' }); + +text = clc.bold.italic.underline.blink.inverse.strike(text); +text = clc.black.red.green.yellow.blue.magenta.cyan.white(text); +text = clc.bgBlack.bgRed.bgGreen.bgYellow.bgBlack.bgMagenta.bgCyan.bgWhite(text); +text = clc.blackBright.redBright.greenBright.yellowBright.blueBright.magentaBright.cyanBright.whiteBright(text); +text = clc.bgBlackBright.bgRedBright.bgGreenBright.bgYellowBright.bgBlueBright.bgMagentaBright.bgCyanBright.bgWhiteBright(text); +text = clc.xterm(color).bgXterm(color)(text); + +text = clc.bold.red.bgGreen.yellowBright.bgBlueBright.xterm(color)(text, text, text); + +text = clc.move(x, y); +text = clc.moveTo(x, y); +text = clc.bol(); +text = clc.bol(n); +text = clc.bol(n, true); +text = clc.up(n); +text = clc.down(n); +text = clc.left(n); +text = clc.right(n); +text = clc.beep; +text = clc.reset; + +var width: number = clc.width; +var height: number = clc.height; +var support: boolean = clc.xtermSupported; + +// Test cli-color/trim +text = ansiTrim(clc.red(text)); + +// Test cli-color/throbber +var throbber: setupThrobber.Throbber; + +throbber = setupThrobber(process.stdout.write.bind(process.stdout), period); +throbber = setupThrobber(process.stdout.write.bind(process.stdout), period, clc.red); + +throbber.start(); +throbber.stop(); +throbber.restart(); diff --git a/cli-color/cli-color.d.ts b/cli-color/cli-color.d.ts new file mode 100644 index 000000000..5764a646c --- /dev/null +++ b/cli-color/cli-color.d.ts @@ -0,0 +1,96 @@ +// Type definitions for cli-color 0.3.2 +// Project: https://github.com/medikoo/cli-color +// Definitions by: Joel Spadin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "cli-color" { + module m { + export interface Format { + (...text: any[]): string; + + bold: Format; + italic: Format; + underline: Format; + blink: Format; + inverse: Format; + strike: Format; + + black: Format; + red: Format; + green: Format; + yellow: Format; + blue: Format; + magenta: Format; + cyan: Format; + white: Format; + + bgBlack: Format; + bgRed: Format; + bgGreen: Format; + bgYellow: Format; + bgBlue: Format; + bgMagenta: Format; + bgCyan: Format; + bgWhite: Format; + + blackBright: Format; + redBright: Format; + greenBright: Format; + yellowBright: Format; + blueBright: Format; + magentaBright: Format; + cyanBright: Format; + whiteBright: Format; + + bgBlackBright: Format; + bgRedBright: Format; + bgGreenBright: Format; + bgYellowBright: Format; + bgBlueBright: Format; + bgMagentaBright: Format; + bgCyanBright: Format; + bgWhiteBright: Format; + + xterm(color: number): Format; + bgXterm(color: number): Format; + + move(x: number, y: number): string; + moveTo(x: number, y: number): string; + bol(n?: number, erase?: boolean): string; + up(n: number): string; + down(n: number): string; + left(n: number): string; + right(n: number): string; + + beep: string; + reset: string; + + width: number; + height: number; + xtermSupported: boolean; + } + } + + var m: m.Format; + export = m; +} + +declare module "cli-color/trim" { + function ansiTrim(str: string): string; + export = ansiTrim; +} + +declare module "cli-color/throbber" { + import clc = require('cli-color'); + + module setupThrobber { + export interface Throbber { + start(): void; + stop(): void; + restart(): void; + } + } + + function setupThrobber(write: (str: string) => any, period: number, format?: clc.Format): setupThrobber.Throbber; + export = setupThrobber; +} diff --git a/colors/colors-tests.ts b/colors/colors-tests.ts index bf83f6005..a7f595fdf 100644 --- a/colors/colors-tests.ts +++ b/colors/colors-tests.ts @@ -1,5 +1,18 @@ /// +import colors = require("colors"); + var test:string = 'test'; var arr:string[] = ['color', 'odd'.italic.zebra, 'radical'.bold.rainbow, test.underline + 'super'.green]; + +colors.black("abc").trim(); +colors.red("abc").trim(); +colors.green("abc").trim(); +colors.yellow("abc").trim(); +colors.blue("abc").trim(); +colors.magenta("abc").trim(); +colors.cyan("abc").trim(); +colors.white("abc").trim(); +colors.gray("abc").trim(); +colors.grey("abc").trim(); diff --git a/colors/colors.d.ts b/colors/colors.d.ts index e6056b354..8332ac5bb 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -5,6 +5,17 @@ declare module "colors" { export function setTheme(theme:any):any; + + export function black(text: string): string; + export function red(text: string): string; + export function green(text: string): string; + export function yellow(text: string): string; + export function blue(text: string): string; + export function magenta(text: string): string; + export function cyan(text: string): string; + export function white(text: string): string; + export function gray(text: string): string; + export function grey(text: string): string; } interface String { diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 66a6e4d23..2f439a76f 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -1162,7 +1162,7 @@ declare module D3 { /** * If separation is specified, uses the specified function to compute separation between neighboring nodes. If separation is not specified, returns the current separation function */ - seperation: { + separation: { /** * Gets the current separation function */ @@ -1170,7 +1170,7 @@ declare module D3 { /** * Sets the specified function to compute separation between neighboring nodes */ - (seperation: (a: GraphNode, b: GraphNode) => number): TreeLayout; + (separation: (a: GraphNode, b: GraphNode) => number): TreeLayout; }; /** * Gets or sets the available layout size @@ -1382,9 +1382,9 @@ declare module D3 { } nodes(root: GraphNode): GraphNode[]; links(nodes: GraphNode[]): GraphLink[]; - seperation: { + separation: { (): (a: GraphNode, b: GraphNode) => number; - (seperation: (a: GraphNode, b: GraphNode) => number): ClusterLayout; + (separation: (a: GraphNode, b: GraphNode) => number): ClusterLayout; } size: { (): number[]; diff --git a/datejs/datejs.d.ts b/datejs/datejs.d.ts index 6c510def6..5c4034bc5 100644 --- a/datejs/datejs.d.ts +++ b/datejs/datejs.d.ts @@ -15,7 +15,7 @@ interface IDateJSLiteral { } /** DateJS Public Static Methods */ -interface IDateJSStatic extends Date { +interface IDateJSStatic extends IDateJS { /** Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM) */ today(): IDateJS; /** Compares the first date to the second date and returns an number indication of their relative values. -1 = this is lessthan date. 0 = values are equal. 1 = this is greaterthan date. */ diff --git a/easeljs/easeljs-tests.ts b/easeljs/easeljs-tests.ts index 552f82e7a..b036ae570 100644 --- a/easeljs/easeljs-tests.ts +++ b/easeljs/easeljs-tests.ts @@ -71,4 +71,18 @@ function test_canvas_tick() { var canvas = document.getElementById('canvas'); var stage = new createjs.Stage(canvas); var stage = createjs.Ticker.addEventListener("tick", stage); +} + +function matrixDecompose() { + var matrix = new createjs.Matrix2D(); + var shape = new createjs.Shape(); + var transform = matrix.decompose(shape); + var transformData = matrix.decompose(); + shape.x = transformData.x; + shape.y = transformData.y; + shape.scaleX = transformData.scaleX; + shape.scaleY = transformData.scaleY; + shape.skewX = transformData.skewX; + shape.skewY = transformData.skewY; + shape.rotation = transformData.rotation; } \ No newline at end of file diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index bd6a31de0..08378828a 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -383,6 +383,7 @@ declare module createjs { appendTransform(x: number, y: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number, regX?: number, regY?: number): Matrix2D; clone(): Matrix2D; copy(matrix: Matrix2D): Matrix2D; + decompose(): {x: number; y: number; scaleX: number; scaleY: number; rotation: number; skewX: number; skewY: number}; decompose(target: Object): Matrix2D; identity(): Matrix2D; initialize(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number): Matrix2D; diff --git a/express/express.d.ts b/express/express.d.ts index cf5014e82..d7d3f0d89 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -681,6 +681,9 @@ declare module "express" { header(field: any): Response; header(field: string, value?: string): Response; + // Property indicating if HTTP headers has been sent for the response. + headersSent: boolean; + /** * Get value for header `field`. * diff --git a/firebase/firebase-tests.ts b/firebase/firebase-tests.ts index eb6be8373..1b921bcba 100644 --- a/firebase/firebase-tests.ts +++ b/firebase/firebase-tests.ts @@ -11,6 +11,152 @@ dataRef.auth(AUTH_TOKEN, function(error, result) { } }); +var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com/'); +/* + * Firebase.authWithCustomToken() + */ +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + // Log me in + dataRef.authWithCustomToken(AUTH_TOKEN, function (error, authData) { + if (error) { + console.log('Login Failed!', error); + } else { + console.log('Authenticated successfully with payload:', authData); + } + }); +} + +/* + * Firebase.authAnonymously() + */ +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + // Log me in + dataRef.authAnonymously(function (error, authData) { + if (error) { + console.log('Login Failed!', error); + } else { + console.log('Authenticated successfully with payload:', authData); + } + }); +} + +/* + * Firebase.authWithPassword() + */ +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + // Log me in + dataRef.authWithPassword({ + "email": "bobtony@firebase.com", + "password": "correcthorsebatterystaple" + }, function (error, authData) { + if (error) { + console.log('Login Failed!', error); + } else { + console.log('Authenticated successfully with payload:', authData); + } + }); +} + +/* + * Firebase.authWithOAuthPopup() + */ +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + // Log me in + dataRef.authWithOAuthPopup("twitter", function (error, authData) { + if (error) { + console.log('Login Failed!', error); + } else { + console.log('Authenticated successfully with payload:', authData); + } + }); +} + +/* + * Firebase.authWithOAuthRedirect + */ +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + // Log me in + dataRef.authWithOAuthRedirect("twitter", function (error) { + if (error) { + console.log('Login Failed!', error); + } else { + // We'll never get here, as the page will redirect on success. + } + }); +} + +/* + * Firebase.authWithOAuthToken() + */ +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + // Authenticate with Facebook using an existing OAuth 2.0 access token + dataRef.authWithOAuthToken("facebook", "", function (error, authData) { + if (error) { + console.log('Login Failed!', error); + } else { + console.log('Authenticated successfully with payload:', authData); + } + }); +} +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + // Authenticate with Twitter using an existing OAuth 1.0a credential set + dataRef.authWithOAuthToken("twitter", { + "user_id": "", + "oauth_token": "", + "oauth_token_secret": "", + }, function (error, authData) { + if (error) { + console.log('Login Failed!', error); + } else { + console.log('Authenticated successfully with payload:', authData); + } + }); +} + +/* + * Firebase.getAuth() + */ +() => { + var dataRef = new Firebase('https://samplechat.firebaseio-demo.com'); + var authData = dataRef.getAuth(); + + if (authData) { + console.log('Authenticated user with uid:', authData.uid); + } +} + +/* + * Firebase.onAuth() + */ +() => { + var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com'); + firebaseRef.onAuth(function (authData) { + if (authData) { + console.log('Client is authenticated with uid ' + authData.uid); + } else { + // Client is unauthenticated + } + }); +} + +/* + * Firebase.offAuth + */ +() => { + var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com'); + var onAuthChange = function (authData: FirebaseAuthData) { /*...*/ }; + firebaseRef.onAuth(onAuthChange); + // Sometime later... + firebaseRef.offAuth(onAuthChange); +} + //Time to log out! dataRef.unauth(); @@ -36,6 +182,146 @@ var fredRef3:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/use var x4:string = fredRef3.name(); // x is now 'fred'. +/* + * Firebase.key() + */ +() => { + var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred"); + var key = fredRef.key(); // key === "fred" + key = fredRef.child("name/last").key(); // key === "last" +} +() => { + // Calling key() on the root of a Firebase will return null: + var rootRef = new Firebase("https://samplechat.firebaseio-demo.com"); + var key = rootRef.key(); // key === null +} + +/* + * Firebase.set() + */ +() => { + var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name'); + fredNameRef.child('first').set('Fred'); + fredNameRef.child('last').set('Flintstone'); + // We've written 'Fred' to the Firebase location storing fred's first name, + // and 'Flintstone' to the location storing his last name +} +() => { + var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name'); + fredNameRef.set({ first: 'Fred', last: 'Flintstone' }); + // Exact same effect as the previous example, except we've written + // fred's first and last name simultaneously +} +() => { + var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name'); + var onComplete = function (error: any) { + if (error) { + console.log('Synchronization failed'); + } else { + console.log('Synchronization succeeded'); + } + }; + fredNameRef.set({ first: 'Fred', last: 'Flintstone' }, onComplete); + // Same as the previous example, except we will also log a message + // when the data has finished synchronizing +} + +/* + * Firebase.update() + */ +() => { + var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name'); + // Modify the 'first' and 'last' children, but leave other data at fredNameRef unchanged + fredNameRef.update({ first: 'Fred', last: 'Flintstone' }); +} +() => { + var fredNameRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/name'); + // Same as the previous example, except we will also display an alert + // message when the data has finished synchronizing. + var onComplete = function (error:any) { + if (error) { + console.log('Synchronization failed'); + } else { + console.log('Synchronization succeeded'); + } + }; + fredNameRef.update({ first: 'Wilma', last: 'Flintstone' }, onComplete); +} +() => { + var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred'); + //The following 2 function calls are equivalent + fredRef.update({ name: { first: 'Fred', last: 'Flintstone' }}); + fredRef.child('name').set({ first: 'Fred', last: 'Flintstone' }); +} + +/* + * Firebase.remove() + */ +() => { + var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred'); + fredRef.remove(); + // All data at the Firebase location for user 'fred' has been deleted + // (including any child data) +} +() => { + var onComplete = function (error: any) { + if (error) { + console.log('Synchronization failed'); + } else { + console.log('Synchronization succeeded'); + } + }; + fredRef.remove(onComplete); + // Same as the previous example, except we will also log + // a message when the delete has finished synchronizing +} + +/* + * Firebase.push() + */ +() => { + var messageListRef = new Firebase('https://samplechat.firebaseio-demo.com/message_list'); + var newMessageRef = messageListRef.push(); + newMessageRef.set({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' }); + // We've appended a new message to the message_list location. + var path = newMessageRef.toString(); + // path will be something like + // 'https://samplechat.firebaseio-demo.com/message_list/-IKo28nwJLH0Nc5XeFmj' +} +() => { + var messageListRef = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list'); + messageListRef.push({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' }); + // Same effect as the previous example, but we've combined the push() and the set(). +} + +/* + * Firebase.setWithPriority() + */ +() => { + var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred'); + + var user = { + name: { + first: 'Fred', + last: 'Flintstone' + }, + rank: 1000 + }; + + fredRef.setWithPriority(user, 1000); + // We've written Fred's name and rank to firebase, and used his rank (1000) as the + // priority of the data so he'll be ordered relative to other users by his rank +} + +/* + * Firebase.setPriority() + */ +() => { + var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred'); + fredRef.setPriority(1000); + // We have changed the priority of fred's user data to 1000 +} + // Increment Fred's rank by 1. var fredRankRef:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred/rank'); fredRankRef.transaction(function(currentRank: number) { @@ -51,7 +337,7 @@ wilmaRef.transaction(function(currentData) { console.log('User wilma already exists.'); return; // Abort the transaction. } -}, function(error: any, committed: boolean, snapshot: IFirebaseDataSnapshot) { +}, function(error: any, committed: boolean, snapshot: FirebaseDataSnapshot) { if (error) console.log('Transaction failed abnormally!', error); else if (!committed) @@ -61,14 +347,523 @@ wilmaRef.transaction(function(currentData) { console.log('Wilma\'s data: ', snapshot.val()); }); -var messageListRef: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list'); -var lastMessagesQuery:IFirebaseQuery = messageListRef.endAt().limit(500); -lastMessagesQuery.on('child_added', function(childSnapshot: IFirebaseDataSnapshot) { /* handle child add */ }); +/* + * Firebase.createUser() + */ +() => { + var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com'); + firebaseRef.createUser({ + email: "bobtony@firebase.com", + password: "correcthorsebatterystaple" + }, function (err) { + if (err) { + switch (err.code) { + case 'EMAIL_TAKEN': + // The new user account cannot be created because the email is already in use. + case 'INVALID_EMAIL': + // The specified email is not a valid email. + default: + } + } else { + // User account created successfully! + } + }); +} -var messageListRef2:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list'); -var firstMessagesQuery:IFirebaseQuery = messageListRef2.startAt().limit(500); -firstMessagesQuery.on('child_added', function(childSnapshot: IFirebaseDataSnapshot) { /* handle child add */ }); +/* + * Firebase.changePassword() + */ +() => { + var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com'); + firebaseRef.changePassword({ + email: "bobtony@firebase.com", + oldPassword: "correcthorsebatterystaple", + newPassword: "shinynewpassword" + }, function (err) { + if (err) { + switch (err.code) { + case 'INVALID_PASSWORD': + // The specified user account password is incorrect. + case 'INVALID_USER': + // The specified user account does not exist. + default: + } + } else { + // User password changed successfully! + } + }); +} -var usersRef3: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users'); -var usersQuery: IFirebaseQuery = usersRef3.startAt(1000).limit(50); -usersQuery.on('child_added', function(userSnapshot: IFirebaseDataSnapshot) { /* handle user */ }); +/* + * Firebase.removeUser() + */ +() => { + var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com'); + firebaseRef.removeUser({ + email: "bobtony@firebase.com", + password: "correcthorsebatterystaple" + }, function (err) { + if (err) { + switch (err.code) { + case 'INVALID_USER': + // The specified user account does not exist. + case 'INVALID_PASSWORD': + // The specified user account password is incorrect. + default: + } + } else { + // User account deleted successfully! + } + }); +} + +/* + * Firebase.resetPassword() + */ +() => { + var firebaseRef = new Firebase('https://samplechat.firebaseio-demo.com'); + firebaseRef.resetPassword({ + email: "bobtony@firebase.com" + }, function (err) { + if (err) { + switch (err.code) { + case 'INVALID_USER': + // The specified user account does not exist. + default: + } + } else { + // Password reset email sent successfully! + } + }); +} + +//var messageListRef: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list'); +//var lastMessagesQuery:FirebaseQuery = messageListRef.endAt().limit(500); +//lastMessagesQuery.on('child_added', function(childSnapshot: FirebaseDataSnapshot) { /* handle child add */ }); + +//var messageListRef2:Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/message_list'); +//var firstMessagesQuery:FirebaseQuery = messageListRef2.startAt().limit(500); +//firstMessagesQuery.on('child_added', function(childSnapshot: FirebaseDataSnapshot) { /* handle child add */ }); + +//var usersRef3: Firebase = new Firebase('https://SampleChat.firebaseIO-demo.com/users'); +//var usersQuery: FirebaseQuery = usersRef3.startAt(1000).limit(50); +//usersQuery.on('child_added', function(userSnapshot: FirebaseDataSnapshot) { /* handle user */ }); + +/* + * Firebase.goOffline() + * Firebase.goOnline() + */ +() => { + var usersRef = new Firebase('https://samplechat.firebaseio-demo.com/users'); + Firebase.goOffline(); // All Firebase instances are disconnected + Firebase.goOnline(); // All Firebase instances automatically reconnect +} + +/* + * FirebaseQuery.on() + */ +() => { + firebaseRef.on('value', function (dataSnapshot) { + // code to handle new value. + }); + + firebaseRef.on('child_added', function (childSnapshot, prevChildName) { + // code to handle new child. + }); + + firebaseRef.on('child_removed', function (oldChildSnapshot) { + // code to handle child removal. + }); + + firebaseRef.on('child_changed', function (childSnapshot, prevChildName) { + // code to handle child data changes. + }); + + firebaseRef.on('child_changed', function (childSnapshot, prevChildName) { + // code to handle child data changes. + }); +} + +/* + * FirebaseQuery.off() + */ +() => { + var onValueChange = function (dataSnapshot: FirebaseDataSnapshot) { /* handle... */ }; + firebaseRef.on('value', onValueChange); + // Sometime later... + firebaseRef.off('value', onValueChange); +} +() => { + // Or you can save a line of code by using an inline function + // and on()'s return value. + var onValueChange = firebaseRef.on('value', function (dataSnapshot) { /* handle... */ }); + // Sometime later... + firebaseRef.off('value', onValueChange); +} + +/* + * FirebaseQuery.once() + */ +() => { + // Basic usage of .once() to read the data located at firebaseRef. + firebaseRef.once('value', function (dataSnapshot) { + // handle read data. + }); +} +() => { + // Provide a failureCallback to be notified when this + // callback is revoked due to security violations. + firebaseRef.once('value', function (dataSnapshot) { + // code to handle new value + }, function (err: any) { + // code to handle read error + }); +} +() => { + // Provide a context to override "this" when callbacks are triggered. + firebaseRef.once('value', function (dataSnapshot) { + // this.x is 1 + }, { x: 1 }); +} + +/* + * FirebaseQuery.orderByChild() + */ +() => { + // For example, using our sample Firebase of dinosaur facts, + // we can read all dinosaurs ordered by height using the following query: + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByChild("height").on("child_added", function (snapshot) { + console.log(snapshot.key() + " was " + snapshot.val().height + " meters tall"); + }); +} + +/* + * FirebaseQuery.orderByKey() + */ +() => { + // For example, using our sample Firebase of dinosaur facts, + // we can read all dinosaurs in alphabetical order, ignoring their priority, + // using the following query: + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByKey().on("child_added", function (snapshot) { + console.log(snapshot.key()); + }); +} + +/* + * FirebaseQuery.orderByPriority() + */ +() => { + // For example, using our sample Firebase of dinosaur facts, + // we can read all dinosaurs in priority order using the following query: + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByPriority().on("child_added", function (snapshot) { + console.log(snapshot.key()); + }); +} + +/* + * FirebaseQuery.startAt() + */ +() => { + // For example, using our sample Firebase of dinosaur facts, + // we can find all dinosaurs that are at least three meters tall + // by combining orderByChild() and startAt(): + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByChild("height").startAt(3).on("child_added", function (snapshot) { + console.log(snapshot.key()) + }); +} + +/* + * FirebaseQuery.endAt() + */ +() => { + // For example, using our sample Firebase of dinosaur facts, + // we can find all dinosaurs whose names come before Pterodactyl lexicographically + // by combining orderByKey() and endAt(): + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByKey().endAt("pterodactyl").on("child_added", function (snapshot) { + console.log(snapshot.key()); + }); +} + +/* + * FirebaseQuery.equalTo() + */ +() => { + // For example, using our sample Firebase of dinosaur facts, + // we can find all dinosaurs whose height is exactly 25 meters + // by combining orderByChild() and equalTo(): + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByChild("height").equalTo(25).on("child_added", function (snapshot) { + console.log(snapshot.key()); + }); +} + +/* + * FirebaseQuery.limitToFirst + */ +() => { + // Using our sample Firebase of dinosaur facts, + // we can find the two shortest dinosaurs with this query: + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByChild("height").limitToFirst(2).on("child_added", function (snapshot) { + console.log(snapshot.key()); + }); +} + +/* + * FirebaseQuery.limitToLast + */ +() => { + // Using our sample Firebase of dinosaur facts, + // we can find the two heaviest dinosaurs with this query: + var ref = new Firebase("https://dinosaur-facts.firebaseio.com/"); + ref.orderByChild("weight").limitToLast(2).on("child_added", function (snapshot) { + console.log(snapshot.key()); + }); +} + +/* + * FirebaseQuery.ref() + */ +() => { + // The Firebase reference returned by ref() is equivalent to the Firebase reference used to create the Query. + var ref = new Firebase("https://samplechat.firebaseio-demo.com/users"); + var query = ref.limitToFirst(5); + var refToSameLocation = query.ref(); // ref === refToSameLocation +} + +/* + * Firebase.onDisconnect().set() + */ +() => { + var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectmessage'); + disconnectRef.onDisconnect().set('I disconnected!'); +} + +/* + * Firebase.onDisconnect().update() + */ +() => { + var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectmessage'); + disconnectRef.onDisconnect().update({ message: 'I disconnected!' }); +} + +/* + * Firebase.onDisconnect().remove() + */ +() => { + var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectdata'); + disconnectRef.onDisconnect().remove(); +} + +/* + * Firebase.onDisconnect().setWithPriority() + */ +() => { + var disconnectRef = new Firebase('https://samplechat.firebaseio-demo.com/disconnectMessage'); + disconnectRef.onDisconnect().setWithPriority('I disconnected', 10); +} + +/* + * Firebase.onDisconnect().cancel() + */ +() => { + var fredOnlineRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred/online'); + fredOnlineRef.onDisconnect().set(false); + + // cancel the previously set onDisconnect().set() event + fredOnlineRef.onDisconnect().cancel(); +} + +/* + * Firebase.ServerValue.TIMESTAMP + */ +() => { + // Record the current time immediately, and queue an event to + // record the time at which the user disconnects. + var sessionsRef = new Firebase('https://samplechat.firebaseio-demo.com/sessions/'); + var mySessionRef = sessionsRef.push(); + mySessionRef.onDisconnect().update({ endedAt: Firebase.ServerValue.TIMESTAMP }); + mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP }); +} + +/* + * DataSnapshot.val() + */ +() => { + // Demonstrate writing data and then reading it back as a Javascript object. + var fredNameRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/fred'); + fredNameRef.set({ first: 'Fred', last: 'Flintstone' }); + + fredNameRef.once('value', function (nameSnapshot) { + var val = nameSnapshot.val(); + // val now contains the object { first: 'Fred', last: 'Flintstone' }. + }); +} + +/* + * DataSnapshot.child() + */ +(dataSnapshot:FirebaseDataSnapshot) => { + // Given a DataSnapshot containing a child 'name' that has children 'first' + // (set to 'Fred') and 'last' (set to 'Flintstone'): + var nameSnapshot = dataSnapshot.child('name'); + var name = nameSnapshot.val(); + // name now contains { first: 'Fred', last: 'Flintstone'}. + + var firstNameSnapshot = dataSnapshot.child('name/first'); + var firstName = firstNameSnapshot.val(); + // firstName now contains 'Fred'. + + var favoriteColorSnapshot = dataSnapshot.child('favorite_color'); + var favoriteColor = favoriteColorSnapshot.val(); + // favoriteColor will be null, because there is no 'favorite_color' child in dataSnapshot. +} + +/* + * DataSnapshot.forEach() + */ +(dataSnapshot:FirebaseDataSnapshot) => { + // Given a DataSnapshot containing a child "fred" and a child "wilma", this callback + // function will be called twice + dataSnapshot.forEach(function (childSnapshot) { + // key will be "fred" the first time and "wilma" the second time + var key = childSnapshot.key(); + + // childData will be the actual contents of the child + var childData = childSnapshot.val(); + }); +} +(dataSnapshot:FirebaseDataSnapshot) => { + // Given a DataSnapshot containing a child "fred" and a child "wilma", this callback + // funciton will only be called once (since we return true) + dataSnapshot.forEach(function (childSnapshot) { + var key = childSnapshot.key(); // key will be "fred" + return true; + }); +} + +/* + * DataSnapshot.hasChild() + */ +(dataSnapshot: FirebaseDataSnapshot) => { + // Given a DataSnapshot with child 'fred' and no other children: + var x = dataSnapshot.hasChild('fred'); + var y = dataSnapshot.hasChild('whales'); + // x is true and y is false. +} + +/* + * DataSnapshot.hasChildren() + */ +(dataSnapshot: FirebaseDataSnapshot) => { + // Given a DataSnapshot containing a child 'name' with children 'first' + // (set to 'Fred') and 'last' (set to 'Flintstone'): + var x = dataSnapshot.hasChildren(); + // x is true. + var y = dataSnapshot.child('name').hasChildren(); + // y is true. + var z = dataSnapshot.child('name/first').hasChildren(); + // z is false since 'Fred' is a string and therefore has no children. +} + +/* + * DataSnapshot.key() + */ +() => { + // Calling key() on any DataSnapshot (except for one which represents the root of a Firebase) + // will return the key name of the location that generated it: + var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred"); + fredRef.on("value", function (fredSnapshot) { + var key = fredSnapshot.key(); // key === "fred" + key = fredSnapshot.child("name/last").key(); // key === "last" + }); +} +() => { + // Calling key() on a DataSnapshot generated from a reference to the root of a Firebase return null: + var rootRef = new Firebase("https://samplechat.firebaseio-demo.com"); + rootRef.on("value", function (rootSnapshot) { + var key = rootSnapshot.key(); // key === null + }); +} + +/* + * DataSnapshot.name() + */ +() => { + var fredRef = new Firebase("https://samplechat.firebaseio-demo.com/users/fred"); + fredRef.on("value", function (fredSnapshot) { + var key = fredSnapshot.name(); // key === "fred" + key = fredSnapshot.child("name/last").name(); // key === "last" + }); +} +() => { + var rootRef = new Firebase("https://samplechat.firebaseio-demo.com"); + rootRef.on("value", function (rootSnapshot) { + var key = rootSnapshot.name(); // key === null + }); +} + +/* + * DataSnapshot.numChildren() + */ +(dataSnapshot: FirebaseDataSnapshot) => { + // Given a DataSnapshot containing a child 'name' with children 'first' + // (set to 'Fred') and 'last' (set to 'Flintstone'): + var x = dataSnapshot.numChildren(); + // x is 1. + var y = dataSnapshot.child('name').numChildren(); + // y is 2. + var z = dataSnapshot.child('name/first').numChildren(); + // z is 0 since 'Fred' is a string and therefore has no children. +} + +/* + * DataSnaphot.ref() + */ +() => { + var fredRef = new Firebase('https://samplechat.firebaseio-demo.com/users/fred'); + fredRef.on('value', function (fredSnapshot) { + var fredRef2 = fredSnapshot.ref(); + // fredRef and fredRef2 both point to the same location. + }); +} + +/* + * DataSnapshot.getPriority() + */ +(dataSnapshot: FirebaseDataSnapshot) => { + // Given a snapshot for data with priority 1000: + var x = dataSnapshot.getPriority(); + // x is now 1000. +} + +/* + * DataSnapshot.exportVal() + */ +(dataSnapshot: FirebaseDataSnapshot) => { + firebaseRef.setWithPriority('hello', 500); + firebaseRef.once('value', function (dataSnapshot) { + var x = dataSnapshot.exportVal(); + // x now contains { '.value': 'hello', '.priority': 500 } + }); +} +(dataSnapshot: FirebaseDataSnapshot) => { + firebaseRef.set('hello'); + firebaseRef.once('value', function (dataSnapshot) { + var x = dataSnapshot.exportVal(); + // x now contains 'hello' + }); +} +(dataSnapshot: FirebaseDataSnapshot) => { + // Note: To access these variables in JavaScript, you can use x['.value'] and x['.priority']. + firebaseRef.setWithPriority({ a: 'hello', b: 'hi' }, 500); + firebaseRef.once('value', function (dataSnapshot) { + var x = dataSnapshot.exportVal(); + // x now contains { 'a': 'hello', 'b': 'hi', '.priority': 500 } + }); +} diff --git a/firebase/firebase.d.ts b/firebase/firebase.d.ts index bac32fbc6..fdb808ec4 100644 --- a/firebase/firebase.d.ts +++ b/firebase/firebase.d.ts @@ -1,75 +1,308 @@ -// Type definitions for Firebase API +// Type definitions for Firebase API 2.0.2 // Project: https://www.firebase.com/docs/javascript/firebase -// Definitions by: Vincent Botone +// Definitions by: Vincent Botone , Shin1 Kashimura // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface IFirebaseAuthResult { +interface FirebaseAuthResult { auth: any; expires: number; } -interface IFirebaseDataSnapshot { +interface FirebaseDataSnapshot { + /** + * Gets the JavaScript object representation of the DataSnapshot. + */ val(): any; - child(childPath: string): IFirebaseDataSnapshot; - forEach(childAction: (childSnapshot: IFirebaseDataSnapshot) => boolean): boolean; + /** + * Gets a DataSnapshot for the location at the specified relative path. + */ + child(childPath: string): FirebaseDataSnapshot; + /** + * Enumerates through the DataSnapshot’s children (in the default order). + */ + forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => void): boolean; + forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => boolean): boolean; + /** + * Returns true if the specified child exists. + */ hasChild(childPath: string): boolean; + /** + * Returns true if the DataSnapshot has any children. + */ hasChildren(): boolean; + /** + * Gets the key name of the location that generated this DataSnapshot. + */ + key(): string; + /** + * @deprecated Use key() instead. + * Gets the key name of the location that generated this DataSnapshot. + */ name(): string; + /** + * Gets the number of children for this DataSnapshot. + */ numChildren(): number; + /** + * Gets the Firebase reference for the location that generated this DataSnapshot. + */ ref(): Firebase; + /** + * Gets the priority of the data in this DataSnapshot. + * @returns {string, number, null} The priority, or null if no priority was set. + */ getPriority(): any; // string or number + /** + * Exports the entire contents of the DataSnapshot as a JavaScript object. + */ exportVal(): Object; } -interface IFirebaseOnDisconnect { +interface FirebaseOnDisconnect { + /** + * Ensures the data at this location is set to the specified value when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ set(value: any, onComplete?: (error: any) => void): void; + /** + * Ensures the data at this location is set to the specified value and priority when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void; setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void; - update(value: any, onComplete?: (error: any) => void): void; + /** + * Writes the enumerated children at this Firebase location when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ + update(value: Object, onComplete?: (error: any) => void): void; + /** + * Ensures the data at this location is deleted when the client is disconnected + * (due to closing the browser, navigating to a new page, or network issues). + */ remove(onComplete?: (error: any) => void): void; + /** + * Cancels all previously queued onDisconnect() set or update events for this location and all children. + */ cancel(onComplete?: (error: any) => void): void; } -interface IFirebaseQuery { - on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void; - off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void; - once(eventType: string, successCallback: (dataSnapshot: IFirebaseDataSnapshot) => void, failureCallback?: () => void, context?: Object): void; - limit(limit: number): IFirebaseQuery; - startAt(priority?: string, name?: string): IFirebaseQuery; - startAt(priority?: number, name?: string): IFirebaseQuery; - endAt(priority?: string, name?: string): IFirebaseQuery; - endAt(priority?: number, name?: string): IFirebaseQuery; +interface FirebaseQuery { + /** + * Listens for data changes at a particular location. + */ + on(eventType: string, callback: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: (error: any) => void, context?: Object): (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void; + /** + * Detaches a callback previously attached with on(). + */ + off(eventType?: string, callback?: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void; + /** + * Listens for exactly one event of the specified event type, and then stops listening. + */ + once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, context?: Object): void; + once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, failureCallback?: (error: any) => void, context?: Object): void; + /** + * Generates a new Query object ordered by the specified child key. + */ + orderByChild(key: string): FirebaseQuery; + /** + * Generates a new Query object ordered by key name. + */ + orderByKey(): FirebaseQuery; + /** + * Generates a new Query object ordered by priority. + */ + orderByPriority(): FirebaseQuery; + /** + * @deprecated Use limitToFirst() and limitToLast() instead. + * Generates a new Query object limited to the specified number of children. + */ + limit(limit: number): FirebaseQuery; + /** + * Creates a Query with the specified starting point. + * The generated Query includes children which match the specified starting point. + */ + startAt(value: string, key?: string): FirebaseQuery; + startAt(value: number, key?: string): FirebaseQuery; + /** + * Creates a Query with the specified ending point. + * The generated Query includes children which match the specified ending point. + */ + endAt(value: string, key?: string): FirebaseQuery; + endAt(value: number, key?: string): FirebaseQuery; + /** + * Creates a Query which includes children which match the specified value. + */ + equalTo(value: string, key?: string): FirebaseQuery; + equalTo(value: number, key?: string): FirebaseQuery; + /** + * Generates a new Query object limited to the first certain number of children. + */ + limitToFirst(limit: number): FirebaseQuery; + /** + * Generates a new Query object limited to the last certain number of children. + */ + limitToLast(limit: number): FirebaseQuery; + /** + * Gets a Firebase reference to the Query's location. + */ ref(): Firebase; } -declare class Firebase implements IFirebaseQuery { - constructor(firebaseURL: string); - auth(authToken: string, onComplete?: (error: any, result: IFirebaseAuthResult) => void, onCancel?:(error: any) => void): void; +interface Firebase extends FirebaseQuery { + /** + * @deprecated Use authWithCustomToken() instead. + * Authenticates a Firebase client using the provided authentication token or Firebase Secret. + */ + auth(authToken: string, onComplete?: (error: any, result: FirebaseAuthResult) => void, onCancel?:(error: any) => void): void; + /** + * Authenticates a Firebase client using an authentication token or Firebase Secret. + */ + authWithCustomToken(autoToken: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?:Object): void; + /** + * Authenticates a Firebase client using a new, temporary guest account. + */ + authAnonymously(onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Authenticates a Firebase client using an email / password combination. + */ + authWithPassword(credentials: FirebaseCredentials, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Authenticates a Firebase client using a popup-based OAuth flow. + */ + authWithOAuthPopup(provider: string, onComplete:(error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Authenticates a Firebase client using a redirect-based OAuth flow. + */ + authWithOAuthRedirect(provider: string, onComplete: (error: any) => void, options?: Object): void; + /** + * Authenticates a Firebase client using OAuth access tokens or credentials. + */ + authWithOAuthToken(provider: string, credentials: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + authWithOAuthToken(provider: string, credentials: Object, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; + /** + * Synchronously access the current authentication state of the client. + */ + getAuth(): FirebaseAuthData; + /** + * Listen for changes to the client's authentication state. + */ + onAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void; + /** + * Detaches a callback previously attached with onAuth(). + */ + offAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void; + /** + * Unauthenticates a Firebase client. + */ unauth(): void; + /** + * Gets a Firebase reference for the location at the specified relative path. + */ child(childPath: string): Firebase; + /** + * Gets a Firebase reference to the parent location. + */ parent(): Firebase; + /** + * Gets a Firebase reference to the root of the Firebase. + */ root(): Firebase; + /** + * Returns the last token in a Firebase location. + */ + key(): string; + /** + * @deprecated Use key() instead. + * Returns the last token in a Firebase location. + */ name(): string; + /** + * Gets the absolute URL corresponding to this Firebase reference's location. + */ toString(): string; + /** + * Writes data to this Firebase location. + */ set(value: any, onComplete?: (error: any) => void): void; - update(value: any, onComplete?: (error: any) => void): void; + /** + * Writes the enumerated children to this Firebase location. + */ + update(value: Object, onComplete?: (error: any) => void): void; + /** + * Removes the data at this Firebase location. + */ remove(onComplete?: (error: any) => void): void; - push(value: any, onComplete?: (error: any) => void): Firebase; + /** + * Generates a new child location using a unique name and returns a Firebase reference to it. + * @returns {Firebase} A Firebase reference for the generated location. + */ + push(value?: any, onComplete?: (error: any) => void): Firebase; + /** + * Writes data to this Firebase location. Like set() but also specifies the priority for that data. + */ setWithPriority(value: any, priority: string, onComplete?: (error: any) => void): void; setWithPriority(value: any, priority: number, onComplete?: (error: any) => void): void; + /** + * Sets a priority for the data at this Firebase location. + */ setPriority(priority: string, onComplete?: (error: any) => void): void; setPriority(priority: number, onComplete?: (error: any) => void): void; - transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: IFirebaseDataSnapshot) => void, applyLocally?: boolean): void; - onDisconnect(): IFirebaseOnDisconnect; - on(eventType: string, callback: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: ()=> void, context?: Object): (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void; - off(eventType?: string, callback?: (dataSnapshot: IFirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void; - once(eventType: string, successCallback: (dataSnapshot: IFirebaseDataSnapshot) => void, failureCallback?: () => void, context?: Object): void; - limit(limit: number): IFirebaseQuery; - startAt(priority?: string, name?: string): IFirebaseQuery; - startAt(priority?: number, name?: string): IFirebaseQuery; - endAt(priority?: string, name?: string): IFirebaseQuery; - endAt(priority?: number, name?: string): IFirebaseQuery; - ref(): Firebase; - goOffline(): void; - goOnline(): void; + /** + * Atomically modifies the data at this location. + */ + transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: FirebaseDataSnapshot) => void, applyLocally?: boolean): void; + /** + * Creates a new user account using an email / password combination. + */ + createUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void; + /** + * Change the password of an existing user using an email / password combination. + */ + changePassword(credentials: { email: string; oldPassword: string; newPassword: string }, onComplete: (error: any) => void): void; + /** + * Removes an existing user account using an email / password combination. + */ + removeUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void; + /** + * Sends a password-reset email to the owner of the account, containing a token that may be used to authenticate and change the user password. + */ + resetPassword(credentials: { email: string }, onComplete: (error: any) => void): void; + onDisconnect(): FirebaseOnDisconnect; } +interface FirebaseStatic { + /** + * Constructs a new Firebase reference from a full Firebase URL. + */ + new (firebaseURL: string): Firebase; + /** + * Manually disconnects the Firebase client from the server and disables automatic reconnection. + */ + goOffline(): void; + /** + * Manually reestablishes a connection to the Firebase server and enables automatic reconnection. + */ + goOnline(): void; + + ServerValue: { + /** + * A placeholder value for auto-populating the current timestamp + * (time since the Unix epoch, in milliseconds) by the Firebase servers. + */ + TIMESTAMP: any; + }; +} +declare var Firebase: FirebaseStatic; + +// Reference: https://www.firebase.com/docs/web/api/firebase/getauth.html +interface FirebaseAuthData { + uid: string; + provider: string; + token: string; + expires: number; + auth: Object; +} + +interface FirebaseCredentials { + email: string; + password: string; +} \ No newline at end of file diff --git a/gamepad/gamepad-tests.ts b/gamepad/gamepad-tests.ts index 5d82c33ec..48b0f8e73 100644 --- a/gamepad/gamepad-tests.ts +++ b/gamepad/gamepad-tests.ts @@ -19,22 +19,22 @@ }; (()=>{ - window.addEventListener('GamepadConnected', (e: GamepadEvent)=>{ + window.addEventListener('GamepadConnected', (e: Gamepad.GamepadEvent)=>{ console.log('Gamepad ' + e.gamepad.index + ' connected!'); }, false); - window.addEventListener('GamepadDisconnected', (e: GamepadEvent)=>{ + window.addEventListener('GamepadDisconnected', (e: Gamepad.GamepadEvent)=>{ console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); }, false); - window.addEventListener('webkitGamepadConnected', (e: GamepadEvent)=>{ + window.addEventListener('webkitGamepadConnected', (e: Gamepad.GamepadEvent)=>{ console.log('Gamepad ' + e.gamepad.index + ' connected!'); }, false); - window.addEventListener('webkitGamepadDisconnected', (e: GamepadEvent)=>{ + window.addEventListener('webkitGamepadDisconnected', (e: Gamepad.GamepadEvent)=>{ console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); }, false); - window.addEventListener('mozGamepadConnected', (e: GamepadEvent)=>{ + window.addEventListener('mozGamepadConnected', (e: Gamepad.GamepadEvent)=>{ console.log('Gamepad ' + e.gamepad.index + ' connected!'); }, false); - window.addEventListener('mozGamepadDisconnected', (e: GamepadEvent)=>{ + window.addEventListener('mozGamepadDisconnected', (e: Gamepad.GamepadEvent)=>{ console.log('Gamepad ' + e.gamepad.index + ' disconnected!'); }, false); @@ -45,9 +45,9 @@ { requestAnimationFrame.call(window, runAnimation); - var gamepads: GamepadList = getGamepads.call(navigator); + var gamepads: Gamepad.GamepadList = getGamepads.call(navigator); for(var i = 0; i < gamepads.length; i++){ - var pad: Gamepad = gamepads[i]; + var pad: Gamepad.Gamepad = gamepads[i]; if(pad){ for (var k = 0; k < pad.buttons.length; k++) { diff --git a/gamepad/gamepad.d.ts b/gamepad/gamepad.d.ts index 833b71434..f6af65a1a 100644 --- a/gamepad/gamepad.d.ts +++ b/gamepad/gamepad.d.ts @@ -3,55 +3,69 @@ // Definitions by: Kon // Definitions: https://github.com/borisyankov/DefinitelyTyped -/** - * This interface defines an individual gamepad device. - */ -interface Gamepad{ +declare module Gamepad{ /** - * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. - * @readonly + * This interface defines an individual gamepad device. */ - id:string; - - /** - * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. - * @readonly - */ - index:number; + export interface Gamepad{ + /** + * An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID. + * @readonly + */ + id:string; + + /** + * The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused. + * @readonly + */ + index:number; + + /** + * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. + * @readonly + */ + timestamp:number; + + /** + * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. + * @readonly + */ + axes:number[]; + + /** + * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. + * @readonly + */ + buttons:number[]; + } /** - * Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp. - * @readonly + * */ - timestamp:number; + export interface GamepadEvent extends Event{ + /** + * The single gamepad attribute provides access to the associated gamepad data for this event. + * @readonly + */ + gamepad:Gamepad; + } - /** - * Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick. - * @readonly + export interface GamepadList{ + [index: number]: Gamepad; + length: number; + } + + + + /* + * @event gamepadconnected + * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. */ - axes:number[]; - /** - * Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array. - * @readonly + /* + * @event gamepaddisconnected + * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. */ - buttons:number[]; -} - -/** - * - */ -interface GamepadEvent extends Event{ - /** - * The single gamepad attribute provides access to the associated gamepad data for this event. - * @readonly - */ - gamepad:Gamepad; -} - -interface GamepadList{ - [index: number]: Gamepad; - length: number; } interface Navigator{ @@ -59,20 +73,10 @@ interface Navigator{ * The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices. * @readonly */ - getGamepads(): Gamepad[]; + getGamepads(): Gamepad.Gamepad[]; + + webkitGetGamepads(): Gamepad.GamepadList; - webkitGetGamepads(): GamepadList; - // Not supported yet :( // mozGetGamepads(): Gamepad[]; } - -/* - * @event gamepadconnected - * A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis. - */ - -/* - * @event gamepaddisconnected - * When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched. - */ \ No newline at end of file diff --git a/glidejs/glidejs-tests.ts b/glidejs/glidejs-tests.ts new file mode 100644 index 000000000..67cd2bdbc --- /dev/null +++ b/glidejs/glidejs-tests.ts @@ -0,0 +1,50 @@ +/// +/// + +// Copied from documentation +$('.slider').glide(); + +$('.slider').glide({ + autoplay: 5000, + arrows: 'body', + navigation: 'body' +}); + +var glide: JQueryGlide.IGlideApi = $('.slider').glide().data('api_glide'); +// Original line modified: glide.jump(3, console.log('Wooo!')); +glide.jump(3, function () { console.log('Wooo!'); }); + +// The rest of tests +glide.current(); +glide.reinit(); +glide.destroy(); +glide.play(); +glide.pause(); +glide.next(function () { }); +glide.prev(function () { }); +glide.nav("div"); +glide.arrows("div"); + +$(".slider").glide({ autoplay: 4000 }); +$(".slider").glide({ hoverpause: true }); +$(".slider").glide({ circular: true }); +$(".slider").glide({ animationDuration: 500 }); +$(".slider").glide({ animationTimingFunc: "cubic - bezier(0.165, 0.840, 0.440, 1.000)" }); +$(".slider").glide({ arrows: true }); +$(".slider").glide({ arrowsWrapperClass: "slider__arrows" }); +$(".slider").glide({ arrowMainClass: "slider__arrows-item" }); +$(".slider").glide({ arrowRightClass: "slider__arrows-item--right" }); +$(".slider").glide({ arrowLeftClass: "slider__arrows-item--left" }); +$(".slider").glide({ arrowRightText: "next" }); +$(".slider").glide({ arrowLeftText: "prev" }); +$(".slider").glide({ navigation: true }); +$(".slider").glide({ navigationCenter: true }); +$(".slider").glide({ navigationClass: "slider__nav" }); +$(".slider").glide({ navigationItemClass: "slider__nav-item" }); +$(".slider").glide({ navigationCurrentItemClass: "slider__nav-item--current" }); +$(".slider").glide({ keyboard: true }); +$(".slider").glide({ touchDistance: 60 }); +$(".slider").glide({ beforeInit: function () { } }); +$(".slider").glide({ afterInit: function () { } }); +$(".slider").glide({ beforeTransition: function () { } }); +$(".slider").glide({ afterTransition: function () { } }); diff --git a/glidejs/glidejs.d.ts b/glidejs/glidejs.d.ts new file mode 100644 index 000000000..bbf35f7e8 --- /dev/null +++ b/glidejs/glidejs.d.ts @@ -0,0 +1,189 @@ +// Type definitions for Glide.js v1.0.6 +// Project: http://glide.jedrzejchalubek.com/ +// Definitions by: Milan Jaros +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface JQuery { + /** + * Glide is responsive and touch-friendly jQuery slider. + * Based on CSS3 transitions with fallback to older broswers. + * It's simple, lightweight and fast. Designed to slide, + * no less, no more. + */ + glide(options?: JQueryGlide.IGlideOptions): JQuery; +} + +declare module JQueryGlide { + interface IGlideOptions { + /** + * Default: 4000 + * {Int or Bool} False for turning off autoplay + */ + autoplay?: any; + /** + * Default: true {Bool} Pause autoplay on mouseover slider + */ + hoverpause?: boolean; + /** + * Default: true {Bool} Circular play (Animation continues without starting over once it reaches the last slide) + */ + circular?: boolean; + + /** + * Default: 500 + * Animation time in ms + * @type {Int} + */ + animationDuration?: number; + /** + * Default: cubic-bezier(0.165, 0.840, 0.440, 1.000) + * cubic-bezier(0.165, 0.840, 0.440, 1.000) + */ + animationTimingFunc?: string; + + /** + * Default: true + * {Bool or String} Show/hide/appendTo arrows + * True for append arrows to slider wrapper + * False for not appending arrows + * Id or class name (e.g. '.class-name') for appending to specific HTML markup + */ + arrows?: any; + /** + * Default: 'slider-arrows' + * {String} Arrows wrapper class + */ + arrowsWrapperClass?: string; + /** + * Default: 'slider-arrow' + * {String} Main class for both arrows + */ + arrowMainClass?: string; + /** + * Default: 'slider-arrow--right' + * {String} Right arrow + */ + arrowRightClass?: string; + /** + * Default: 'next' + * {String} Right arrow text + */ + arrowRightText?: string; + /** + * Default: 'slider-arrow--left' + * {String} Left arrow + */ + arrowLeftClass?: string; + /** + * Default: 'prev' + * {String} Left arrow text + */ + arrowLeftText?: string; + + /** + * Default: true + * {Bool or String} Show/hide/appendTo bullets navigation + * True for append arrows to slider wrapper + * False for not appending arrows + * Id or class name (e.g. '.class-name') for appending to specific HTML markup + */ + navigation?: any; + /** + * Default: true + * {Bool} Center bullet navigation + */ + navigationCenter?: boolean; + /** + * Default: 'slider-nav' + * {String} Navigation class + */ + navigationClass?: string; + /** + * Default: 'slider-nav__item' + * {String} Navigation item class + */ + navigationItemClass?: string; + /** + * Default: 'slider-nav__item--current' + * {String} Current navigation item class + */ + navigationCurrentItemClass?: string; + + /** + * Default: true + * {Bool} Slide on left / right keyboard arrows press + */ + keyboard?: boolean; + + /** + * Default: 60 + * {Int or Bool} Touch settings + */ + touchDistance?: any; + + /** + * Default: function () {} + * {Function} Callback before plugin init + */ + beforeInit?: Function; + /** + * Default: function () {} + * {Function} Callback after plugin init + */ + afterInit?: Function; + + /** + * Default: function () {} + * {Function} Callback before slide change + */ + beforeTransition?: Function; + /** + * Default: function() {} + * {Function} Callback after slide change + */ + afterTransition?: Function; + } + + interface IGlideApi { + /** + * Returning current slide number + */ + current(): number; + /** + * Rebuild and recalculate dimensions of slider elements + */ + reinit(): void; + /** + * Destroy and cleanup slider + */ + destroy(): void; + /** + * Starting autoplay + */ + play(): void; + /** + * Stopping autoplay + */ + pause(): void; + /** + * Slide one forward + */ + next(callback: Function): void; + /** + * Slide one backward + */ + prev(callback: Function): void; + /** + * Jump to current slide + */ + jump(distance: number, callback: Function): void; + /** + * Append navigation to specifed target (eq. 'body', '.class', '#id') + */ + nav(target: string): void; + /** + * Append arrows to specifed target (eq. 'body', '.class', '#id') + */ + arrows(target: string): void; + } +} diff --git a/gm/gm-tests.ts b/gm/gm-tests.ts new file mode 100644 index 000000000..e3172dfc6 --- /dev/null +++ b/gm/gm-tests.ts @@ -0,0 +1,350 @@ +/// +/// + +import gm = require('gm'); +import stream = require('stream'); + +var src: string; +var matrix: string; +var enable: boolean; +var ltr: boolean; +var password: string; +var bits: number; +var intensity: number; +var r: number; +var g: number; +var b: number; +var opacity: number; +var x: number; +var y: number; +var radius: number; +var sigma: number; +var width: number; +var height: number; +var color: string; +var channel: string; +var type: string; +var factor: number; +var numColors: number; +var operator: string; +var multiplier: number; +var kernel: string; +var usePercent: boolean; +var time: number; +var server: string; +var method: string; +var percent: number; +var encoding: string; +var options: string; +var file: string; +var distance: number; +var geometry: string; +var direction: string; +var name: string; +var offset: number; +var blackPoint: number; +var gamma: number; +var whitePoint: number; +var limit: string; +var format: string; +var iterations: number; +var count: number; +var b: number; +var s: number; +var h: number; +var dest: string; +var images: string[]; +var angle: number; +var NxN: string; +var size: number; +var command: string; +var index: number; +var threshold: number; +var attribute: string; +var attrValue: string; +var format: string; +var font: string; +var quality: number; +var align: string; +var depth: number; +var readStream: stream.PassThrough; + +gm(src) + .adjoin() + .affine(matrix) + .antialias(enable) + .append(src) + .append(src, ltr) + .authenticate(password) + .autoOrient() + .backdrop() + .bitdepth(bits) + .blackThreshold(intensity) + .blackThreshold(r, g, b) + .blackThreshold(r, g, b, opacity) + .bluePrimary(x, y) + .blur(radius) + .blur(radius, sigma) + .border(width, height) + .borderColor(color) + .box(color) + .channel(channel) + .charcoal(factor) + .chop(width, height) + .chop(width, height, x, y) + .clip() + .coalesce() + .colorize(r, g, b) + .colorMap(type) + .colors(numColors) + .colorspace(type) + .compose(operator) + .compress(type) + .contrast(multiplier) + .convolve(kernel) + .createDirectories() + .crop(width, height) + .crop(width, height, x, y) + .crop(width, height, x, y, usePercent) + .cycle(factor) + .deconstruct() + .define() + .delay(time) + .density(width, height) + .despeckle() + .displace(x, y) + .display(server) + .dispose(method) + .dissolve(percent) + .dither() + .dither(enable) + .edge() + .edge(radius) + .emboss() + .emboss(radius) + .encoding(encoding) + .endian(type) + .enhance() + .equalize() + .extent(width, height) + .extent(width, height, options) + .file(file) + .filter(type) + .flatten() + .flip() + .flop() + .foreground(color) + .frame(width, height, width, height) + .fuzz(distance) + .fuzz(distance, usePercent) + .gamma(r, b, g) + .gaussian(radius) + .gaussian(radius, sigma) + .geometry(width, height) + .geometry(width, height, options) + .geometry(geometry) + .greenPrimary(x, y) + .gravity(direction) + .highlightColor(color) + .highlightStyle(type) + .iconGeometry(geometry) + .implode() + .implode(factor) + .intent(type) + .interlace(type) + .label(name) + .lat(width, height, offset) + .lat(width, height, offset, usePercent) + .level(blackPoint, gamma, whitePoint) + .level(blackPoint, gamma, whitePoint, usePercent) + .limit(type, limit) + .list(type) + .log(format) + .loop(iterations) + .lower(width, height) + .magnify(factor) + .map(file) + .mask(file) + .matte() + .matteColor(color) + .maximumError(count) + .median() + .median(radius) + .minify(factor) + .mode(type) + .modulate(b, s, h) + .monitor() + .monochrome() + .morph(src, dest) + .morph(src, dest, (err, stdout, stderr, cmd) => { + }) + .morph(images, dest) + .morph(images, dest, (err, stdout, stderr, cmd) => { + }) + .mosaic() + .motionBlur(radius) + .motionBlur(radius, sigma) + .motionBlur(radius, sigma, angle) + .name() + .negative() + .noise(type) + .noise(radius) + .noop() + .normalize() + .opaque(color) + .operator(channel, operator, factor) + .operator(channel, operator, factor, usePercent) + .orderedDither(channel, NxN) + .outputDirectory(dest) + .page(width, height) + .page(width, height, options) + .pause(time) + .pen(color) + .ping() + .pointSize(size) + .noProfile() + .preview(type) + .paint(radius) + .process(command) + .profile(file) + .progress() + .randomThreshold(channel, NxN) + .quality(factor) + .raise(width, height) + .recolor(matrix) + .redPrimary(x, y) + .region(width, height) + .region(width, height, x, y) + .remote() + .render() + .repage('+') + .repage(width, height, x, y) + .repage(width, height, x, y, options) + .sample(geometry) + .samplingFactor(factor, factor) + .rawSize(width, height) + .rawSize(width, height, offset) + .resample(width, height) + .resize(width, height) + .resize(width, height, options) + .roll(x, y) + .rotate(color, angle) + .scene(index) + .scenes(index, index) + .scale(width, height) + .screen() + .segment(threshold, threshold) + .sepia() + .set(attribute, attrValue) + .setFormat(format) + .shade(angle, distance) + .shadow(radius) + .shadow(radius, sigma) + .sharedMemory() + .shave(width, height) + .shave(width, height, usePercent) + .sharpen(radius) + .sharpen(radius, sigma) + .shear(angle, angle) + .silent() + .snaps(count) + .solarize(threshold) + .spread(distance) + .stegano(offset) + .stereo() + .strip() + .swirl(angle) + .textFont(font) + .threshold(threshold) + .threshold(threshold, usePercent) + .thumb(width, height, dest, (err, stdout, stderr, cmd) => { + }) + .thumb(width, height, dest, quality, (err, stdout, stderr, cmd) => { + }) + .thumb(width, height, dest, quality, align, (err, stdout, stderr, cmd) => { + }) + .tile(file) + .title(name) + .transform(color) + .transparent(color) + .treeDepth(depth) + .trim() + .type(type) + .update(time) + .units(type) + .unsharp(radius) + .unsharp(radius, sigma) + .unsharp(radius, sigma, factor) + .unsharp(radius, sigma, factor, threshold) + .usePixmap() + .view() + .virtualPixel(method) + .visual(type) + .watermark(b, s) + .wave(factor, distance) + .whitePoint(x, y) + .whiteThreshold(intensity) + .whiteThreshold(r, g, b) + .whiteThreshold(r, g, b, opacity) + .window(name) + .windowGroup() + .color((err, color) => { + }) + .depth((err, bitdepth) => { + }) + .filesize((err, size) => { + }) + .format((err, format) => { + }) + .identify((err, info) => { + }) + .res((err, resolution) => { + }) + .size((err, size) => { + }) + .orientation((err, orient) => { + }) + .draw(options) + .drawArc(x, y, x, y, radius, radius) + .drawBezier(x, y, x, y) + .drawBezier(x, y, x, y, x, y) + .drawBezier(x, y, x, y, x, y, x, y) + .drawCircle(x, y, x, y) + .drawEllipse(x, y, radius, radius, radius, radius) + .drawLine(x, y, x, y) + .drawPoint(x, y) + .drawPolygon(x, y, x, y, x, y) + .drawPolygon(x, y, x, y, x, y, x, y) + .drawPolyline(x, y, x, y, x, y) + .drawPolyline(x, y, x, y, x, y, x, y) + .drawRectangle(x, y, x, y) + .drawRectangle(x, y, x, y, radius) + .drawRectangle(x, y, x, y, radius, radius) + .drawText(x, y, name, direction) + .fill(color) + .font(font) + .font(font, size) + .fontSize(size) + .stroke(color) + .stroke(color, width) + .setDraw(type, x, y, method) + .write(dest, (err, stdout, stderr, cmd) => { + }); + +gm.compare(file, file, (err, isEqual, equality, raw) => { +}); + +readStream = gm(src).stream(); +readStream = gm(src).stream(format); +readStream = gm(src).stream(format, (err, stdout, stderr, cmd) => { +}); + +gm(src).toBuffer((err, buffer) => { +}); +gm(src).toBuffer(format, (err, buffer) => { +}); + +var imageMagick = gm.subClass({ imageMagick: true }); +var readStream = imageMagick(src) + .adjoin() + .stream(); diff --git a/gm/gm.d.ts b/gm/gm.d.ts new file mode 100644 index 000000000..2373300fe --- /dev/null +++ b/gm/gm.d.ts @@ -0,0 +1,623 @@ +// Type definitions for gm 1.17.0 +// Project: https://github.com/aheckmann/gm +// Definitions by: Joel Spadin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gm" { + import stream = require('stream'); + + function m(image: string): m.State; + + module m { + export interface ClassOptions { + imageMagick?: boolean; + } + + export interface CompareCallback { + (err: Error, isEqual: boolean, equality: number, raw: number): any; + } + + export interface GetterCallback { + (err: Error, value: T): any; + } + + export interface WriteCallback { + (err: Error, stdout: string, stderr: string, cmd: string): any; + } + + export interface ChannelInfo { + Red: T; + Green: T; + Blue: T; + } + + export interface CompareOptions { + file?: string; + highlightColor?: string; + highlightStyle?: string; + tolerance?: number; + } + + export interface ColorStatistics { + Minimum: string; + Maximum: string; + Mean: string; + 'Standard Deviation': string; + } + + export interface Dimensions { + width: number; + height: number; + } + + export interface ImageInfo { + 'Background Color': string; + 'Border Color': string; + 'Channel Depths': ChannelInfo; + 'Channel Statistics': ChannelInfo; + Class: string; + color: number; + Compose: string; + Compression: string; + depth: number; + Depth: string; + Dispose: string; + Filesize: string; + format: string; + Format: string; + Geometry: string; + Interlace: string; + Iterations: string; + 'JPEG-Quality'?: string; + 'JPEG-Colorspace'?: string; + 'JPEG-Colorspace-Name'?: string; + 'JPEG-Sampling-factors'?: string; + 'Matte Color': string; + Orientation: string; + 'Page geometry': string; + path: string; + + 'Profile-color'?: string; + 'Profile-iptc'?: { + [key: string]: string; + }; + 'Profile-EXIF'?: { + [key: string]: string; + }; + 'Profile-XMP'?: string; + Resolution?: string; + size: Dimensions; + Signature: string; + Software: string; + Tainted: string; + Type: string; + } + + export interface State { + // Image Operations + adjoin(): State; + affine(matrix: string): State; + antialias(enable: boolean): State; + append(image: string, ltr?: boolean): State; + authenticate(password: string): State; + autoOrient(): State; + backdrop(): State; + bitdepth(bits: number): State; + blackThreshold(intensity: number): State; + blackThreshold(red: number, green: number, blue: number, opacity?: number): State; + bluePrimary(x: number, y: number): State; + blur(radius: number, sigma?: number): State; + border(width: number, height: number): State; + borderColor(color: string): State; + box(color: string): State; + channel(type: 'Red'): State; + channel(type: 'Green'): State; + channel(type: 'Blue'): State; + channel(type: 'Opacity'): State; + channel(type: 'Matte'): State; + channel(type: 'Cyan'): State; + channel(type: 'Magenta'): State; + channel(type: 'Yellow'): State; + channel(type: 'Black'): State; + channel(type: 'Gray'): State; + channel(type: string): State; + charcoal(factor: number): State; + chop(width: number, height: number, x?: number, y?: number): State; + clip(): State; + coalesce(): State; + colorize(red: number, green: number, blue: number): State; + colorMap(type: 'shared'): State; + colorMap(type: 'private'): State; + colorMap(type: string): State; + colors(colors: number): State; + colorspace(space: 'CineonLog'): State; + colorspace(space: 'CMYK'): State; + colorspace(space: 'GRAY'): State; + colorspace(space: 'HSL'): State; + colorspace(space: 'HSB'): State; + colorspace(space: 'OHTA'): State; + colorspace(space: 'RGB'): State; + colorspace(space: 'Rec601Luma'): State; + colorspace(space: 'Rec709Luma'): State; + colorspace(space: 'Rec601YCbCr'): State; + colorspace(space: 'Rec709YCbCr'): State; + colorspace(space: 'Transparent'): State; + colorspace(space: 'XYZ'): State; + colorspace(space: 'YCbCr'): State; + colorspace(space: 'YIQ'): State; + colorspace(space: 'YPbPr'): State; + colorspace(space: 'YUV'): State; + colorspace(space: string): State; + compose(operator: 'Over'): State; + compose(operator: 'In'): State; + compose(operator: 'Out'): State; + compose(operator: 'Atop'): State; + compose(operator: 'Xor'): State; + compose(operator: 'Plus'): State; + compose(operator: 'Minus'): State; + compose(operator: 'Add'): State; + compose(operator: 'Subtract'): State; + compose(operator: 'Difference'): State; + compose(operator: 'Divide'): State; + compose(operator: 'Multiply'): State; + compose(operator: 'Bumpmap'): State; + compose(operator: 'Copy'): State; + compose(operator: 'CopyRed'): State; + compose(operator: 'CopyGreen'): State; + compose(operator: 'CopyBlue'): State; + compose(operator: 'CopyOpacity'): State; + compose(operator: 'CopyCyan'): State; + compose(operator: 'CopyMagenta'): State; + compose(operator: 'CopyYellow'): State; + compose(operator: 'CopyBlack'): State; + compose(operator: string): State; + compress(type: 'None'): State; + compress(type: 'BZip'): State; + compress(type: 'Fax'): State; + compress(type: 'Group4'): State; + compress(type: 'JPEG'): State; + compress(type: 'Lossless'): State; + compress(type: 'LZW'): State; + compress(type: 'RLE'): State; + compress(type: 'Zip'): State; + compress(type: 'LZMA'): State; + compress(type: string): State; + contrast(multiplier: number): State; + convolve(kernel: string): State; + createDirectories(): State; + crop(width: number, height: number, x?: number, y?: number, percent?: boolean): State; + cycle(amount: number): State; + deconstruct(): State; + define(): State; + delay(milliseconds: number): State; + density(width: number, height: number): State; + despeckle(): State; + displace(horizontal: number, vertical: number): State; + display(xServer: string): State; + dispose(method: 'Undefined'): State; + dispose(method: 'None'): State; + dispose(method: 'Background'): State; + dispose(method: 'Previous'): State; + dispose(method: string): State; + dissolve(percent: number): State; + dither(enable?: boolean): State; + edge(radius?: number): State; + emboss(radius?: number): State; + encoding(encoding: 'AdobeCustom'): State; + encoding(encoding: 'AdobeExpert'): State; + encoding(encoding: 'AdobeStandard'): State; + encoding(encoding: 'AppleRoman'): State; + encoding(encoding: 'BIG5'): State; + encoding(encoding: 'GB2312'): State; + encoding(encoding: 'Latin 2'): State; + encoding(encoding: 'None'): State; + encoding(encoding: 'SJIScode'): State; + encoding(encoding: 'Symbol'): State; + encoding(encoding: 'Unicode'): State; + encoding(encoding: 'Wansung'): State; + encoding(encoding: string): State; + endian(type: 'MSB'): State; + endian(type: 'LSB'): State; + endian(type: 'Native'): State; + endian(type: string): State; + enhance(): State; + equalize(): State; + extent(width: number, height: number, options?: string): State; + file(filename: string): State; + filter(type: 'Point'): State; + filter(type: 'Box'): State; + filter(type: 'Triangle'): State; + filter(type: 'Hermite'): State; + filter(type: 'Hanning'): State; + filter(type: 'Hamming'): State; + filter(type: 'Blackman'): State; + filter(type: 'Gaussian'): State; + filter(type: 'Quadratic'): State; + filter(type: 'Cubic'): State; + filter(type: 'Catrom'): State; + filter(type: 'Mitchell'): State; + filter(type: 'Lanczos'): State; + filter(type: 'Bessel'): State; + filter(type: 'Sinc'): State; + filter(type: string): State; + flatten(): State; + flip(): State; + flop(): State; + foreground(color: string): State; + frame(width: number, height: number, outerBevelWidth: number, outBevelHeight: number): State; + fuzz(distance: number, percent?: boolean): State; + gamma(r: number, g: number, b: number): State; + gaussian(radius: number, sigma?: number): State; + /** Width and height are specified in percents */ + geometry(width: number, height: number, option: '%'): State; + /** Specify maximum area in pixels */ + geometry(width: number, height: number, option: '@'): State; + /** Ignore aspect ratio */ + geometry(width: number, height: number, option: '!'): State; + /** Width and height are minimum values */ + geometry(width: number, height: number, option: '^'): State; + /** Change dimensions only if image is smaller than width or height */ + geometry(width: number, height: number, option: '<'): State; + /** Change dimensions only if image is larger than width or height */ + geometry(width: number, height: number, option: '>'): State; + geometry(width: number, height?: number, option?: string): State; + geometry(geometry: string): State; + greenPrimary(x: number, y: number): State; + gravity(direction: 'NorthWest'): State; + gravity(direction: 'North'): State; + gravity(direction: 'NorthEast'): State; + gravity(direction: 'West'): State; + gravity(direction: 'Center'): State; + gravity(direction: 'East'): State; + gravity(direction: 'SouthWest'): State; + gravity(direction: 'South'): State; + gravity(direction: 'SouthEast'): State; + gravity(direction: string): State; + highlightColor(color: string): State; + highlightStyle(style: 'Assign'): State; + highlightStyle(style: 'Threshold'): State; + highlightStyle(style: 'Tint'): State; + highlightStyle(style: 'XOR'): State; + highlightStyle(style: string): State; + iconGeometry(geometry: string): State; + implode(factor?: number): State; + intent(type: 'Absolute'): State; + intent(type: 'Perceptual'): State; + intent(type: 'Relative'): State; + intent(type: 'Saturation'): State; + intent(type: string): State; + interlace(type: 'None'): State; + interlace(type: 'Line'): State; + interlace(type: 'Plane'): State; + interlace(type: 'Partition'): State; + interlace(type: string): State; + label(name: string): State; + lat(width: number, height: number, offset: number, percent?: boolean): State; + level(blackPoint: number, gamma: number, whitePoint: number, percent?: boolean): State; + limit(type: 'disk', val: string): State; + limit(type: 'file', val: string): State; + limit(type: 'map', val: string): State; + limit(type: 'memory', val: string): State; + limit(type: 'pixels', val: string): State; + limit(type: 'threads', val: string): State; + limit(type: string, val: string): State; + list(type: string): State; + list(type: 'Color'): State; + list(type: 'Delegate'): State; + list(type: 'Format'): State; + list(type: 'Magic'): State; + list(type: 'Module'): State; + list(type: 'Resource'): State; + list(type: 'Type'): State; + log(format: string): State; + loop(iterations: number): State; + lower(width: number, height: number): State; + magnify(factor: number): State; + map(filename: string): State; + mask(filename: string): State; + matte(): State; + matteColor(color: string): State; + maximumError(limit: number): State; + median(radius?: number): State; + minify(factor: number): State; + mode(mode: 'frame'): State; + mode(mode: 'unframe'): State; + mode(mode: 'concatenate'): State; + mode(mode: string): State; + modulate(b: number, s: number, h: number): State; + monitor(): State; + monochrome(): State; + morph(otherImg: string, outName: string, callback?: WriteCallback): State; + morph(otherImg: string[], outName: string, callback?: WriteCallback): State; + mosaic(): State; + motionBlur(radius: number, sigma?: number, angle?: number): State; + name(): State; + negative(): State; + noise(type: 'uniform'): State; + noise(type: 'gaussian'): State; + noise(type: 'multiplicative'): State; + noise(type: 'impulse'): State; + noise(type: 'laplacian'): State; + noise(type: 'poisson'): State; + noise(type: string): State; + noise(radius: number): State; + noop(): State; + normalize(): State; + opaque(color: string): State; + operator(channel: string, operator: 'Add', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'And', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Assign', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Depth', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Divide', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Gamma', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Negate', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'LShift', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Log', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Max', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Min', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Multiply', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Or', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Pow', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'RShift', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Subtract', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Threshold', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Threshold-White', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Threshold-White-Negate', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Threshold-Black', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Threshold-Black-Negate', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Xor', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Noise-Gaussian', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Noise-Impulse', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Noise-Laplacian', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Noise-Multiplicative', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Noise-Poisson', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Noise-Random', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: 'Noise-Uniform', rvalue: number, percent?: boolean): State; + operator(channel: string, operator: string, rvalue: number, percent?: boolean): State; + orderedDither(channelType: 'All', NxN: string): State; + orderedDither(channelType: 'Intensity', NxN: string): State; + orderedDither(channelType: 'Red', NxN: string): State; + orderedDither(channelType: 'Green', NxN: string): State; + orderedDither(channelType: 'Blue', NxN: string): State; + orderedDither(channelType: 'Cyan', NxN: string): State; + orderedDither(channelType: 'Magenta', NxN: string): State; + orderedDither(channelType: 'Yellow', NxN: string): State; + orderedDither(channelType: 'Black', NxN: string): State; + orderedDither(channelType: 'Opacity', NxN: string): State; + orderedDither(channelType: string, NxN: string): State; + outputDirectory(directory: string): State; + page(width: number, height: number, arg?: '%'): State; + page(width: number, height: number, arg?: '!'): State; + page(width: number, height: number, arg?: '<'): State; + page(width: number, height: number, arg?: '>'): State; + page(width: number, height: number, arg?: string): State; + pause(seconds: number): State; + pen(color: string): State; + ping(): State; + pointSize(size: number): State; + noProfile(): State; + preview(type: 'Rotate'): State; + preview(type: 'Shear'): State; + preview(type: 'Roll'): State; + preview(type: 'Hue'): State; + preview(type: 'Saturation'): State; + preview(type: 'Brightness'): State; + preview(type: 'Gamma'): State; + preview(type: 'Spiff'): State; + preview(type: 'Dull'): State; + preview(type: 'Grayscale'): State; + preview(type: 'Quantize'): State; + preview(type: 'Despeckle'): State; + preview(type: 'ReduceNoise'): State; + preview(type: 'AddNoise'): State; + preview(type: 'Sharpen'): State; + preview(type: 'Blur'): State; + preview(type: 'Threshold'): State; + preview(type: 'EdgeDetect'): State; + preview(type: 'Spread'): State; + preview(type: 'Shade'): State; + preview(type: 'Raise'): State; + preview(type: 'Segment'): State; + preview(type: 'Solarize'): State; + preview(type: 'Swirl'): State; + preview(type: 'Implode'): State; + preview(type: 'Wave'): State; + preview(type: 'OilPaint'): State; + preview(type: 'CharcoalDrawing'): State; + preview(type: 'JPEG'): State; + preview(type: string): State; + paint(radius: number): State; + process(command: string): State; + profile(filename: string): State; + progress(): State; + randomThreshold(channelType: 'All', LOWxHIGH: string): State; + randomThreshold(channelType: 'Intensity', LOWxHIGH: string): State; + randomThreshold(channelType: 'Red', LOWxHIGH: string): State; + randomThreshold(channelType: 'Green', LOWxHIGH: string): State; + randomThreshold(channelType: 'Blue', LOWxHIGH: string): State; + randomThreshold(channelType: 'Cyan', LOWxHIGH: string): State; + randomThreshold(channelType: 'Magenta', LOWxHIGH: string): State; + randomThreshold(channelType: 'Yellow', LOWxHIGH: string): State; + randomThreshold(channelType: 'Black', LOWxHIGH: string): State; + randomThreshold(channelType: 'Opacity', LOWxHIGH: string): State; + randomThreshold(channelType: string, LOWxHIGH: string): State; + quality(level: number): State; + raise(width: number, height: number): State; + recolor(matrix: string): State; + redPrimary(x: number, y: number): State; + region(width: number, height: number, x?: number, y?: number): State; + remote(): State; + render(): State; + repage(reset: '+'): State; + repage(reset: string): State; + repage(width: number, height: number, xoff: number, yoff: number, arg?: string): State; + sample(geometry: string): State; + samplingFactor(horizontalFactor: number, verticalFactor: number): State; + rawSize(width: number, height: number, offset?: number): State; + resample(horizontal: number, vertical: number): State; + /** Width and height are specified in percents */ + resize(width: number, height: number, option: '%'): State; + /** Specify maximum area in pixels */ + resize(width: number, height: number, option: '@'): State; + /** Ignore aspect ratio */ + resize(width: number, height: number, option: '!'): State; + /** Width and height are minimum values */ + resize(width: number, height: number, option: '^'): State; + /** Change dimensions only if image is smaller than width or height */ + resize(width: number, height: number, option: '<'): State; + /** Change dimensions only if image is larger than width or height */ + resize(width: number, height: number, option: '>'): State; + resize(width: number, height?: number, option?: string): State; + roll(horizontal: number, vertical: number): State; + rotate(backgroundColor: string, degrees: number): State; + scene(index: number): State; + scenes(start: number, end: number): State; + scale(width: number, height: number): State; + screen(): State; + segment(clustherThreshold: number, smoothingThreshold: number): State; + sepia(): State; + set(attribute: string, value: string): State; + setFormat(format: string): State; + shade(azimuth: number, elevation: number): State; + shadow(radius: number, sigma?: number): State; + sharedMemory(): State; + shave(width: number, height: number, percent?: boolean): State; + sharpen(radius: number, sigma?: number): State; + shear(xDegrees: number, yDegress: number): State; + silent(): State; + snaps(count: number): State; + solarize(threshold: number): State; + spread(amount: number): State; + stegano(offset: number): State; + stereo(): State; + strip(): State; + swirl(degrees: number): State; + textFont(font: string): State; + threshold(value: number, percent?: boolean): State; + thumb(width: number, height: number, outName: string, callback: WriteCallback): State; + thumb(width: number, height: number, outName: string, quality: number, callback: WriteCallback): State; + thumb(width: number, height: number, outName: string, quality: number, align: 'topleft', callback: WriteCallback): State; + thumb(width: number, height: number, outName: string, quality: number, align: 'center', callback: WriteCallback): State; + thumb(width: number, height: number, outName: string, quality: number, align: string, callback: WriteCallback): State; + tile(filename: string): State; + title(title: string): State; + transform(color: string): State; + transparent(color: string): State; + treeDepth(depth: number): State; + trim(): State; + type(type: 'Bilevel'): State; + type(type: 'Grayscale'): State; + type(type: 'Palette'): State; + type(type: 'PaletteMatte'): State; + type(type: 'TrueColor'): State; + type(type: 'TrueColorMatte'): State; + type(type: 'ColorSeparation'): State; + type(type: 'ColorSeparationMatte'): State; + type(type: 'Optimize'): State; + type(type: string): State; + update(seconds: number): State; + units(type: 'Undefined'): State; + units(type: 'PixelsPerInch'): State; + units(type: 'PixelsPerCentimeter'): State; + units(type: string): State; + unsharp(radius: number, sigma?: number, amount?: number, threshold?: number): State; + usePixmap(): State; + view(): State; + virtualPixel(method: 'Constant'): State; + virtualPixel(method: 'Edge'): State; + virtualPixel(method: 'Mirror'): State; + virtualPixel(method: 'Tile'): State; + virtualPixel(method: string): State; + visual(type: 'StaticGray'): State; + visual(type: 'GrayScale'): State; + visual(type: 'StaticColor'): State; + visual(type: 'PseudoColor'): State; + visual(type: 'TrueColor'): State; + visual(type: 'DirectColor'): State; + visual(type: 'default'): State; + visual(type: string): State; + watermark(brightness: number, saturation: number): State; + wave(amplitude: number, wavelength: number): State; + whitePoint(x: number, y: number): State; + whiteThreshold(intensity: number): State; + whiteThreshold(red: number, green: number, blue: number, opacity?: number): State; + window(id: string): State; + windowGroup(): State; + + // Getters + color(callback: GetterCallback): State; + depth(callback: GetterCallback): State; + filesize(callback: GetterCallback): State; + format(callback: GetterCallback): State; + identify(callback: GetterCallback): State; + res(callback: GetterCallback): State; + size(callback: GetterCallback): State; + orientation(callback: GetterCallback): State; + + // Drawing Operations + draw(args: string): State; + drawArc(x0: number, y0: number, x1: number, y1: number, r0: number, r1: number): State; + drawBezier(x0: number, y0: number, x1: number, y1: number): State; + drawBezier(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): State; + drawBezier(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, ...coords: number[]): State; + drawCircle(x0: number, y0: number, x1: number, y1: number): State; + drawEllipse(x0: number, y0: number, rx: number, ry: number, a0: number, a1: number): State; + drawLine(x0: number, y0: number, x1: number, y1: number): State; + drawPoint(x: number, y: number): State; + drawPolygon(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): State; + drawPolygon(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, ...coords: number[]): State; + drawPolyline(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number): State; + drawPolyline(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, ...coords: number[]): State; + drawRectangle(x0: number, y0: number, x1: number, y1: number): State; + drawRectangle(x0: number, y0: number, x1: number, y1: number, rc: number): State; + drawRectangle(x0: number, y0: number, x1: number, y1: number, wc: number, hc: number): State; + drawText(x: number, y: number, text: string, gravity: 'NorthWest'): State; + drawText(x: number, y: number, text: string, gravity: 'North'): State; + drawText(x: number, y: number, text: string, gravity: 'NorthEast'): State; + drawText(x: number, y: number, text: string, gravity: 'West'): State; + drawText(x: number, y: number, text: string, gravity: 'Center'): State; + drawText(x: number, y: number, text: string, gravity: 'East'): State; + drawText(x: number, y: number, text: string, gravity: 'SouthWest'): State; + drawText(x: number, y: number, text: string, gravity: 'South'): State; + drawText(x: number, y: number, text: string, gravity: 'SouthEast'): State; + drawText(x: number, y: number, text: string, gravity?: string): State; + fill(color: string): State; + font(name: string, size?: number): State; + fontSize(size: number): State; + stroke(color: string, width?: number): State; + strokeWidth(width: number): State; + setDraw(property: 'color', x: number, y: number, method: 'point'): State; + setDraw(property: 'color', x: number, y: number, method: 'replace'): State; + setDraw(property: 'color', x: number, y: number, method: 'floodfill'): State; + setDraw(property: 'color', x: number, y: number, method: 'filltoborder'): State; + setDraw(property: 'color', x: number, y: number, method: 'reset'): State; + setDraw(property: 'matte', x: number, y: number, method: 'point'): State; + setDraw(property: 'matte', x: number, y: number, method: 'replace'): State; + setDraw(property: 'matte', x: number, y: number, method: 'floodfill'): State; + setDraw(property: 'matte', x: number, y: number, method: 'filltoborder'): State; + setDraw(property: 'matte', x: number, y: number, method: 'reset'): State; + setDraw(property: string, x: number, y: number, method: string): State; + + // Commands + stream(callback?: WriteCallback): stream.PassThrough; + stream(format: string, callback?: WriteCallback): stream.PassThrough; + toBuffer(callback: (err: Error, buffer: Buffer) => any): stream.PassThrough; + toBuffer(format: string, callback: (err: Error, buffer: Buffer) => any): stream.PassThrough; + write(filename: string, callback: WriteCallback): void; + } + + export interface SubClass { + (image: string): State; + } + + export function compare(filename1: string, filename2: string, callback: CompareCallback): void; + export function compare(filename1: string, filename2: string, tolerance: number, callback: CompareCallback): void; + export function compare(filename1: string, filename2: string, options: CompareOptions, callback: CompareCallback): void; + + export function subClass(options: ClassOptions): SubClass; + } + + export = m; +} diff --git a/hammerjs/hammerjs-1.1.3-tests.ts b/hammerjs/hammerjs-1.1.3-tests.ts new file mode 100644 index 000000000..42c5ccea3 --- /dev/null +++ b/hammerjs/hammerjs-1.1.3-tests.ts @@ -0,0 +1,49 @@ +/// +/// + +// plugin check +if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) { + Hammer.plugins.fakeMultitouch(); + Hammer.plugins.showTouches(); +} + +// instance method check +var el = document.getElementById("container"); + +Hammer(el).on("doubletap", function () { + alert('you doubletapped me!'); +}); + +var hammertime = Hammer(el, { + drag: false, + transform: false +}).off("tap", function (event:HammerEvent) { + alert('hello!'); +}); + +hammertime.enable(false); + +hammertime.on("touch drag transform", function (ev: HammerEvent) { + if (!ev.gesture) { + return; + } + + if (ev.gesture.deltaX >= 20) { + hammertime.trigger("swipe", ev.gesture); + } +}); + +// jQuery check +$("#element") + .hammer({ + // Options + }) + .on("tap", function (ev) { + console.log(ev); + }); + +$("#container").hammer({ + prevent_default: false, + drag_block_vertical: false +}).on("hold tap doubletap transformstart transform transformend dragstart drag dragend release swipe", function (ev) { +}); \ No newline at end of file diff --git a/hammerjs/hammerjs-1.1.3.d.ts b/hammerjs/hammerjs-1.1.3.d.ts new file mode 100644 index 000000000..4e7f69306 --- /dev/null +++ b/hammerjs/hammerjs-1.1.3.d.ts @@ -0,0 +1,142 @@ +// Type definitions for Hammer.js 1.1.3 +// Project: http://eightmedia.github.com/hammer.js/ +// Definitions by: Boris Yankov , Drew Noakes +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare var Hammer: HammerStatic; + +interface HammerStatic { + (element: any, options?: HammerOptions): HammerInstance; + + VERSION: number; + HAS_POINTEREVENTS: boolean; + HAS_TOUCHEVENTS: boolean; + UPDATE_VELOCITY_INTERVAL: number; + POINTER_MOUSE: HammerPointerType; + POINTER_TOUCH: HammerPointerType; + POINTER_PEN: HammerPointerType; + + DIRECTION_UP: HammerDirectionType; + DIRECTION_DOWN: HammerDirectionType; + DIRECTION_LEFT: HammerDirectionType; + DIRECTION_RIGH: HammerDirectionType; + + EVENT_START: HammerTouchEventState; + EVENT_MOVE: HammerTouchEventState; + EVENT_END: HammerTouchEventState; + + plugins: any; + gestures: any; + READY: boolean; +} + +declare class HammerInstance { + constructor(element: any, options?: HammerOptions); + + on(gesture: string, handler: (event: HammerEvent) => void): HammerInstance; + off(gesture: string, handler: (event: HammerEvent) => void): HammerInstance; + enable(toggle: boolean): HammerInstance; + + // You shouldn't normally use this internal method. Only use it when you know what you're doing! You can read the sourcecode for information about how to use this. + trigger(gesture: string, eventData: HammerGestureEventData): HammerInstance; +} + +// Gesture Options : https://github.com/EightMedia/hammer.js/wiki/Getting-Started#gesture-options +interface HammerOptions { + behavior?: { + contentZooming?: string; + tapHighlightColor?: string; + touchAction?: string; + touchCallout?: string; + userDrag?: string; + userSelect?: string; + }; + doubleTapDistance?: number; + doubleTapInterval?: number; + drag?: boolean; + dragBlockHorizontal?: boolean; + dragBlockVertical?: boolean; + dragDistanceCorrection?: boolean; + dragLockMinDistance?: number; + dragLockToAxis?: boolean; + dragMaxTouches?: number; + dragMinDistance?: number; + gesture?: boolean; + hold?: boolean; + holdThreshold?: number; + holdTimeout?: number; + preventDefault?: boolean; + preventMouse?: boolean; + release?: boolean; + showTouches?: boolean; + swipe?: boolean; + swipeMaxTouches?: number; + swipeMinTouches?: number; + swipeVelocityX?: number; + swipeVelocityY?: number; + tap?: boolean; + tapAlways?: boolean; + tapMaxDistance?: number; + tapMaxTime?: number; + touch?: boolean; + transform?: boolean; + transformMinRotation?: number; + transformMinScale?: number; +} + +interface HammerGestureEventData { + timestamp: number; + target: HTMLElement; + touches: HammerPoint[]; + pointerType: HammerPointerType; + center: HammerPoint; + deltaTime: number; + deltaX: number; + deltaY: number; + velocityX: number; + velocityY: number; + angle: number; + interimAngle: number; + direction: HammerDirectionType; + interimDirection: HammerDirectionType; + distance: number; + scale: number; + rotation: number; + eventType: HammerTouchEventState; + srcEvent: any; + startEvent: any; + + stopPropagation(): void; + preventDefault(): void; + stopDetect(): void; +} + +interface HammerPoint { + clientX: number; + clientY: number; + pageX: number; + pageY: number; +} + +interface HammerEvent { + type: string; + gesture: HammerGestureEventData; + + stopPropagation(): void; + preventDefault(): void; + +} + +declare enum HammerPointerType { +} +declare enum HammerDirectionType { +} +declare enum HammerTouchEventState { +} + +interface JQuery { + hammer(options?: HammerOptions): JQuery; +} diff --git a/hammerjs/hammerjs-tests.ts b/hammerjs/hammerjs-tests.ts index 23fa92d4d..a17c16287 100644 --- a/hammerjs/hammerjs-tests.ts +++ b/hammerjs/hammerjs-tests.ts @@ -1,49 +1,115 @@ -/// -/// - -// plugin check -if (!Hammer.HAS_TOUCHEVENTS && !Hammer.HAS_POINTEREVENTS) { - Hammer.plugins.fakeMultitouch(); - Hammer.plugins.showTouches(); -} - -// instance method check -var el = document.getElementById("container"); - -Hammer(el).on("doubletap", function () { - alert('you doubletapped me!'); -}); - -var hammertime = Hammer(el, { - drag: false, - transform: false -}).off("tap", function (event:HammerEvent) { - alert('hello!'); -}); - -hammertime.enable(false); - -hammertime.on("touch drag transform", function (ev: HammerEvent) { - if (!ev.gesture) { - return; - } - - if (ev.gesture.deltaX >= 20) { - hammertime.trigger("swipe", ev.gesture); - } -}); - -// jQuery check -$("#element") - .hammer({ - // Options - }) - .on("tap", function (ev) { - console.log(ev); - }); - -$("#container").hammer({ - prevent_default: false, - drag_block_vertical: false -}).on("hold tap doubletap transformstart transform transformend dragstart drag dragend release swipe", function (ev) { -}); \ No newline at end of file +// Tests based on examples at http://hammerjs.github.io/examples/ + +/// + +(() => +{ + var myElement = document.getElementById( 'myElement' ); + + // create a simple instance + // by default, it only adds horizontal recognizers + var mc = new Hammer( myElement ); + + // listen to events... + mc.on( "panleft panright tap press", function ( ev ) + { + myElement.textContent = ev.type + " gesture detected."; + } ); +})(); + + +(() => +{ + var myElement = document.getElementById( 'myElement' ); + + // create a simple instance + // by default, it only adds horizontal recognizers + var mc = new Hammer( myElement ); + + // let the pan gesture support all directions. + // this will block the vertical scrolling on a touch-device while on the element + mc.get( 'pan' ).set( {direction: Hammer.DIRECTION_ALL} ); + + // listen to events... + mc.on( "panleft panright panup pandown tap press", function ( ev:HammerInput ) + { + myElement.textContent = ev.type + " gesture detected."; + } ); +})(); + + +(() => +{ + var myElement = document.getElementById( 'myElement' ); + + var mc = new Hammer.Manager( myElement ); + + // create a pinch and rotate recognizer + // these require 2 pointers + var pinch = new Hammer.Pinch(); + var rotate = new Hammer.Rotate(); + + // we want to detect both the same time + pinch.recognizeWith( rotate ); + + // add to the Manager + mc.add( [pinch, rotate] ); + + + mc.on( "pinch rotate", function ( ev:HammerInput ) + { + myElement.textContent += ev.type + " "; + } ); +})(); + + +(() => +{ + var myElement = document.getElementById( 'myElement' ); + + // We create a manager object, which is the same as Hammer(), but without the presetted recognizers. + var mc = new Hammer.Manager( myElement ); + + // Default, tap recognizer + mc.add( new Hammer.Tap() ); + + // Tap recognizer with minimal 4 taps + mc.add( new Hammer.Tap( {event: 'quadrupletap', taps: 4} ) ); + + // we want to recognize this simulatenous, so a quadrupletap will be detected even while a tap has been recognized. + // the tap event will be emitted on every tap + mc.get( 'quadrupletap' ).recognizeWith( 'tap' ); + + + mc.on( "tap quadrupletap", function ( ev ) + { + myElement.textContent += ev.type + " "; + } ); +})(); + + +(() => +{ + var myElement = document.getElementById( 'myElement' ); + + // We create a manager object, which is the same as Hammer(), but without the presetted recognizers. + var mc = new Hammer.Manager( myElement ); + + + // Tap recognizer with minimal 2 taps + mc.add( new Hammer.Tap( {event: 'doubletap', taps: 2} ) ); + // Single tap recognizer + mc.add( new Hammer.Tap( {event: 'singletap'} ) ); + + + // we want to recognize this simulatenous, so a quadrupletap will be detected even while a tap has been recognized. + mc.get( 'doubletap' ).recognizeWith( 'singletap' ); + // we only want to trigger a tap, when we don't have detected a doubletap + mc.get( 'singletap' ).requireFailure( 'doubletap' ); + + + mc.on( "singletap doubletap", function ( ev ) + { + myElement.textContent += ev.type + " "; + } ); +})(); \ No newline at end of file diff --git a/hammerjs/hammerjs.d.ts b/hammerjs/hammerjs.d.ts index 6f4c0d4ce..a3a7aed42 100644 --- a/hammerjs/hammerjs.d.ts +++ b/hammerjs/hammerjs.d.ts @@ -1,142 +1,327 @@ -// Type definitions for Hammer.js 1.1.3 -// Project: http://eightmedia.github.com/hammer.js/ -// Definitions by: Boris Yankov , Drew Noakes -// Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/// - -declare var Hammer: HammerStatic; - -interface HammerStatic { - (element: any, options?: HammerOptions): HammerInstance; - - VERSION: number; - HAS_POINTEREVENTS: boolean; - HAS_TOUCHEVENTS: boolean; - UPDATE_VELOCITY_INTERVAL: number; - POINTER_MOUSE: HammerPointerType; - POINTER_TOUCH: HammerPointerType; - POINTER_PEN: HammerPointerType; - - DIRECTION_UP: HammerDirectionType; - DIRECTION_DOWN: HammerDirectionType; - DIRECTION_LEFT: HammerDirectionType; - DIRECTION_RIGH: HammerDirectionType; - - EVENT_START: HammerTouchEventState; - EVENT_MOVE: HammerTouchEventState; - EVENT_END: HammerTouchEventState; - - plugins: any; - gestures: any; - READY: boolean; -} - -declare class HammerInstance { - constructor(element: any, options?: HammerOptions); - - on(gesture: string, handler: (event: HammerEvent) => void): HammerInstance; - off(gesture: string, handler: (event: HammerEvent) => void): HammerInstance; - enable(toggle: boolean): HammerInstance; - - // You shouldn't normally use this internal method. Only use it when you know what you're doing! You can read the sourcecode for information about how to use this. - trigger(gesture: string, eventData: HammerGestureEventData): HammerInstance; -} - -// Gesture Options : https://github.com/EightMedia/hammer.js/wiki/Getting-Started#gesture-options -interface HammerOptions { - behavior?: { - contentZooming?: string; - tapHighlightColor?: string; - touchAction?: string; - touchCallout?: string; - userDrag?: string; - userSelect?: string; - }; - doubleTapDistance?: number; - doubleTapInterval?: number; - drag?: boolean; - dragBlockHorizontal?: boolean; - dragBlockVertical?: boolean; - dragDistanceCorrection?: boolean; - dragLockMinDistance?: number; - dragLockToAxis?: boolean; - dragMaxTouches?: number; - dragMinDistance?: number; - gesture?: boolean; - hold?: boolean; - holdThreshold?: number; - holdTimeout?: number; - preventDefault?: boolean; - preventMouse?: boolean; - release?: boolean; - showTouches?: boolean; - swipe?: boolean; - swipeMaxTouches?: number; - swipeMinTouches?: number; - swipeVelocityX?: number; - swipeVelocityY?: number; - tap?: boolean; - tapAlways?: boolean; - tapMaxDistance?: number; - tapMaxTime?: number; - touch?: boolean; - transform?: boolean; - transformMinRotation?: number; - transformMinScale?: number; -} - -interface HammerGestureEventData { - timestamp: number; - target: HTMLElement; - touches: HammerPoint[]; - pointerType: HammerPointerType; - center: HammerPoint; - deltaTime: number; - deltaX: number; - deltaY: number; - velocityX: number; - velocityY: number; - angle: number; - interimAngle: number; - direction: HammerDirectionType; - interimDirection: HammerDirectionType; - distance: number; - scale: number; - rotation: number; - eventType: HammerTouchEventState; - srcEvent: any; - startEvent: any; - - stopPropagation(): void; - preventDefault(): void; - stopDetect(): void; -} - -interface HammerPoint { - clientX: number; - clientY: number; - pageX: number; - pageY: number; -} - -interface HammerEvent { - type: string; - gesture: HammerGestureEventData; - - stopPropagation(): void; - preventDefault(): void; - -} - -declare enum HammerPointerType { -} -declare enum HammerDirectionType { -} -declare enum HammerTouchEventState { -} - -interface JQuery { - hammer(options?: HammerOptions): JQuery; -} +// Type definitions for Hammer.js 2.0.4 +// Project: http://hammerjs.github.io/ +// Definitions by: Philip Bulley +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var Hammer:HammerStatic; + +interface HammerStatic +{ + new( element:HTMLElement, options?:any ): HammerManager; + + defaults:HammerDefaults; + + VERSION: number; + + INPUT_START: number; + INPUT_MOVE: number; + INPUT_END: number; + INPUT_CANCEL: number; + + STATE_POSSIBLE: number; + STATE_BEGAN: number; + STATE_CHANGED: number; + STATE_ENDED: number; + STATE_RECOGNIZED: number; + STATE_CANCELLED: number; + STATE_FAILED: number; + + DIRECTION_NONE: number; + DIRECTION_LEFT: number; + DIRECTION_RIGHT: number; + DIRECTION_UP: number; + DIRECTION_DOWN: number; + DIRECTION_HORIZONTAL: number; + DIRECTION_VERTICAL: number; + DIRECTION_ALL: number; + + Manager: HammerManager; + Input: HammerInput; + TouchAction: TouchAction; + + TouchInput: TouchInput; + MouseInput: MouseInput; + PointerEventInput: PointerEventInput; + TouchMouseInput: TouchMouseInput; + SingleTouchInput: SingleTouchInput; + + Recognizer: RecognizerStatic; + AttrRecognizer: AttrRecognizerStatic; + Tap: TapRecognizerStatic; + Pan: PanRecognizerStatic; + Swipe: SwipeRecognizerStatic; + Pinch: PinchRecognizerStatic; + Rotate: RotateRecognizerStatic; + Press: PressRecognizerStatic; + + on( target:EventTarget, types:string, handler:Function ):void; + off( target:EventTarget, types:string, handler:Function ):void; + each( obj:any, iterator:Function, context:any ): void; + merge( dest:any, src:any ): any; + extend( dest:any, src:any, merge:boolean ): any; + inherit( child:Function, base:Function, properties:any ):any; + bindFn( fn:Function, context:any ):Function; + prefixed( obj:any, property:string ):string; +} + +interface HammerDefaults +{ + domEvents:boolean; + enable:boolean; + preset:any[]; + touchAction:string; + cssProps:CssProps; + + inputClass():void; + inputTarget():void; +} + +interface CssProps +{ + contentZooming:string; + tapHighlightColor:string; + touchCallout:string; + touchSelect:string; + userDrag:string; + userSelect:string; +} + +interface HammerOptions extends HammerDefaults +{ + +} + +interface HammerManager +{ + new( element:HTMLElement, options?:any ):HammerManager; + + add( recogniser:Recognizer ):Recognizer; + add( recogniser:Recognizer ):HammerManager; + add( recogniser:Recognizer[] ):Recognizer; + add( recogniser:Recognizer[] ):HammerManager; + destroy():void; + emit( event:string, data:any ):void; + get( recogniser:Recognizer ):Recognizer; + get( recogniser:string ):Recognizer; + off( events:string, handler:( event:HammerInput ) => void ):void; + on( events:string, handler:( event:HammerInput ) => void ):void; + recognize( inputData:any ):void; + remove( recogniser:Recognizer ):HammerManager; + remove( recogniser:string ):HammerManager; + set( options:HammerOptions ):HammerManager; + stop( force:boolean ):void; +} + +declare class HammerInput +{ + constructor( manager:HammerManager, callback:Function ); + + destroy():void; + handler():void; + init():void; + + /** Name of the event. Like panstart. */ + type:string; + + /** Movement of the X axis. */ + deltaX:number; + + /** Movement of the Y axis. */ + deltaY:number; + + /** Total time in ms since the first input. */ + deltaTime:number; + + /** Distance moved. */ + distance:number; + + /** Angle moved. */ + angle:number; + + /** Velocity on the X axis, in px/ms. */ + velocityX:number; + + /** Velocity on the Y axis, in px/ms */ + velocityY:number; + + /** Highest velocityX/Y value. */ + velocity:number; + + /** Direction moved. Matches the DIRECTION constants. */ + direction:number; + + /** Direction moved from it's starting point. Matches the DIRECTION constants. */ + offsetDirection:string; + + /** Scaling that has been done when multi-touch. 1 on a single touch. */ + scale:number; + + /** Rotation that has been done when multi-touch. 0 on a single touch. */ + rotation:number; + + /** Center position for multi-touch, or just the single pointer. */ + center:HammerPoint; + + /** Source event object, type TouchEvent, MouseEvent or PointerEvent. */ + srcEvent:Event; // TODO: Update to Union Type (TouchEvent | MouseEvent | PointerEvent) if it lands in TS1.4 + + /** Target that received the event. */ + target:HTMLElement; + + /** Primary pointer type, could be touch, mouse, pen or kinect. */ + pointerType:string; + + /** Event type, matches the INPUT constants. */ + eventType:string; + + /** true when the first input. */ + isFirst:boolean; + + /** true when the final (last) input. */ + isFinal:boolean; + + /** Array with all pointers, including the ended pointers (touchend, mouseup). */ + pointers:any[]; + + /** Array with all new/moved/lost pointers. */ + changedPointers:any[]; + + /** Reference to the srcEvent.preventDefault() method. Only for experts! */ + preventDefault:Function; +} + +declare class MouseInput extends HammerInput +{ + constructor( manager:HammerManager, callback:Function ); +} + +declare class PointerEventInput extends HammerInput +{ + constructor( manager:HammerManager, callback:Function ); +} + +declare class SingleTouchInput extends HammerInput +{ + constructor( manager:HammerManager, callback:Function ); +} + +declare class TouchInput extends HammerInput +{ + constructor( manager:HammerManager, callback:Function ); +} + +declare class TouchMouseInput extends HammerInput +{ + constructor( manager:HammerManager, callback:Function ); +} + +interface RecognizerStatic +{ + new( options?:any ):Recognizer; +} + +interface Recognizer +{ + defaults:any; + + canEmit():boolean; + canRecognizeWith( otherRecognizer:Recognizer ):boolean; + dropRecognizeWith( otherRecognizer:Recognizer ):Recognizer; + dropRecognizeWith( otherRecognizer:string ):Recognizer; + dropRequireFailure( otherRecognizer:Recognizer ):Recognizer; + dropRequireFailure( otherRecognizer:string ):Recognizer; + emit( input:HammerInput ):void; + getTouchAction():any[]; + hasRequireFailures():boolean; + process( inputData:HammerInput ):string; + recognize( inputData:HammerInput ):void; + recognizeWith( otherRecognizer:Recognizer ):Recognizer; + recognizeWith( otherRecognizer:string ):Recognizer; + requireFailure( otherRecognizer:Recognizer ):Recognizer; + requireFailure( otherRecognizer:string ):Recognizer; + reset():void; + set( options?:any ):Recognizer; + tryEmit( input:HammerInput ):void; +} + +interface AttrRecognizerStatic +{ + attrTest( input:HammerInput ):boolean; + process( input:HammerInput ):any; +} + +interface AttrRecognizer extends Recognizer +{ + new( options?:any ):AttrRecognizer; +} + +interface PanRecognizerStatic +{ + new( options?:any ):PanRecognizer; +} + +interface PanRecognizer extends AttrRecognizer +{ +} + +interface PinchRecognizerStatic +{ + new( options?:any ):PinchRecognizer; +} + +interface PinchRecognizer extends AttrRecognizer +{ +} + +interface PressRecognizerStatic +{ + new( options?:any ):PressRecognizer; +} + +interface PressRecognizer extends AttrRecognizer +{ +} + +interface RotateRecognizerStatic +{ + new( options?:any ):RotateRecognizer; +} + +interface RotateRecognizer extends AttrRecognizer +{ +} + +interface SwipeRecognizerStatic +{ + new( options?:any ):SwipeRecognizer; +} + +interface SwipeRecognizer +{ +} + +interface TapRecognizerStatic +{ + new( options?:any ):TapRecognizer; +} + +interface TapRecognizer extends AttrRecognizer +{ +} + +declare class TouchAction +{ + constructor( manager:HammerManager, value:string ); + + compute():string; + preventDefaults( input:HammerInput ):void; + preventSrc( srcEvent:any ):void; + set( value:string ):void; + update():void; +} + +interface HammerPoint +{ + x: number; + y: number; +} diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 8b9964287..ad6140ace 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -629,6 +629,14 @@ interface JQueryCoordinates { top: number; } +/** + * Elements in the array returned by serializeArray() + */ +interface JQuerySerializeArrayElement { + name: string; + value: string; +} + interface JQueryAnimationOptions { /** * A string or number determining how long the animation will run. @@ -1321,7 +1329,7 @@ interface JQuery { /** * Encode a set of form elements as an array of names and values. */ - serializeArray(): Object[]; + serializeArray(): JQuerySerializeArrayElement[]; /** * Adds the specified class(es) to each of the set of matched elements. diff --git a/linq/linq.d.ts b/linq/linq.d.ts index 461fe2eb0..c15bc895e 100644 --- a/linq/linq.d.ts +++ b/linq/linq.d.ts @@ -208,7 +208,7 @@ declare module linq { ThenBy(keySelector: ($) => T): OrderedEnumerable; ThenBy(keySelector: string): OrderedEnumerable; ThenByDescending(keySelector: ($) => T): OrderedEnumerable; - ThenByDescending(keySelector: T): OrderedEnumerable; + ThenByDescending(keySelector: string): OrderedEnumerable; } interface Grouping extends Enumerable { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index dfa5e2e6a..364ec3de8 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6324,6 +6324,14 @@ declare module _ { noop(): void; } + //_.constant + interface LoDashStatic { + /** + * Creates a function that returns value.. + **/ + constant(value: T): T; + } + //_.create interface LoDashStatic { /** diff --git a/nock/nock.d.ts b/nock/nock.d.ts index 40b728d49..18119e1db 100644 --- a/nock/nock.d.ts +++ b/nock/nock.d.ts @@ -12,6 +12,12 @@ declare module "nock" { module nock { export function cleanAll(): void; + + export function disableNetConnect(): void; + export function enableNetConnect(): void; + export function enableNetConnect(regex: RegExp): void; + export function enableNetConnect(domain: string): void; + export var recorder: Recorder; export interface Scope { diff --git a/node-imap/imap-tests.ts b/node-imap/imap-tests.ts new file mode 100644 index 000000000..61f4b2e0c --- /dev/null +++ b/node-imap/imap-tests.ts @@ -0,0 +1,126 @@ +import Imap = require('imap'); +var inspect = require('util').inspect; + +var imap = new Imap({ + user: 'mygmailname@gmail.com', + password: 'mygmailpassword', + host: 'imap.gmail.com', + port: 993, + tls: true +}); + +imap.once('ready', function () { + imap.openBox('INBOX', true,function (err, box) { + if (err) throw err; + var f = imap.seq.fetch('1:3', { + bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)', + struct: true + }); + f.on('message', function (msg, seqno) { + console.log('Message #%d', seqno); + var prefix = '(#' + seqno + ') '; + msg.on('body', function (stream, info) { + var buffer = ''; + stream.on('data', function (chunk) { + buffer += chunk.toString('utf8'); + }); + stream.once('end', function () { + console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer))); + }); + }); + msg.once('attributes', function (attrs) { + console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8)); + }); + msg.once('end', function () { + console.log(prefix + 'Finished'); + }); + }); + f.once('error', function (err) { + console.log('Fetch error: ' + err); + }); + f.once('end', function () { + console.log('Done fetching all messages!'); + imap.end(); + }); + }); +}); + +imap.once('error', function (err) { + console.log(err); +}); + +imap.once('end', function () { + console.log('Connection ended'); +}); + +imap.connect(); + +imap.openBox('INBOX', true, function (err, box) { + if (err) throw err; + var f = imap.seq.fetch(box.messages.total + ':*', { bodies: ['HEADER.FIELDS (FROM)', 'TEXT'] }); + f.on('message', function (msg, seqno) { + console.log('Message #%d', seqno); + var prefix = '(#' + seqno + ') '; + msg.on('body', function (stream, info) { + if (info.which === 'TEXT') + console.log(prefix + 'Body [%s] found, %d total bytes', inspect(info.which), info.size); + var buffer = '', count = 0; + stream.on('data', function (chunk) { + count += chunk.length; + buffer += chunk.toString('utf8'); + if (info.which === 'TEXT') + console.log(prefix + 'Body [%s] (%d/%d)', inspect(info.which), count, info.size); + }); + stream.once('end', function () { + if (info.which !== 'TEXT') + console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer))); + else + console.log(prefix + 'Body [%s] Finished', inspect(info.which)); + }); + }); + msg.once('attributes', function (attrs) { + console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8)); + }); + msg.once('end', function () { + console.log(prefix + 'Finished'); + }); + }); + f.once('error', function (err) { + console.log('Fetch error: ' + err); + }); + f.once('end', function () { + console.log('Done fetching all messages!'); + imap.end(); + }); +}); + +var fs = require('fs'), fileStream : any; + +imap.openBox('INBOX', true,function (err, box) { + if (err) throw err; + imap.search(['UNSEEN', ['SINCE', 'May 20, 2010']], function (err : Error, results: any) { + if (err) throw err; + var f = imap.fetch(results, { bodies: '' }); + f.on('message', function (msg, seqno) { + console.log('Message #%d', seqno); + var prefix = '(#' + seqno + ') '; + msg.on('body', function (stream, info) { + console.log(prefix + 'Body'); + stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt')); + }); + msg.once('attributes', function (attrs) { + console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8)); + }); + msg.once('end', function () { + console.log(prefix + 'Finished'); + }); + }); + f.once('error', function (err) { + console.log('Fetch error: ' + err); + }); + f.once('end', function () { + console.log('Done fetching all messages!'); + imap.end(); + }); + }); +}); diff --git a/node-imap/imap.d.ts b/node-imap/imap.d.ts new file mode 100644 index 000000000..2b387136f --- /dev/null +++ b/node-imap/imap.d.ts @@ -0,0 +1,102 @@ +// Type definitions for node imap +// Project: https://github.com/mscdex/node-imap +// Definitions by: Steve Fenton +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "imap" { + interface ImapOptions { + user: string; + password: string; + host: string; + port: number; + tls: boolean; + } + + interface ImapBox { + name: string; + readOnly: boolean; + newKeywords: boolean; + uidvalidity: number; + uidnext: number; + flags: any[]; // TODO + permFlags: any[]; // TODO + persistentUIDs: boolean; + messages: { + total: number; + 'new': number; + unseen: number; + } + } + + interface ImapChunk { + toString(charset: string): string; + length: number; + } + + interface ImapFetch { + once(event: 'end', callback: () => void): void; + once(event: 'error', callback: (error: Error) => void): void; + once(event: string, callback: Function): void; + + on(event: 'message', callback: (msg: ImapMessage, seqno: number) => void): void; + on(event: string, callback: Function): void; + } + + interface ImapBodyStream { + once(event: 'end', callback: () => void): void; + once(event: string, callback: Function): void; + + on(event: 'data', callback: (chunk: ImapChunk) => void): void; + on(event: string, callback: Function): void; + + pipe(stream: any): void; + } + + interface ImapMessage { + // TODO: typeof attributes + once(event: 'attributes', callback: (attributes: any) => void): void; + once(event: string, callback: Function): void; + + // TODO: typeof info + on(event: 'body', callback: (stream: ImapBodyStream, info: any) => void): void; + on(event: string, callback: Function): void; + } + + class Imap { + constructor(options: ImapOptions); + + connect(): void; + + //TODO: + // param a + openBox(name: string, a: boolean, callback: (err: Error, box: ImapBox) => void) : void; + + //TODO: + // param a + // param b + once(event: 'end', callback: () => void): void; + once(event: 'error', callback: (error: Error) => void): void; + once(a: string, callback: Function) : void; + + end(): void; + + //TODO: + // return type + parseHeader(header: string): any; + static parseHeader(header: string): any; + + search(searchTerms: any[], callback: Function): void; + + fetch(results: any, options: {}): ImapFetch; + + //TODO: + // type + seq: { + fetch(messageSourceQuery: string, options: {}): ImapFetch; + }; + } + + export = Imap; +} diff --git a/node/node-0.11.d.ts b/node/node-0.11.d.ts index 2da9c47c6..a564ac85f 100644 --- a/node/node-0.11.d.ts +++ b/node/node-0.11.d.ts @@ -465,7 +465,7 @@ declare module "zlib" { } declare module "os" { - export function tmpDir(): string; + export function tmpdir(): string; export function hostname(): string; export function type(): string; export function platform(): string; @@ -767,13 +767,13 @@ declare module "dgram" { port: number; size: number; } - + interface AddressInfo { - address: string; - family: string; - port: number; + address: string; + family: string; + port: number; } - + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; interface Socket extends events.EventEmitter { diff --git a/node/node.d.ts b/node/node.d.ts index f2b5eee24..99ab5eccd 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -465,7 +465,7 @@ declare module "zlib" { } declare module "os" { - export function tmpDir(): string; + export function tmpdir(): string; export function hostname(): string; export function type(): string; export function platform(): string; @@ -528,8 +528,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: events.EventEmitter) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: events.EventEmitter) =>void ): http.ClientRequest; + 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 var globalAgent: Agent; } diff --git a/phantom/phantom-tests.ts b/phantom/phantom-tests.ts new file mode 100644 index 000000000..bd12a5e6e --- /dev/null +++ b/phantom/phantom-tests.ts @@ -0,0 +1,168 @@ +/// + +import phantom = require("phantom"); + +phantom.create((ph: phantom.PhantomJS): void => { + ph.createPage((page): void => { + page.open("http://www.google.com", (status: string): void => { + console.log("opened google? ", status); + page.evaluate((): string => { + return document.title; + }, (result: string): void => { + console.log('Page title is ' + result); + ph.exit(); + }); + }); + }); +}); + + +var _ph: phantom.PhantomJS; +phantom.create("--web-security=no", "--ignore-ssl-errors=yes", { port: 12345 }, (ph) => { + console.log("Phantom Bridge Initiated"); + _ph = ph; +}); +var _page: phantom.WebPage; +_ph.createPage((page) => { + console.log("Page created!"); + _page = page; +}); + +_page.open("http://www.google.com", function (status) { + if (status == "success") { + console.log("Page is open!"); + _page.close(); + } +}); + +_page.evaluate(function() { + var title = (document.querySelector("title")).innerText + console.log("The page title is " + title) +}) +_page.evaluate(function(selector) { + var text = (document.querySelector(selector)).innerText + console.log(selector + " contains the following text: " + text) +}, function(result) {}, "title") +_page.evaluate(function(selector) { + var text = (document.querySelector(selector)).innerText + return text +}, function(result) { + console.log("The element contains the following text: " + result) +}, "title"); + + +_page.set('viewportSize', { width: 1920, height: 1080 }, function (result) { + console.log("Viewport set to: " + result.width + "x" + result.height); +}); +_page.set('onConsoleMessage', function (msg: string) { + console.log("Phantom Console: " + msg); +}); +_page.set('onUrlChanged', function(url: string) { + console.log("New URL: "+url); +}); +_page.set('onResourceRequested', function () { + console.log("Resource requested.."); +}); +_page.set('onResourceReceived', function (res: any) { + if (res.stage == 'end') { + console.log("Resource received!") + } +}); +_page.set('onLoadStarted', function () { + console.log("Loading started"); +}); +_page.set('onLoadFinished', function (status: string) { + console.log("Loading finished, the page is " + ((status == "success") ? "open." : "not open!")); +}); +_page.set('settings.loadImages', false); +_page.set('settings.resourceTimeout', 1000); + + +_page.set('settings.viewportSize', { + width : 1920, + height : 1080 +}); +_page.open("http://google.co.jp", (status) => { + _page.render("/tmp/google-top.jpg", { + format : 'jpeg', + quality : '80' + }); + _ph.exit(); +}); + + +phantom.create((ph) => { + ph.addCookie('cookie_name', 'cookie_value', 'localhost', () => {}); + ph.getCookies((cookies) => {}); + + ph.createPage((page) => { + page.set('Referer', 'http://google.com'); + page.set('settings.userAgent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1'); + + page.open("http://localhost:9901/cookie", (status) => { + var someFunc = (aaa: string, my_obj: Object) => { + var attribute_to_want = aaa; + var h2Arr: string[] = []; + var results = document.querySelectorAll(attribute_to_want); + for (var i = 0, len = results.length; i < len; ++i) { + var result = results[i]; + h2Arr.push(result.innerText); + } + return { + h2: h2Arr, + aaa: this.arguments, + obj: my_obj + }; + }; + var finishedFunc = (result: any) => { + ph.exit(); + }; + page.evaluate(someFunc, finishedFunc, 'div', {wahtt: 111}); + }); + }); + + ph.createPage((page) => { + page.open('http://www.phantomjs.org', (status) => { + if (status === 'success') { + page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', () => { + page.injectJs('do.js', (res) => { + page.evaluate(() => { + return document.title; + }, (title: string) => { + console.log(title); + ph.exit(); + }); + }); + }); + + page.sendEvent('click', 350, 320); + page.sendEvent('click', 350, 320, 'right'); + page.sendEvent('keypress', 'A', null, null, 0x02000000 | 0x08000000); + page.sendEvent('keypress', 'A'); + + page.setViewportSize(800, 640); + page.setPaperSize({ + width: '200px', + height: '300px', + margin: '0px' + }); + page.setPaperSize({ + format: 'A4', + orientation: 'portrait', + margin: '1cm' + }); + page.setPaperSize({ + width: '5in', + height: '7in', + margin: { + top: '50px', + left: '20px' + } + }); + page.setZoomFactor(0.25); + } + }); + }); +}); + + diff --git a/phantom/phantom.d.ts b/phantom/phantom.d.ts new file mode 100644 index 000000000..8f491072f --- /dev/null +++ b/phantom/phantom.d.ts @@ -0,0 +1,78 @@ +// Type definitions for PhantomJS bridge for NodeJS 0.7.0 +// Project: https://github.com/sgentle/phantomjs-node +// Definitions by: horiuchi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "phantom" { + + function create(callback: (ph: PhantomJS) => void): void; + function create(options: ICreateOptions, callback: (ph: PhantomJS) => void): void; + function create(arg: string, callback: (ph: PhantomJS) => void): void; + function create(arg: string, options: ICreateOptions, callback: (ph: PhantomJS) => void): void; + function create(arg1: string, arg2: string, callback: (ph: PhantomJS) => void): void; + function create(arg1: string, arg2: string, options: ICreateOptions, callback: (ph: PhantomJS) => void): void; + function create(arg1: string, arg2: string, arg3: string, callback: (ph: PhantomJS) => void): void; + function create(arg1: string, arg2: string, arg3: string, options: ICreateOptions, callback: (ph: PhantomJS) => void): void; + + interface PhantomJS { + createPage(callback: (page: WebPage) => void): void; + exit(returnValue?: number): void; + injectJs(filename: string, callback?: (result: boolean) => void): void; + + addCookie(name: string, value: string, domain: string, callback?: (res: boolean) => void): void; + clearCookies(callback?: () => void): void; + getCookies(callback: (cookies: { name: string; value: string; domain?: string; }[]) => void): void; + } + + interface WebPage { + open(url: string, callback: (status: string) => void): void; + close(): void; + + get(key: string, callback: (result: any) => void): void; + set(key: string, value: any, callback?: (result: any) => void): void; + setHeaders(headers: Object, callback?: () => void): void; + setViewportSize(width: number, height: number, callback?: () => void): void; + setPaperSize(options: IPaperSizeOptions, callback?: () => void): void; + setZoomFactor(factor: number, callback?: () => void): void; + + evaluate(callback: () => void): void; + evaluate(callback: () => R, returnCallback: (result: R) => void): void; + evaluate(callback: (arg: T) => void, returnCallback: () => void, arg: T): void; + evaluate(callback: (arg: T) => R, returnCallback: (result: R) => void, arg: T): void; + evaluate(callback: (arg1: T1, arg2: T2) => R, returnCallback: (result: R) => void, arg1: T1, arg2: T2): void; + evaluate(callback: (arg1: T1, arg2: T2, arg3: T3) => R, returnCallback: (result: R) => void, arg1: T1, arg2: T2, arg3: T3): void; + includeJs(url: string, callback?: () => void): void; + injectJs(filename: string, callback?: (res: boolean) => void): void; + sendEvent(mouseEventType: string, mouseX: number, mouseY: number, button?: string): void; + sendEvent(keyboardEventType: string, key: string, null1?: void, null2?: void, modifier?: number): void; + uploadFile(selector: string, filename: string): void; + + render(filename: string, callback?: () => void): void; + render(filename: string, options?: { format?: string; quality?: string; }, callback?: () => void): void; + renderBase64(type: string, callback: (data: string) => void): void; + + goBack(): void; + goForward(): void; + reload(): void; + + getContent(callback: (content: string) => void): void; + setContent(html: string, url: string, callback?: (status: string) => void): void; + getCookies(callback: (cookies: { name: string; value: string; domain?: string; }[]) => void): void; + } + + interface ICreateOptions { + binary?: string; + hostname?: string; + path?: string; + port?: number; + } + interface IPaperSizeOptions { + width?: string; + height?: string; + format?: string; + orientation?: string; + margin?: any; // string | { top?: string; left?: string; bottom?: string; right?: string; } + } + +} + diff --git a/playerframework/playerFramework-tests.ts b/playerframework/playerFramework-tests.ts new file mode 100644 index 000000000..9d1d7921a --- /dev/null +++ b/playerframework/playerFramework-tests.ts @@ -0,0 +1,174 @@ +/// + +var el = document.createElement("div"); +var player = new PlayerFramework.MediaPlayer(el); + +// Getters +var currentSrc = player.currentSrc; +var interactiveModel = player.defaultInteractiveViewModel; +var duration = player.duration; +var element = player.element; +var ended = player.ended; +var error = player.error; +var initialTime = player.initialTime; +var audioAllowed = player.isAudioAllowed; +var captionsAllowed = player.isCaptionsAllowed; +var currentTime = player.isCurrentTimeLive; +var timeAllowed = player.isElapsedTimeAllowed; +var forwardAllowed = player.isFastForwardAllowed; +var fullscreenAllowed = player.isFullScreenAllowed; +var goLiveAllowed = player.isGoLiveAllowed; +var live = player.isLive; +var mediaQualityAllowed = player.isMediaQualityAllowed; +var muteAllowed = player.isMuteAllowed; +var pauseAllowed = player.isPauseAllowed; +var playPauseAllowed = player.isPlayPauseAllowed; +var playResumeAllowed = player.isPlayResumeAllowed; +var remainingTimeAllowed = player.isRemainingTimeAllowed; +var replayAllowed = player.isReplayAllowed; +var rewindAllowed = player.isRewindAllowed; +var strengthAllowed = player.isSignalStrengthAllowed; +var aheadAllowed = player.isSkipAheadAllowed; +var backAllowed = player.isSkipBackAllowed; +var nextAllowed = player.isSkipNextAllowed; +var prevAllowed = player.isSkipPreviousAllowed; +var motionAllowed = player.isSlowMotionAllowed; +var timelineAllowed = player.isTimelineAllowed; +var volumeAllowed = player.isVolumeAllowed; +var muteAllowed = player.isVolumeMuteAllowed; +var optimalPlayback = player.msIsLayoutOptimalForPlayback; +var stereo = player.msIsStereo3D; +var playToSource = player.msPlayToSource; +var networkState = player.networkState; +var paused = player.paused; +var playlistPlugin = player.playlistPlugin; +var readyState = player.readyState; +var scrubbing = player.scrubbing; +var seeking = player.seeking; +var videoHeight = player.videoHeight; +var videoWidth = player.videoWidth; + +// Getters/Setters +player.advertisingState = PlayerFramework.AdvertisingState.linear; +player.autobuffer = false; +player.autohide = false; +player.autohideBehavior = PlayerFramework.AutohideBehavior.all; +player.autohideTime = 0; +player.autoload = false; +player.autoplay = false; +player.controls = false; +player.currentTime = 0; +player.defaultPlaybackRate = 0; +player.endTime = 0; +player.height = '100px'; +player.interactiveActivationMode = PlayerFramework.InteractionType.all; +player.interactiveDeactivationMode = PlayerFramework.InteractionType.all; +player.interactiveViewModel = new PlayerFramework.InteractiveViewModel(); +player.isAudioEnabled = false; +player.isAudioVisible = false; +player.isCaptionsVisible = false; +player.isElapsedTimeEnabled = false; +player.isElapsedTimeVisible = false; +player.isFastForwardEnabled = false; +player.isFastForwardVisible = false; +player.isFullScreen = false; +player.isFullScreenEnabled = false; +player.isFullScreenVisible = false; +player.isGoLiveEnabled = false; +player.isGoLiveVisible = false; +player.isInteractive = false; +player.isMediaQualityEnabled = false; +player.isMediaQualityVisible = false; +player.isMuteEnabled = false; +player.isMuteVisible = false; +player.isPauseEnabled = false; +player.isPauseVisible = false; +player.isPlayPauseEnabled = false; +player.isPlayPauseVisible = false; +player.isPlayResumeEnabled = false; +player.isPlayResumeVisible = false; +player.isRemainingTimeEnabled = false; +player.isRemainingTimeVisible = false; +player.isReplayEnabled = false; +player.isReplayVisible = false; +player.isRewindEnabled = false; +player.isRewindVisible = false; +player.isSignalStrengthEnabled = false; +player.isSignalStrengthVisible = false; +player.isSkipAheadEnabled = false; +player.isSkipAheadVisible = false; +player.isSkipBackEnabled = false; +player.isSkipBackVisible = false; +player.isSkipNextEnabled = false; +player.isSkipNextVisible = false; +player.isSkipPreviousEnabled = false; +player.isSkipPreviousVisible = false; +player.isSlowMotion = false; +player.isSlowMotionEnabled = false; +player.isSlowMotionVisible = false; +player.isStartTimeOffset = false; +player.isTimelineEnabled = false; +player.isTimelineVisible = false; +player.isVolumeEnabled = false; +player.isVolumeMuteEnabled = false; +player.isVolumeMuteVisible = false; +player.isVolumeVisible = false; +player.liveTime = 0; +player.liveTimeBuffer = 0; +player.loop = false; +player.mediaElement = document.createElement('video'); +player.mediaExtensionManager = new Windows.Media.MediaExtensionManager(); +player.mediaQuality = PlayerFramework.MediaQuality.highDefinition; +player.msAudioCategory = 'audioCategory'; +player.msAudioDeviceType = 'deviceType'; +player.msHorizontalMirror = false; +player.msPlayToDisabled = false; +player.msPlayToPrimary = false; +player.msRealTime = false; +player.msStereo3DPackingMode = 'stereoMode'; +player.msStereo3DRenderMode = 'stereoMode'; +player.msZoom = false; +player.muted = false; + +player.playbackRate = 0; +player.playerState = PlayerFramework.PlayerState.starting; +player.poster = 'poster'; +player.preload = 'preload'; +player.replayOffset = 0; +player.seekWhileScrubbing = false; +player.signalStrength = 0; + +player.skipAheadInterval = 0; +player.skipBackInterval = 0; +player.slowMotionPlaybackRate = 0; +player.src = 'srcUrl'; +player.startTime = 0; +player.startupTime = 0; +player.testForMediaPack = false; +player.volume = 50; +player.width = '100px'; + + +// Methods +player.addClass('className'); +player.addEventListener('eventName', () => { }); +player.addEventListener('eventName', () => { }, false); +player.addTextTrack('kind'); +player.addTextTrack('kind', 'label'); +player.addTextTrack('kind', 'label', 'language'); +var canPlay = player.canPlayType('type'); +player.decreasePlaybackRate(); +player.dispose(); +player.focus(); +player.increasePlaybackRate(); +player.load(); +player.pause(); +player.play(); +player.playResume(); +player.removeClass('className'); +player.removeEventListener('eventName', () => { }); +player.replay(); +player.retry(); +player.stop(); +player.update({}); + diff --git a/playerframework/playerFramework.d.ts b/playerframework/playerFramework.d.ts new file mode 100644 index 000000000..339b94a73 --- /dev/null +++ b/playerframework/playerFramework.d.ts @@ -0,0 +1,1965 @@ +// Type definitions for Player Framework (MMPPF) +// Project: https://playerframework.codeplex.com/ +// Definitions by: Ricardo Sabino +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare module PlayerFramework { + + // Enumerations + enum AdvertisingState { + /** + * No ad is loading or playing. + **/ + none = 0, + /** + * An ad is loading. + **/ + loading = 1, + /** + * A linear ad is playing. + **/ + linear = 2, + /** + * A non-linear ad is playing. + **/ + nonLinear = 3 + } + + + enum AutohideBehavior { + /** + * No behaviors are applied to the autohide feature. + **/ + none = 0, + /** + * Autohide is allowed during media playback only. + **/ + allowDuringPlaybackOnly = 1, + /** + * Autohide is prevented when the pointer is over interactive components such as the control panel. + **/ + preventDuringInteractiveHover = 2, + /** + * All behaviors are applied to the autohide feature. + **/ + all = 3 + } + + enum InteractionType { + /** + * Indicates no interaction. + **/ + none = 0, + /** + * Indicates a "soft" interaction such as mouse movement or a timeout occurring. + **/ + soft = 1, + /** + * Indicates a "hard" interaction such as a tap, click, or a key is pressed. + **/ + hard = 2, + /** + * Indicates both "soft" and "hard" interactions. + **/ + all = 3 + } + + enum NetworkState { + /** + * The player has not yet initialized any audio/video. + **/ + empty = 0, + /** + * The player has active audio/video and has selected a resource, but is not using the network. + **/ + idle = 1, + /** + * The player is downloading data. + **/ + loading = 2, + /** + * The player has no audio/video source. + **/ + noSource = 3 + } + + enum MediaQuality { + /** + * Typically indicates less than 720p media quality. + **/ + standardDefinition = 0, + /** + * Typically indicates greater than or equal to 720p media quality. + **/ + highDefinition = 1 + } + + enum PlayerState { + /** + * The player is unloaded and no media source is set. + **/ + unloaded = 0, + /** + * The media source is set and the player is waiting to load the media (e.g. autoload is false). + **/ + pending = 1, + /** + * The media source is set, but the player is still executing loading operations. + **/ + loading = 2, + /** + * The media has finished loading, but has not been opened yet. + **/ + loaded = 3, + /** + * The media can be played. + **/ + opened = 4, + /** + * The media has been told to start playing, but the player is still executing starting operations. + **/ + starting = 5, + /** + * The media has been started and the player is either playing or paused. + **/ + started = 6, + /** + * The media has finished, but the player is still executing ending operations. + **/ + ending = 7, + /** + * The media has ended. + **/ + ended = 8, + /** + * The media has failed and the player must be reloaded. + **/ + failed = 9, + } + + enum ReadyState { + /** + * The player has no information for the audio/video + **/ + nothing = 0, + /** + * The player has metadata for the audio/video. + **/ + metadata = 1, + /** + * The player has data for the current playback position, but not enough data to play the next frame. + **/ + currentData = 2, + /** + * The player has data for the current playback position and at least the next frame. + **/ + futureData = 3, + /** + * The player has enough data available to start playing. + **/ + enoughData = 4 + } + + enum MediaErrorCode { + /** + * An unknown media error occurred. + **/ + unknown = 0, + /** + * Media playback was aborted. + **/ + aborted = 1, + /** + * Media download failed due to a network error. + **/ + network = 2, + /** + * Media playback was aborted due to a corruption problem or because unsupported features were used. + **/ + decode = 3, + /** + * Media source could not be loaded either because the server or network failed or because the format is not supported. + **/ + notSupported = 4 + } + + enum ImageErrorCode { + /** + * An unknown image error occurred. + **/ + unknown = 0, + /** + * Image download was aborted. + **/ + aborted = 1 + } + + class TextTrackMode { + /** + * The track is disabled. + **/ + static off: string; + /** + * The track is active, but the player is not actively displaying cues. + **/ + static hidden: string; + /** + * The track is active and the player is actively displaying cues. + **/ + static showing: string; + } + + enum TextTrackDisplayMode { + /** + * Indicates tracks should not be displayed. + */ + none = 0, + /** + * Indicates tracks should be displayed using custom UI. + */ + custom = 1, + /** + * Indicates tracks should be displayed using native UI. + */ + native = 2, + /** + * Indicates tracks should be displayed using both custom and native UI. This is useful for debugging. + */ + all = 3 + } + + enum TextTrackReadyState { + /** + * The track is unloaded. + */ + none = 0, + /** + * The track is currently loading. + */ + loading = 1, + /** + * The track is loaded. + */ + loaded = 2, + /** + * The track failed to load. + */ + error = 3 + } + + enum ViewModelState { + /** + * No media is loaded. + */ + unloaded = 0, + /** + * The media is loading. + */ + loading = 1, + /** + * The media is paused. + */ + paused = 2, + /** + * The media is playing. + */ + playing = 3 + } + + + + interface PlaylistItem { + src: string; + tracks?: Array; //TODO + } + + class PluginBase { + isEnabled: boolean; + isLoaded: boolean; + isActive: boolean; + mediaPlayer: MediaPlayer; + currentMediaSource: MediaSource; + + load(): void; + unload(): void; + update(mediaSource: MediaSource): void; + } + + module Plugins { + + class TrackingPluginBase extends PluginBase { + trackingEvents: Array; + + } + + class BufferingPlugin extends PluginBase { + hide(): void; + show(): void; + } + + class ControlPlugin extends PluginBase { + compactThresholdInInches(): number; + hide(): void; + isCompact(): boolean; + orientation(): string; + show(): void; + } + + class ErrorPlugin extends PluginBase { + hide(): void; + show(): void; + } + + class LoaderPlugin extends PluginBase { + hide(): void; + show(): void; + } + + /** + * + **/ + class PlaylistPlugin extends PluginBase { + /** + * + **/ + autoAdvance: boolean; + /** + * + **/ + currentPlaylistItem: PlaylistItem; + /** + * + **/ + currentPlaylistItemIndex: number; + /** + * + **/ + playlist: Array; + /** + * + **/ + startupPlaylistItemIndex: number; + /** + * + **/ + skipBackThreshold: number; + + // Methods + goToPreviousPlaylistItem(): void; + goToNextPlaylistItem(): void; + canGoToPreviousPlaylistItem(): boolean; + canGoToNextPlaylistItem(): boolean; + } + + class PlayTimeTrackingPlugin extends PluginBase { + playTime: number; + playTimePercentage: number; + } + + class PositionTrackingPlugin extends PluginBase { + evaluateOnForwardOnly: boolean; + position: number; + positionPercentage: number; + } + + class SystemTransportControlsPlugin extends PluginBase { + isPreviousTrackEnabled: boolean; + isNextTrackEnabled: boolean; + nextTrackExists: boolean; + previousTrackExists: boolean; + } + + class ChaptersPlugin extends PluginBase { + defaultChapterCount: number; + autoCreateDefaultChapters: boolean; + autoCreateChaptersFromTextTracks: boolean; + visualMarkerClass: string; + } + + class DisplayRequestPlugin extends PluginBase { + isRequestActive: boolean; + } + + class CaptionSelectorPlugin extends PluginBase { + hide(): void; + show(): void; + + /** + * Not available in phone. + **/ + alignment: string; + /** + * Not available in phone. + **/ + anchor: HTMLElement; + /** + * Not available in phone. + **/ + placement: string; + } + + class AudioSelectorPlugin extends PluginBase { + hide(): void; + show(): void; + + /** + * Not available in phone. + **/ + alignment: string; + /** + * Not available in phone. + **/ + anchor: HTMLElement; + /** + * Not available in phone. + **/ + placement: string; + } + } + + /** + * + **/ + class InteractiveViewModel { + /** + * TODO + **/ + state: ViewModelState; + /** + * TODO + **/ + startTime: number; + /** + * TODO + **/ + maxTime: number; + /** + * TODO + **/ + endTime: number; + /** + * TODO + **/ + currentItem: number; + /** + * TODO + **/ + bufferedPercentage: number; + /** + * TODO + **/ + playPouseIcon: string; + /** + * TODO + **/ + playPauseLabel: string; + /** + * TODO + **/ + playPauseTooltip: string; + /** + * TODO + **/ + isPlayPauseDisabled: boolean; + /** + * TODO + **/ + isPlayPauseHidden: boolean; + /** + * TODO + **/ + playResumeIcon: string; + /** + * TODO + **/ + playResumeLabel: string; + /** + * TODO + **/ + playResumeTooltip: string; + /** + * TODO + **/ + isPlayResumeDisabled: boolean; + /** + * TODO + **/ + isPlayResumeHidden: boolean; + /** + * TODO + **/ + pauseIcon: string; + /** + * TODO + **/ + pauseLabel: string; + /** + * TODO + **/ + pauseTooltip: string; + /** + * TODO + **/ + isPauseDisabled: boolean; + /** + * TODO + **/ + isPauseHidden: boolean; + /** + * TODO + **/ + replayIcon: string; + /** + * TODO + **/ + replayLabel: string; + /** + * TODO + **/ + replayTooltip: string; + /** + * TODO + **/ + isReplayDisabled: boolean; + /** + * TODO + **/ + isReplayHidden: boolean; + /** + * TODO + **/ + rewindIcon: string; + /** + * TODO + **/ + rewindLabel: string; + /** + * TODO + **/ + rewindTooltip: string; + /** + * TODO + **/ + isRewindDisabled: boolean; + /** + * TODO + **/ + isRewindHidden: boolean; + /** + * TODO + **/ + fastForwardIcon: string; + /** + * TODO + **/ + fastForwardLabel: string; + /** + * TODO + **/ + fastForwardTooltip: string; + /** + * TODO + **/ + isFastForwardDisabled: boolean; + /** + * TODO + **/ + isFastForwardHidden: boolean; + /** + * TODO + **/ + slowMotionIcon: string; + /** + * TODO + **/ + slowMotionLabel: string; + /** + * TODO + **/ + slowMotionTooltip: string; + /** + * TODO + **/ + isSlowMotionDisabled: boolean; + /** + * TODO + **/ + isSlowMotionHidden: boolean; + /** + * TODO + **/ + skipPreviousIcon: string; + /** + * TODO + **/ + skipPreviousLabel: string; + /** + * TODO + **/ + skipPreviousTooltip: string; + /** + * TODO + **/ + isSkipPreviousDisabled: boolean; + /** + * TODO + **/ + isSkipPreviousHidden: boolean; + /** + * TODO + **/ + skipNextIcon: string; + /** + * TODO + **/ + skipNextLabel: string; + /** + * TODO + **/ + skipNextTooltip: string; + /** + * TODO + **/ + isSkipNextDisabled: boolean; + /** + * TODO + **/ + isSkipNextHidden: boolean; + /** + * TODO + **/ + skipBackIcon: string; + /** + * TODO + **/ + skipBackLabel: string; + /** + * TODO + **/ + skipBackTooltip: string; + /** + * TODO + **/ + isSkipBackDisabled: boolean; + /** + * TODO + **/ + isSkipBackHidden: boolean; + /** + * TODO + **/ + skipAheadIcon: string; + /** + * TODO + **/ + skipAheadLabel: string; + /** + * TODO + **/ + skipAheadTooltip: string; + /** + * TODO + **/ + isSkipAheadDisabled: boolean; + /** + * TODO + **/ + isSkipAheadHidden: boolean; + /** + * TODO + **/ + elapsedTime: number; + /** + * TODO + **/ + elapsedTimeText: string; + /** + * TODO + **/ + elapsedTimeLabel: string; + /** + * TODO + **/ + elapsedTimeTooltip: string; + /** + * TODO + **/ + isElapsedTimeDisabled: boolean; + /** + * TODO + **/ + isElapsedTimeHidden: boolean; + /** + * TODO + **/ + remainingTime: number; + /** + * TODO + **/ + remainingTimeText: string; + /** + * TODO + **/ + remainingTimeLabel: string; + /** + * TODO + **/ + remainingTimeTooltip: string; + /** + * TODO + **/ + isRemainingTimeDisabled: boolean; + /** + * TODO + **/ + isRemainingTimeHidden: boolean; + /** + * TODO + **/ + totalTime: number; + /** + * TODO + **/ + totalTimeText: string; + /** + * TODO + **/ + totalTimeLabel: string; + /** + * TODO + **/ + totalTimeTooltip: string; + /** + * TODO + **/ + isTotalTimeDisabled: boolean; + /** + * TODO + **/ + isTotalTimeHidden: boolean; + /** + * TODO + **/ + timelineLabel: string; + /** + * TODO + **/ + timelineTooltip: string; + /** + * TODO + **/ + isTimelineDisabled: boolean; + /** + * TODO + **/ + isTimelineHidden: boolean; + /** + * TODO + **/ + goLiveText: string; + /** + * TODO + **/ + goLiveLabel: string; + /** + * TODO + **/ + goLiveTooltip: string; + /** + * TODO + **/ + isGoLiveDisabled: boolean; + /** + * TODO + **/ + isGoLiveHidden: boolean; + /** + * TODO + **/ + captionsIcon: string; + /** + * TODO + **/ + captionsLabel: string; + /** + * TODO + **/ + captionsTooltip: string; + /** + * TODO + **/ + isCaptionsDisabled: boolean; + /** + * TODO + **/ + audioIcon: string; + /** + * TODO + **/ + audioLabel: string; + /** + * TODO + **/ + audioTooltip: string; + /** + * TODO + **/ + isAudioDisabled: boolean; + /** + * TODO + **/ + isAudioHidden: boolean; + /** + * TODO + **/ + volume: number; + /** + * TODO + **/ + volumeMuteIcon: string; + /** + * TODO + **/ + volumeMuteLabel: string; + /** + * TODO + **/ + volumeMuteTooltip: string; + /** + * TODO + **/ + isVolumeMuteDisabled: boolean; + /** + * TODO + **/ + isVolumeMuteHidden: boolean; + /** + * TODO + **/ + volumeIcon: string; + /** + * TODO + **/ + volumeLabel: string; + /** + * TODO + **/ + volumeTooltip: string; + /** + * TODO + **/ + isVolumeDisabled: boolean; + /** + * TODO + **/ + isVolumeHidden: boolean; + /** + * TODO + **/ + muteIcon: string; + /** + * TODO + **/ + muteLabel: string; + /** + * TODO + **/ + muteTooltip: string; + /** + * TODO + **/ + isMuteDisabled: boolean; + /** + * TODO + **/ + isMuteHidden: boolean; + /** + * TODO + **/ + fullScreenIcon: string; + /** + * TODO + **/ + fullScreenLabel: string; + /** + * TODO + **/ + fullScreenTooltip: string; + /** + * TODO + **/ + isFullScreenDisabled: boolean; + /** + * TODO + **/ + isFullScreenHidden: boolean; + /** + * TODO + **/ + stopIcon: string; + /** + * TODO + **/ + stopLabel: string; + /** + * TODO + **/ + stopTooltip: string; + /** + * TODO + **/ + isStopDisabled: boolean; + /** + * TODO + **/ + isStopHidden: boolean; + /** + * TODO + **/ + infoIcon: string; + /** + * TODO + **/ + infoLabel: string; + /** + * TODO + **/ + infoTooltip: string; + /** + * TODO + **/ + isInfoDisabled: boolean; + /** + * TODO + **/ + isInfoHidden: boolean; + /** + * TODO + **/ + moreIcon: string; + /** + * TODO + **/ + moreLabel: string; + /** + * TODO + **/ + moreTooltip: string; + /** + * TODO + **/ + isMoreDisabled: boolean; + /** + * TODO + **/ + isMoreHidden: boolean; + /** + * TODO + **/ + zoomIcon: string; + /** + * TODO + **/ + zoomLabel: string; + /** + * TODO + **/ + zoomTooltip: string; + /** + * TODO + **/ + isZoomDisabled: boolean; + /** + * TODO + **/ + isZoomHidden: boolean; + /** + * TODO + **/ + signalStrength: number; + /** + * TODO + **/ + signalStrengthLabel: string; + /** + * TODO + **/ + signalStrengthTooltip: string; + /** + * TODO + **/ + isSignalStrengthDisabled: boolean; + /** + * TODO + **/ + isSignalStrengthHidden: boolean; + /** + * TODO + **/ + mediaQuality: MediaQuality; + /** + * TODO + **/ + mediaQualityLabel: string; + /** + * TODO + **/ + mediaQualityTooltip: string; + /** + * TODO + **/ + isMediaQualityDisabled: boolean; + /** + * TODO + **/ + isMediaQualityHidden: boolean; + /** + * TODO + **/ + visualMarkers: Array; + /** + * TODO + **/ + thumbnailImageSrc: string; + /** + * TODO + **/ + isThumbnailVisible: boolean; + /** + * TODO + **/ + mediaMetadata: Object; + + + uninitialize(): void; + playPause(e?: any): void; + playResume(): void; + pause(): void; + replay(): void; + rewind(): void; + fastForward(): void; + slowMotion(): void; + skipPrevious(): void; + skipNext(): void; + skipBack(): void; + skipAhead(): void; + startScrub(time: number): void; + updateScrub(time: number): void; + completeScrub(time: number): void; + goLive(): void; + setVolume(volume: number): void; + toggleMutted(): void; + toggleFullScreen(): void; + stop(): void; + info(): void; + more(): void; + toggleZoom(): void; + captions(): void; + audio(): void; + onTimelineSliderStart(e: any): void; + onTimelineSliderUpdate(e: any): void; + onTimelineSliderComplete(e: any): void; + onTimelineSliderSkipToMarker(e: any): void; + onVolumeSliderUpdate(e: any): void; + onVolumeMuteClick(e: any): void; + onVolumeMuteFocus(e: any): void; + onVolumeMuteSliderUpdate(e: any): void; + onVolumeMuteSliderFocusIn(e: any): void; + onVolumeMuteSliderFocusOut(e: any): void; + onVolumeMuteSliderMSPointerOver(e: any): void; + onVolumeMuteSliderMSPointerOut(e: any): void; + onVolumeMuteSliderTransitionEnd(e: any): void; + } + + /** + * + **/ + class MediaPlayer { + constructor(element: HTMLElement, options?: any); + /** + * Gets or sets the current advertising state of the player. + **/ + advertisingState: AdvertisingState; + /** + * Gets the audio tracks for the current media source. + **/ + audioTracks: Array; + + /** + * Gets or sets a value that indicates whether to automatically start buffering the current media source. + **/ + autobuffer: boolean; + /** + * Gets or sets a value that specifies whether interactive elements(e.g.the control panel) will be hidden automatically. + **/ + autohide: boolean; + /** + * Gets or sets the behavior of the autohide feature. + **/ + autohideBehavior: AutohideBehavior; + /** + * Gets or sets the amount of time (in seconds) before interactive elements(e.g.the control panel) will be hidden automatically. + **/ + autohideTime: number; + /** + * Gets or sets a value that specifies whether to start loading the current media source automatically. + **/ + autoload: boolean; + /** + * Gets or sets a value that specifies whether to automatically start playing the current media source. + **/ + autoplay: boolean; + /** + * Gets the buffered time ranges for the current media source. + **/ + buffered: Array; //TODO: (type: TimeRanges, read - only) + /** + * Gets the caption and subtitle tracks for the current media source. + **/ + captionTracks: Array; + /** + * Gets or sets a value that specifies whether to display the native controls for the current media source. + **/ + controls: boolean; + /** + * Gets or sets the current audio track. + **/ + currentAudioTrack: any; //TODO: (type: AudioTrack, read / write) + /** + * Gets or sets the current caption / subtitle track. + **/ + currentCaptionTrack: any; //TODO: (type: TextTrack, read / write) + /** + * Gets the URL of the current media source. + **/ + currentSrc: string; + /** + * Gets or sets the current playback position (in seconds). + **/ + currentTime: number; + /** + * Gets the view model that will be restored following a temporary change to the current interactive view model(e.g.during an ad). + **/ + defaultInteractiveViewModel: InteractiveViewModel; + /** + * Gets or sets the playback rate to use when play is resumed. + **/ + defaultPlaybackRate: number; + /** + * Gets the duration (in seconds) of the current media source. + **/ + duration: number; + /** + * Gets the host element for the control. + **/ + element: HTMLElement; + /** + * Gets a value that specifies whether playback has ended. + **/ + ended: boolean; + /** + * Gets or sets the end time (in seconds) of the current media source.This is useful in live streaming scenarios. + **/ + endTime: number; + /** + * Gets the current error state of the player. + **/ + error: MediaError; + /** + * Gets or sets the height of the host element. + **/ + height: string; + /** + * Gets the earliest possible position (in seconds) that playback can begin. + **/ + initialTime: number; + /** + * Gets or sets the type of interactions that will cause interactive elements(e.g.the control panel) to be shown. + **/ + interactiveActivationMode: InteractionType; + /** + * Gets or sets the type of interactions that will cause interactive elements(e.g.the control panel) to be hidden. + **/ + interactiveDeactivationMode: InteractionType; + /** + * Gets or sets the view model that interactive elements are bound to(e.g.the control panel). + **/ + interactiveViewModel: InteractiveViewModel; + /** + * Gets a value that specifies whether interaction with the audio control is allowed based on the current state of the player. + **/ + isAudioAllowed: boolean; + /** + * Gets or sets a value that specifies whether the audio control is enabled. + **/ + isAudioEnabled: boolean; + /** + * Gets or sets a value that specifies whether the audio control is visible. + **/ + isAudioVisible: boolean; + /** + * Gets a value that specifies whether interaction with the captions control is allowed based on the current state of the player. + **/ + isCaptionsAllowed: boolean; + /** + * Gets or sets a value that specifies whether the captions control is enabled. + **/ + isCaptionsEnabled: boolean; //TODO: READ-ONLY + /** + * Gets or sets a value that specifies whether the captions control is visible. + **/ + isCaptionsVisible: boolean; + /** + * Gets a value that specifies whether the current playback position is "live". + **/ + isCurrentTimeLive: boolean; + /** + * Gets a value that specifies whether interaction with the elapsed time control is allowed based on the current state of the player. + **/ + isElapsedTimeAllowed: boolean; + /** + * Gets or sets a value that specifies whether the elapsed time control is enabled. + **/ + isElapsedTimeEnabled: boolean; + /** + * Gets or sets a value that specifies whether the elapsed time control is visible. + **/ + isElapsedTimeVisible: boolean; + /** + * Gets a value that specifies whether interaction with the fast forward control is allowed based on the current state of the player. + **/ + isFastForwardAllowed: boolean; + /** + * Gets or sets a value that specifies whether the fast forward control is enabled. + **/ + isFastForwardEnabled: boolean; + /** + * Gets or sets a value that specifies whether the fast forward control is visible. + **/ + isFastForwardVisible: boolean; + /** + * Gets or sets a value that specifies whether the player is in full screen mode. + **/ + isFullScreen: boolean; + /** + * Gets a value that specifies whether interaction with the full screen control is allowed based on the current state of the player. + **/ + isFullScreenAllowed: boolean; + /** + * Gets or sets a value that specifies whether the full screen control is enabled. + **/ + isFullScreenEnabled: boolean; + /** + * Gets or sets a value that specifies whether the full screen control is visible. + **/ + isFullScreenVisible: boolean; + /** + * Gets a value that specifies whether interaction with the go live control is allowed based on the current state of the player. + **/ + isGoLiveAllowed: boolean; + /** + * Gets or sets a value that specifies whether the go live control is enabled. + **/ + isGoLiveEnabled: boolean; + /** + * Gets or sets a value that specifies whether the go live control is visible. + **/ + isGoLiveVisible: boolean; + /** + * Gets or sets a value that specifies whether the player is currently in interactive mode(e.g.showing the control panel). + **/ + isInteractive: boolean; + /** + * Gets a value that specifies whether the current media source is a live stream. + **/ + isLive: boolean; + /** + * Gets a value that specifies whether interaction with the media quality control is allowed based on the current state of the player. + **/ + isMediaQualityAllowed: boolean; + /** + * Gets or sets a value that specifies whether the media quality control is enabled. + **/ + isMediaQualityEnabled: boolean; + /** + * Gets or sets a value that specifies whether the media quality control is visible. + **/ + isMediaQualityVisible: boolean; + /** + * Gets a value that specifies whether interaction with the mute control is allowed based on the current state of the player. + **/ + isMuteAllowed: boolean; + /** + * Gets or sets a value that specifies whether the mute control is enabled. + **/ + isMuteEnabled: boolean; + /** + * Gets or sets a value that specifies whether the mute control is visible. + **/ + isMuteVisible: boolean; + /** + * Gets a value that specifies whether interaction with the pause control is allowed based on the current state of the player. + **/ + isPauseAllowed: boolean; + /** + * Gets or sets a value that specifies whether the pause control is enabled. + **/ + isPauseEnabled: boolean; + /** + * Gets or sets a value that specifies whether the pause control is visible. + **/ + isPauseVisible: boolean; + /** + * Gets a value that specifies whether interaction with the play / pause control is allowed based on the current state of the player. + **/ + isPlayPauseAllowed: boolean; + /** + * Gets or sets a value that specifies whether the play / pause control is enabled. + **/ + isPlayPauseEnabled: boolean; + /** + * Gets or sets a value that specifies whether the play / pause control is visible. + **/ + isPlayPauseVisible: boolean; + /** + * Gets a value that specifies whether interaction with the play / resume control is allowed based on the current state of the player. + **/ + isPlayResumeAllowed: boolean; + /** + * Gets or sets a value that specifies whether the play / resume control is enabled. + **/ + isPlayResumeEnabled: boolean; + /** + * Gets or sets a value that specifies whether the play / resume control is visible. + **/ + isPlayResumeVisible: boolean; + /** + * Gets a value that specifies whether interaction with the remaining time control is allowed based on the current state of the player. + **/ + isRemainingTimeAllowed: boolean; + /** + * Gets or sets a value that specifies whether the remaining time control is enabled. + **/ + isRemainingTimeEnabled: boolean; + /** + * Gets or sets a value that specifies whether the remaining time control is visible. + **/ + isRemainingTimeVisible: boolean; + /** + * Gets a value that specifies whether interaction with the replay control is allowed based on the current state of the player. + **/ + isReplayAllowed: boolean; + /** + * Gets or sets a value that specifies whether the replay control is enabled. + **/ + isReplayEnabled: boolean; + /** + * Gets or sets a value that specifies whether the replay control is visible. + **/ + isReplayVisible: boolean; + /** + * Gets a value that specifies whether interaction with the rewind control is allowed based on the current state of the player. + **/ + isRewindAllowed: boolean; + /** + * Gets or sets a value that specifies whether the rewind control is enabled. + **/ + isRewindEnabled: boolean; + /** + * Gets or sets a value that specifies whether the rewind control is visible. + **/ + isRewindVisible: boolean; + /** + * Gets a value that specifies whether interaction with the signal strength control is allowed based on the current state of the player. + **/ + isSignalStrengthAllowed: boolean; + /** + * Gets or sets a value that specifies whether the signal strength control is enabled. + **/ + isSignalStrengthEnabled: boolean; + /** + * Gets or sets a value that specifies whether the signal strength control is visible. + **/ + isSignalStrengthVisible: boolean; + /** + * Gets a value that specifies whether interaction with the skip ahead control is allowed based on the current state of the player. + **/ + isSkipAheadAllowed: boolean; + /** + * Gets or sets a value that specifies whether the skip ahead control is enabled. + **/ + isSkipAheadEnabled: boolean; + /** + * Gets or sets a value that specifies whether the skip ahead control is visible. + **/ + isSkipAheadVisible: boolean; + /** + * Gets a value that specifies whether interaction with the skip back control is allowed based on the current state of the player. + **/ + isSkipBackAllowed: boolean; + /** + * Gets or sets a value that specifies whether the skip back control is enabled. + **/ + isSkipBackEnabled: boolean; + /** + * Gets or sets a value that specifies whether the skip back control is visible. + **/ + isSkipBackVisible: boolean; + /** + * Gets a value that specifies whether interaction with the skip next control is allowed based on the current state of the player. + **/ + isSkipNextAllowed: boolean; + /** + * Gets or sets a value that specifies whether the skip next control is enabled. + **/ + isSkipNextEnabled: boolean; + /** + * Gets or sets a value that specifies whether the skip next control is visible. + **/ + isSkipNextVisible: boolean; + /** + * Gets a value that specifies whether interaction with the skip previous control is allowed based on the current state of the player. + **/ + isSkipPreviousAllowed: boolean; + /** + * Gets or sets a value that specifies whether the skip previous control is enabled. + **/ + isSkipPreviousEnabled: boolean; + /** + * Gets or sets a value that specifies whether the skip previous control is visible. + **/ + isSkipPreviousVisible: boolean; + /** + * Gets or sets a value that specifies whether the player is playing in slow motion. + **/ + isSlowMotion: boolean; + /** + * Gets a value that specifies whether interaction with the slow motion control is allowed based on the current state of the player. + **/ + isSlowMotionAllowed: boolean; + /** + * Gets or sets a value that specifies whether the slow motion control is enabled. + **/ + isSlowMotionEnabled: boolean; + /** + * Gets or sets a value that specifies whether the slow motion control is visible. + **/ + isSlowMotionVisible: boolean; + /** + * Gets or sets a value that specifies whether the start time is offset. + **/ + isStartTimeOffset: boolean; + /** + * Gets a value that specifies whether interaction with the timeline control is allowed based on the current state of the player. + **/ + isTimelineAllowed: boolean; + /** + * Gets or sets a value that specifies whether the timeline control is enabled. + **/ + isTimelineEnabled: boolean; + /** + * Gets or sets a value that specifies whether the timeline control is visible. + **/ + isTimelineVisible: boolean; + /** + * Gets a value that specifies whether interaction with the volume control is allowed based on the current state of the player. + **/ + isVolumeAllowed: boolean; + /** + * Gets or sets a value that specifies whether the volume control is enabled. + **/ + isVolumeEnabled: boolean; + /** + * Gets a value that specifies whether interaction with the volume / mute control is allowed based on the current state of the player. + **/ + isVolumeMuteAllowed: boolean; + /** + * Gets or sets a value that specifies whether the volume / mute control is enabled. + **/ + isVolumeMuteEnabled: boolean; + /** + * Gets or sets a value that specifies whether the volume / mute control is visible. + **/ + isVolumeMuteVisible: boolean; + /** + * Gets or sets a value that specifies whether the volume control is visible. + **/ + isVolumeVisible: boolean; + /** + * Gets or sets the live position (in seconds). + **/ + liveTime: number; + /** + * Gets or sets the live buffer time (in seconds) for the current playback position to be considered "live". + **/ + liveTimeBuffer: number; + /** + * Gets or sets a value that specifies whether playback should be restarted after it ends. + **/ + loop: boolean; + /** + * Gets the media element associated with the player. + **/ + mediaElement: HTMLMediaElement; + /** + * Gets or sets the media extension manager to be used by the player and its plugins.A new instance will be created on first use if one is not already set. + **/ + mediaExtensionManager: Windows.Media.MediaExtensionManager; + /** + * Gets or sets the quality of the current media source. + **/ + mediaQuality: MediaQuality; + /** + * Gets or sets a value that specifies the purpose of the media, such as background audio or alerts. + **/ + msAudioCategory: string; + /** + * Gets or sets a value that specifies the output device ID that the audio will be sent to. + **/ + msAudioDeviceType: string; + /** + * Gets or sets a value that specifies whether the media is flipped horizontally. + **/ + msHorizontalMirror: boolean; + /** + * Gets a value that specifies whether the media can be rendered more efficiently. + **/ + msIsLayoutOptimalForPlayback: boolean; + /** + * Gets a value that specifies whether the system considers the media to be stereo 3D. + **/ + msIsStereo3D: boolean; + /** + * Gets or sets a value that specifies whether the DLNA PlayTo device is available. + **/ + msPlayToDisabled: boolean; + /** + * Gets or sets the primary DLNA PlayTo device. + **/ + msPlayToPrimary: boolean; + /** + * Gets the media source for use by the PlayToManager. + **/ + msPlayToSource: Object; + /** + * Gets or sets a value that specifies whether or not to enable low - latency playback. + **/ + msRealTime: boolean; + /** + * Gets or sets the frame - packing mode for stereo 3D video content. + **/ + msStereo3DPackingMode: string; + /** + * Gets or sets a value that specifies whether the system display is set to stereo display. + **/ + msStereo3DRenderMode: string; + /** + * Gets or sets a value that specifies whether the video frame is trimmed to fit the display. + **/ + msZoom: boolean; + /** + * Gets or sets a value that indicates whether the audio is muted. + **/ + muted: boolean; + /** + * Gets the current network state for the player. + **/ + networkState: NetworkState; + /** + * Gets a value that specifies whether playback is paused. + **/ + paused: boolean; + /** + * Gets or sets the playback rate for the current media source. + **/ + playbackRate: number; + /** + * Gets the played time ranges for the current media source. + **/ + played: Array; //TODO: (type: TimeRanges, read - only) + /** + * Gets the playlist plugin. + **/ + playlistPlugin: Plugins.PlaylistPlugin; + /** + * Gets or sets the current state of the player. + **/ + playerState: PlayerState; + /* + * Gets the plugins associated with the player. + **/ + plugins: Array; //TODO: (type: ?, read - only) + /* + * Gets or sets the URL of an image to display while the current media source is loading. + **/ + poster: string; + /** + ** Gets or sets a hint to how much buffering is advisable for the current media source. + **/ + preload: string; + /** + * Gets the current readiness state of the player. + **/ + readyState: ReadyState; + /** + * Gets or sets the amount of time (in seconds) to offset the current playback position during replay. + **/ + replayOffset: number; + /** + * Gets a value that specifies whether the player is currently moving to a new playback position due to a scrub operation. + **/ + scrubbing: boolean; //TODO: (type: Boolean, read - only) + /** + * Gets the seekable time ranges of the current media source. + **/ + seekable: any; //TODO: (type: TimeRanges, read - only) + /** + * Gets a value that specifies whether the player is currently moving to a new playback position due to a seek operation. + **/ + seeking: boolean; //TODO: (type: Boolean, read - only) + /** + * Gets or sets a value that specifies whether the current video frame should be updated during a scrub operation. + **/ + seekWhileScrubbing: boolean; + /** + * Gets or sets the signal strength of the current media source.This is useful in adaptive streaming scenarios. + **/ + signalStrength: number; + /** + * Gets or sets the amount of time (in seconds) that the skip ahead control will seek forward. + **/ + skipAheadInterval: number; + /** + * Gets or sets the amount of time (in seconds) that the skip back control will seek backward. + **/ + skipBackInterval: number; + /** + * Gets or sets the playback rate to use when in slow motion. + **/ + slowMotionPlaybackRate: number; + /** + * Gets or sets the media sources to be considered. + **/ + sources: Array; //TODO: (type: Array, read / write) + /** + * Gets or sets the URL of the current media source to be considered. + **/ + src: string; + /** + * Gets or sets the start time (in seconds) of the current media source.This is useful in live streaming scenarios. + **/ + startTime: number; + /** + * Gets or sets the position (in seconds) where playback should start.This is useful for resuming a video where the user left off in a previous session. + **/ + startupTime: number; + /** + * Gets or sets whether a test for the media feature pack should be performed prior to allowing content to be laoded.This is useful to enable if Windows 8 N / KN users will be using this app. + **/ + testForMediaPack: boolean; + /** + * Gets the text tracks for the current media source. + **/ + textTracks: any; // TODO: (type: TextTrackList, read - only) + /** + * Gets or sets the tracks for the player. + **/ + tracks: Array; // TODO: (type: Array, read / write) + /** + * Gets the intrinsic height of the current video (in pixels). + **/ + videoHeight: number; + /** + * Gets the intrinsic width of the current video (in pixels). + **/ + videoWidth: number; + /** + * Gets or sets the volume level(from 0 to 1) for the audio portions of media playback. + **/ + volume: number; + /** + * Gets or sets the width of the host element. + **/ + width: string; + + /* Methods */ + + /** + * Adds the specified CSS class to the host element. + * @param name The name of the class to add. Multiple classes can be added using space-delimited names. + **/ + addClass(name: string): void; + /** + * Adds an event listener for the MediaPlayer events. + * //TODO + * @param type The type (name) of the event. You can use any of the following: "". + * @param listener The listener to invoke when the event is raised. + * @param capture true to initiate capture, otherwise false. + **/ + addEventListener(type: string, listener: Function, capture?: boolean): void; + /** + * Create a new TextTrack object to add to an HTML5 video. + * @param kind String The type of text track + * @param label String A user readable title for a text track + * @param language String The BCP47 language tag of the track. For example "en" for English or "fr" for French + **/ + addTextTrack(kind: string, label?: string, language?: string): void; + /** + * Raises the audioinvoked event used to indicate that an audio selection dialog should be presented to the user (usually in the form of a flyout). + **/ + audio(): void; + /** + * Returns a value that specifies whether the player can play a given media type. + * @param type The type of media to be played. + * @returns One of the following values: "probably", "maybe", or an empty string if the media cannot be rendered. + **/ + canPlayType(type: string): string; + /** + * Raises the captionsinvoked event used to indicate that closed options should be toggled on/off or that a caption selection dialog should be presented to the user (usually in the form of a flyout). + **/ + captions(): void; + /** + * Decreases the current playback rate by a factor of two.After the rate reaches 1(normal speed), it will flip to - 1, and then begins to rewind. + **/ + decreasePlaybackRate(): void; + /** + * Shuts down and releases all resources. + **/ + dispose(): void; + /** + * Gives focus to the host element. + **/ + focus(): void; + /** + * Increases the current playback rate by a factor of two.After the rate reaches - 1, it flips to 1(normal speed), and then begins to fast forward. + **/ + increasePlaybackRate(): void; + /** + * Raises the infoinvoked event used to indicate that more information about the current media should be displayed to the user. + **/ + info(): void; + /** + * Reloads the current media source. + **/ + load(): void; + /** + * Raises the moreinvoked event typically used to indicate that more options that were unable to fit in the control panel should be presented to the user (usually in the form of a flyout). + **/ + more(): void; + /** + * Clears all effects from the media pipeline. + **/ + msClearEffects(): void; + /** + * Steps the video forward or backward by one frame. + * @param forward If true, the video is stepped forward, otherwise the video is stepped backward. + **/ + msFrameStep(forward: boolean): void; + /** + * Inserts the specified audio effect into the media pipeline. + * @param activatableClassId The audio effects class. + * @param effectRequired + * @param config + **/ + msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config: Object): void; + /** + * Inserts the specified video effect into the media pipeline. + * @param activatableClassId The video effects class. + * @param effectRequired + * @param config + **/ + msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config: Object): void + /** + * Sets the MSMediaKeys to be used for decrypting media data. + * @param mediaKeys The media keys to use for decrypting media data. + **/ + msSetMediaKeys(mediaKeys: MSMediaKeys): void; + /** + * Sets the media protection manager for a given media pipeline. + * @param mediaProtectionManager + **/ + msSetMediaProtectionManager(mediaProtectionManager: Windows.Media.Protection.MediaProtectionManager): void; + /** + * Sets the dimensions of a sub - rectangle within a video. + * @param left The left position of the rectangle. + * @param top The top position of the rectangle. + * @param right The right position of the rectangle. + * @param bottom The bottom position of the rectangle. + **/ + msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; + /** + * Pauses playback of the current media source. + **/ + pause(): void; + /** + * Loads and starts playback of the current media source. + **/ + play(): void; + /** + * Resets the playback rate and resumes playing the current media source. + **/ + playResume(): void; + /** + * Removes the specified CSS class from the host element. + * @param name The name of the class to remove. Multiple classes can be removed using space-delimited names. + **/ + removeClass(name: string): void; + /** + * Removes an event listener from the media player control. + * @param type The type (name) of the event. You can use any of the following: "". //TODO + * @param eventHandler The listener to remove. + **/ + removeEventListener(eventName: string, eventHandler: Function): void; + /** + * Supports instant replay by applying an offset to the current playback position. + **/ + replay(): void; + /** + * Reloads the current media source and resumes where playback was left off. + **/ + retry(): void; + /** + * Stops playback and raises the stopped event. + **/ + stop(): void; + /** + * Updates the player and its plugins with the specified media source(e.g.the current playlist item). + * @param mediaSource A JSON object containing the set of options that represent a media source. + **/ + update(mediaSource: Object): void; + } + + class DynamicTextTrack { + stream: any; + label: string; + language: string; + augmentPayload(payload: any, startTime: number, endTime: number): void; + } + + module UI { + class Button { + element: HTMLElement; + type: string; + content: string; + hoverContent: string; + label: string; + tooltip: string; + disabled: boolean; + hidden: boolean; + flyout: Element; + } + + class ControlPanel { + element: HTMLElement; + hidden: boolean; + isPlayPauseHidden: boolean; + isPlayResumeHidden: boolean; + isPauseHidden: boolean; + isReplayHidden: boolean; + isRewindHidden: boolean; + isFastForwardHidden: boolean; + isSlowMotionHidden: boolean; + isSkipPreviousHidden: boolean; + isSkipNextHidden: boolean; + isSkipBackHidden: boolean; + isSkipAheadHidden: boolean; + isElapsedTimeHidden: boolean; + isRemainingTimeHidden: boolean; + isTotalTimeHidden: boolean; + isTimelineHidden: boolean; + isGoLiveHidden: boolean; + isCaptionsHidden: boolean; + isAudioHidden: boolean; + isVolumeMuteHidden: boolean; + isVolumeHidden: boolean; + isMuteHidden: boolean; + isFullScreenHidden: boolean; + isStopHidden: boolean; + isInfoHidden: boolean; + isMoreHidden: boolean; + isZoomHidden: boolean; + isSignalStrengthHidden: boolean; + isMediaQualityHidden: boolean; + flyoutContainerElement: HTMLElement; + } + + class Indicator { + element: HTMLElement; + value: string; + label: string; + tooltip: string; + disabled: boolean; + hidden: boolean; + } + + class Meter { + element: HTMLElement; + value: number; + label: string; + tooltip: string; + disabled: boolean; + hidden: boolean; + } + + class Slider { + element: HTMLElement; + min: number; + max: number; + value: number; + progress: number; + step: number; + altStep1: number; + altStep2: number; + altStep3: number; + label: string; + tooltip: string; + vertical: boolean; + disabled: boolean; + hidden: boolean; + markers: Array; + thumbnailImageSrc: string; + isThumbnailVisible: boolean; + } + + + } +} + +declare module PlayerFramework.Advertising { + interface AdvertisementBase { + source: any; + } + + class PrerollAdvertisement implements AdvertisementBase { + source: any; + } + + class MidrollAdvertisement implements AdvertisementBase { + source: any; + time: number; + timePercentage: number; + } +} + + +declare module Microsoft.VideoAdvertising { + class VastAdPayloadHandler { + static adType: string; + } + + class Extensions { + static defaultUserAgent: string; + } +} + +declare module Microsoft.PlayerFramework.Js.Advertising { + /** + * Provides an ad source that requires a Url to be downloaded and turned into a stream before passing to the ad handler. + **/ + class RemoteAdSource { + + } +} \ No newline at end of file diff --git a/pouchDB/pouch.d.ts b/pouchDB/pouch.d.ts index 47ffcad60..40a28cf23 100644 --- a/pouchDB/pouch.d.ts +++ b/pouchDB/pouch.d.ts @@ -217,6 +217,12 @@ interface PouchDB extends PouchApi { } declare var PouchDB: PouchDB; + +// Support AMD require +declare module 'pouchdb' { + export = PouchDB; +} + // // emit is the function that the PouchFilter.map function should call in order to add a particular item to // a filter view. diff --git a/promises-a-plus/promises-a-plus-tests.ts b/promises-a-plus/promises-a-plus-tests.ts index bba258649..bf6cc5ce0 100644 --- a/promises-a-plus/promises-a-plus-tests.ts +++ b/promises-a-plus/promises-a-plus-tests.ts @@ -2,8 +2,7 @@ /// /// /// -import When = require("../when/when"); - +/// var thenNum: PromisesAPlus.Thenable; var thenStr: PromisesAPlus.Thenable; diff --git a/q/Q-tests.ts b/q/Q-tests.ts index 48a3224bc..ff540bd6b 100644 --- a/q/Q-tests.ts +++ b/q/Q-tests.ts @@ -94,6 +94,7 @@ Q.fbind((dateString?: string) => new Date(dateString), "11/11/1991")().then(d => Q.when(8, num => num + "!"); Q.when(Q(8), num => num + "!").then(str => str.split(',')); +var voidPromise: Q.Promise = Q.when(); declare function saveToDisk(): Q.Promise; declare function saveToCloud(): Q.Promise; @@ -137,4 +138,50 @@ class Repo { } var kitty = new Repo(); -Q.nbind(kitty.find, kitty)({ cute: true }).done((kitties: any[]) => {}); \ No newline at end of file +Q.nbind(kitty.find, kitty)({ cute: true }).done((kitties: any[]) => {}); + + +/* + * Test: Can "rethrow" rejected promises + */ +module TestCanRethrowRejectedPromises { + + interface Foo { + a: number; + } + + function nestedBar(): Q.Promise { + var deferred = Q.defer(); + + return deferred.promise; + } + + function bar(): Q.Promise { + return nestedBar() + .then((foo:Foo) => { + console.log("Lorem ipsum"); + }) + .fail((error) => { + console.log("Intermediate error handling"); + + /* + * Cannot do this, because: + * error TS2322: Type 'Promise' is not assignable to type 'Promise' + */ + //throw error; + + return Q.reject(error); + }) + ; + } + + bar() + .finally(() => { + console.log("Cleanup") + }) + .done() + ; + +} + + diff --git a/q/Q.d.ts b/q/Q.d.ts index 59e891c52..25411a550 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -3,18 +3,11 @@ // Definitions by: Barrie Nemetchek , Andrew Gaspar , John Reilly // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - /** * If value is a Q promise, returns the promise. * If value is a promise from another library it is coerced into a Q promise (where possible). */ declare function Q(promise: Q.IPromise): Q.Promise; -/** - * If value is a Q promise, returns the promise. - * If value is a promise from another library it is coerced into a Q promise (where possible). - */ -declare function Q(promise: JQueryPromise): Q.Promise; /** * If value is not a promise, returns a promise that is fulfilled with value. */ @@ -74,8 +67,8 @@ declare module Q { */ spread(onFulfilled: Function, onRejected?: Function): Promise; - fail(onRejected: (reason: any) => U): Promise; fail(onRejected: (reason: any) => IPromise): Promise; + fail(onRejected: (reason: any) => U): Promise; /** * A sugar method, equivalent to promise.then(undefined, onRejected). */ @@ -188,6 +181,9 @@ declare module Q { reason?: any; } + // If no value provided, returned promise will be of void type + export function when(): Promise; + // if no fulfill, reject, or progress provided, returned promise will be of same type export function when(value: IPromise): Promise; export function when(value: T): Promise; @@ -329,7 +325,7 @@ declare module Q { /** * Returns a promise that is rejected with reason. */ - export function reject(reason?: any): Promise; + export function reject(reason?: any): Promise; export function Promise(resolver: (resolve: (val: IPromise) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise; export function Promise(resolver: (resolve: (val: T) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise; diff --git a/rest/rest-tests.ts b/rest/rest-tests.ts new file mode 100644 index 000000000..4ffe17d21 --- /dev/null +++ b/rest/rest-tests.ts @@ -0,0 +1,40 @@ +/// + +import rest = require('rest'); +import mime = require('rest/interceptor/mime'); +import errorCode = require('rest/interceptor/errorCode'); +import registry = require('rest/mime/registry'); + +rest('/').then(function(response) { + console.log('response: ', response); +}); + + +var client = rest.wrap(mime); +client({ path: '/data.json' }).then(function(response) { + console.log('response: ', response); +}); + +client = rest.wrap(mime).wrap(errorCode, { code: 500 }); +client({ path: '/data.json' }).then( + function(response) { + console.log('response: ', response); + }, + function(response) { + console.error('response error: ', response); + } +); + +registry.register('application/vnd.com.example', { + read: function(str: string) { + var obj: any; + // do string to object conversions + return obj; + }, + write: function(obj: any) { + var str: string; + // do object to string conversions + return str; + } +}); + diff --git a/rest/rest.d.ts b/rest/rest.d.ts new file mode 100644 index 000000000..34ffc3bf2 --- /dev/null +++ b/rest/rest.d.ts @@ -0,0 +1,92 @@ +// Type definitions for rest.js v1.2.0 +// Project: https://github.com/cujojs/rest +// Definitions by: Wim Looman +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "rest" { + import when = require("when"); + + export = rest; + + function rest(path: string): rest.ResponsePromise; + function rest(request: rest.Request): rest.ResponsePromise; + + module rest { + export function wrap(interceptor: Interceptor): Client; + + export interface Request { + method?: string; + path?: string; + params?: any; + headers?: any; + entity?: any; + } + + export interface Status { + code: number; + text?: string; + } + + export interface Headers { + [index: string]: any // string or string[] + } + + export interface Response { + request: Request; + raw: any; + status: Status; + headers: Headers; + entity: any; + } + + export interface ResponsePromise extends when.Promise { + entity(): when.Promise; + status(): when.Promise; + headers(): when.Promise; + header(headerName: string): when.Promise; // string or string[] + } + + export interface Interceptor { + (parent?: Client, config?: any): Client; + } + + export interface Client { + (path: string): ResponsePromise; + (request: Request): ResponsePromise; + + skip(): Client; + wrap(interceptor: Interceptor, config?: any): Client; + } + } +} + +declare module "rest/interceptor/errorCode" { + import rest = require("rest"); + + var errorCode: rest.Interceptor; + + export = errorCode; +} + +declare module "rest/interceptor/mime" { + import rest = require("rest"); + + var mime: rest.Interceptor; + + export = mime; +} + +declare module "rest/mime/registry" { + import when = require("when"); + + export interface MIMEConverter { + read(value: string): any; // any or when.Promise; + write(value: any): any; // string or when.Promise; + } + + export function lookup(mimeType: string): when.Promise; + + export function register(mimeType: string, converter: MIMEConverter): void; +} diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 417ea1e2f..9ea16186d 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -7241,7 +7241,7 @@ declare module SP { } export class Status { - static addStatus(strTitle: string, strHtml: string, atBegining: boolean): string; + static addStatus(strTitle: string, strHtml?: string, atBegining?: boolean): string; static appendStatus(sid: string, strTitle: string, strHtml: string): string; static updateStatus(sid: string, strHtml: string): void; static setStatusPriColor(sid: string, strColor: string): void; @@ -8410,11 +8410,11 @@ declare module SP.WorkflowServices { /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - get_restrictScope(): string; + get_restrictToScope(): string; /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - set_restrictScope(value: string): string; + set_restrictToScope(value: string): string; /** RestrictToType determines the possible event source type for a workflow subscription that uses this definition. Possible values include "List", "Site", the empty string, or null. */ get_restrictToType(): string; diff --git a/slickgrid/SlickGrid.d.ts b/slickgrid/SlickGrid.d.ts index 36ac6a3b3..904e4f127 100644 --- a/slickgrid/SlickGrid.d.ts +++ b/slickgrid/SlickGrid.d.ts @@ -1500,7 +1500,8 @@ declare module Slick { public fastSort(field: string, ascending: boolean): void; public fastSort(field: Function, ascending: boolean): void; // todo: typeof(field), should be the same callback as Array.sort public reSort(): void; - public setGrouping(groupingInfo: GroupingOptions[]): void; + public setGrouping(groupingInfos: GroupingOptions[]): void; + public setGrouping(groupingInfo: GroupingOptions): void; public getGrouping(): GroupingOptions[]; /** diff --git a/snapsvg/snapsvg-tests.ts b/snapsvg/snapsvg-tests.ts new file mode 100644 index 000000000..b07bc2007 --- /dev/null +++ b/snapsvg/snapsvg-tests.ts @@ -0,0 +1,83 @@ +//Copied from the snap homepage http://snapsvg.io/ + +/// +// First lets create our drawing surface out of existing SVG element +// If you want to create new surface just provide dimensions +// like s = Snap(800, 600); +var s = Snap("#svg"); +// Lets create big circle in the middle: +var bigCircle = s.circle(150, 150, 100); +// By default its black, lets change its attributes +bigCircle.attr({ + fill: "#bada55", + stroke: "#000", + strokeWidth: 5 +}); +// Now lets create another small circle: +var smallCircle = s.circle(100, 150, 70); +// Lets put this small circle and another one into a group: +var discs = s.group(smallCircle, s.circle(200, 150, 70)); +// Now we can change attributes for the whole group +discs.attr({ + fill: "#fff" +}); +// Now more interesting stuff +// Lets assign this group as a mask for our big circle +bigCircle.attr({ + mask: discs +}); +// Despite our small circle now is a part of a group +// and a part of a mask we could still access it: +smallCircle.animate({ r: 50 }, 1000); +// We don’t have reference for second small circle, +// but we could easily grab it with CSS selectors: +discs.select("circle:nth-child(2)").animate({ r: 50 }, 1000); +// Now lets create pattern +var p = s.path("M10-5-10,15M15,0,0,15M0-5-20,15").attr({ + fill: "none", + stroke: "#bada55", + strokeWidth: 5 +}); +// To create pattern, +// just specify dimensions in pattern method: +p = p.pattern(0, 0, 10, 10); +// Then use it as a fill on big circle +bigCircle.attr({ + fill: p +}); +// We could also grab pattern from SVG +// already embedded into our page +discs.attr({ + fill: Snap("#pattern") +}); +// Lets change fill of circles to gradient +// This string means relative radial gradient +// from white to black +discs.attr({ fill: "r()#fff-#000" }); +// Note that you have two gradients for each circle +// If we want them to share one gradient, +// we need to use absolute gradient with capital R +discs.attr({ fill: "R(150, 150, 100)#fff-#000" }); +// Of course we could animate color as well +p.select("path").animate({ stroke: "#f00" }, 1000); +// Now lets load external SVG file: +Snap.load("mascot.svg", function (f:Snap.Fragment) { + // Note that we traversre and change attr before SVG + // is even added to the page + f.selectAll("polygon[fill='#09B39C']").attr({ fill: "#bada55" }); + var g = f.select("g"); + s.append(g); + // Making croc draggable. Go ahead drag it around! + g.drag(); + // Obviously drag could take event handlers too + // That’s better! selectAll for the rescue. +}); +// Writing text as simple as: +s.text(200, 100, "Snap.svg"); +// Provide an array of strings (or arrays), to generate tspans +var t = s.text(200, 120, ["Snap", ".", "svg"]); +t.selectAll("tspan:nth-child(3)").attr({ + fill: "#900", + "font-size": "20px" +}); + diff --git a/snapsvg/snapsvg.d.ts b/snapsvg/snapsvg.d.ts new file mode 100644 index 000000000..821f27de0 --- /dev/null +++ b/snapsvg/snapsvg.d.ts @@ -0,0 +1,289 @@ +// Type definitions for Snap-SVG 0.3 +// Project: https://github.com/adobe-webplatform/Snap.svg +// Definitions by: Lars Klein +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare function mina(a:number, A:number, b:number, B:number, get:Function, set:Function, easing?:Function):Object; +declare module mina { + export interface Mina { + id: string; + duration: Function; + easing: Function; + speed: Function; + status: Function; + stop: Function; + } + + export function backin(n:number):number; + export function backout(n:number):number; + export function bounce(n:number):number; + export function easein(n:number):number; + export function easeinout(n:number):number; + export function easeout(n:number):number; + export function elastic(n:number):number; + export function getById(id:string):Object; + export function linear(n:number):number; + export function time():number; +} + +declare function Snap(width:number,height:number):Snap.Paper; +declare function Snap(query:string):Snap.Paper; +declare function Snap(DOM:SVGElement):Snap.Paper; + +declare module Snap { + + export var filter:Filter; + export var path:Path; + + export function Matrix(a:number,b:number,c:number,d:number,e:number,f:number):Matrix; + export function Matrix(svgMatrix:SVGMatrix):Matrix; + + export function ajax(url:string,postData:string,callback:Function,scope?:Object):XMLHttpRequest; + export function ajax(url:string,postData:Object,callback:Function,scope?:Object):XMLHttpRequest; + export function ajax(url:string,callback:Function,scope?:Object):XMLHttpRequest; + export function format(token:string,json:Object):string; + export function fragment(varargs:any):Fragment; + export function getElementByPoint(x:number,y:number):Object; + export function is(o:any,type:string):boolean; + export function load(url:string,callback:Function,scope?:Object):void; + export function plugin(f:Function):void; + export function select(query:string):Snap.Element; + export function selectAll(query:string):any; + export function snapTo(values:Array,value:number,tolerance?:number):number; + + export function animate(from:number,to:number,setter:Function,duration:number,easing:Function,callback:Function):mina.Mina; + export function animate(from:Array,to:number,setter:Function,duration:number,easing:Function,callback:Function):mina.Mina; + export function animate(from:number,to:Array,setter:Function,duration:number,easing:Function,callback:Function):mina.Mina; + export function animate(from:Array,to:Array,setter:Function,duration:number,easing:Function,callback:Function):mina.Mina; + export function animation(attr:Object,duration:number,easing?:Function,callback?:Function):Object; + + export function color(clr:string):Object;export function getRGB(color:string):Object; + export function hsb(h:number,s:number,b:number):HSB; + export function hsl(h:number,s:number,l:number):HSL; + export function rgb(r:number,g:number,b:number):RGB; + export function hsb2rgb(h:number,s:number,v:number):RGB; + export function hsl2rgb(h:number,s:number,l:number):RGB; + export function rgb2hsb(r:number,g:number,b:number):HSB; + export function rgb2hsl(r:number,g:number,b:number):HSL; + + export function angle(x1:number,y1:number,x2:number,y2:number,x3?:number,y3?:number):number; + export function rad(deg:number):number; + export function deg(rad:number):number; + + export function parse(svg:string):Fragment; + export function parsePathString(pathString:string):Array; + export function parsePathString(pathString:Array):Array; + export function parseTransformString(TString:string):Array; + export function parseTransformString(TString:Array):Array; + + export interface RGB{ + r:number; + g:number; + b:number; + hex:string; + } + + export interface HSB{ + h:number; + s:number; + b:number; + } + export interface HSL{ + h:number; + s:number; + l:number; + } + + export interface BBox{ + cx:number; + cy:number; + h:number; + height:number; + path:number; + r0:number; + r1:number; + r2:number; + vb:string; + w:number; + width:number; + x2:number; + x:number; + y2:number; + y:number; + } + + export interface Element { + add():void; + addClass(value:string):Snap.Element; + after(el:Snap.Element):Snap.Element; + animate(attrs:Object,duration:number,easing?:Function,callback?:Function):Snap.Element; + animate(animation:any):Snap.Element; + append(el:Snap.Element):Snap.Element; + appendTo(el:Snap.Element):Snap.Element; + asPX(attr:string,value?:string):Snap.Element; + attr(params:Object):Snap.Element; + attr(param:string):string; + before(el:Snap.Element):Snap.Element; + clone():Snap.Element; + data(key:string,value?:any):any; + getBBox():BBox; + getPointAtLength(length:number):Object; + getSubpath(from:number,to:number):string; + getTotalLength():number; + hasClass(value:string):boolean; + inAnim():Object; + innerSVG():string; + insertAfter(el:Snap.Element):Snap.Element; + insertBefore(el:Snap.Element):Snap.Element; + marker(x:number,y:number,width:number,height:number,refX:number,refY:number):Snap.Element; + node:Element; + outerSVG():string; + parent():Snap.Element; + pattern(x:any,y:any,width:any,height:any):Snap.Element; + prepend(el:Snap.Element):Snap.Element; + prependTo(el:Snap.Element):Snap.Element; + remove():Snap.Element; + removeClass(value:string):Snap.Element; + removeData(key?:string):Snap.Element; + select(query:string):Snap.Element; + selectAll(query: string): Snap.Set; + selectAll(): Snap.Set; + stop():Snap.Element; + toDefs():Snap.Element; + toPattern(x:number,y:number,width:number,height:number):Object; + toPattern(x:string,y:string,width:string,height:string):Object; + toString():string; + toggleClass(value:string,flag:boolean):Snap.Element; + transform(tstr:string):any; + type:string; + use():Object; + + click(handler:Function):Snap.Element; + unclick(handler:Function):Snap.Element; + dblclick(handler:Function):Snap.Element; + undblclick(handler:Function):Snap.Element; + mousedown(handler:Function):Snap.Element; + unmousedown(handler:Function):Snap.Element; + mousemove(handler:Function):Snap.Element; + unmousemove(handler:Function):Snap.Element; + mouseout(handler:Function):Snap.Element; + unmouseout(handler:Function):Snap.Element; + mouseover(handler:Function):Snap.Element; + unmouseover(handler:Function):Snap.Element; + mouseup(handler:Function):Snap.Element; + unmouseup(handler:Function):Snap.Element; + touchstart(handler:Function):Snap.Element; + untouchstart(handler:Function):Snap.Element; + touchmove(handler:Function):Snap.Element; + untouchmove(handler:Function):Snap.Element; + touchend(handler:Function):Snap.Element; + untouchend(handler:Function):Snap.Element; + touchcancel(handler:Function):Snap.Element; + untouchcancel(handler:Function):Snap.Element; + hover(f_in:Function,f_out:Function,icontext?:Object,ocontext?:Object):Snap.Element; + unhover(f_in: Function, f_out: Function): Snap.Element; + drag(): void; + drag(onmove:Function,onstart:Function,onend:Function,mcontext?:Object,scontext?:Object,econtext?:Object):Snap.Element; + undrag():Snap.Element; + } + + export interface Fragment { + //TODO: The documentation says that selectAll returns a set, but the getting started guide + // uses .attr on the returned object. That's not supported by a set + select(query:string):Snap.Element; + selectAll(query:string):Snap.Set; + selectAll():Snap.Set; + } + + export interface Matrix { + add(a:number,b:number,c:number,d:number,e:number,f:number):void; + add(matrix:Matrix):void; + clone():Matrix; + determinant():number; + invert():Matrix; + rotate(a:number,x:number,y:number):void; + scale(x:number,y?:number,cx?:number,cy?:number):void; + split():Object; + toTransformString():string; + translate(x:number,y:number):void; + x(x:number,y:number):number; + y(x:number,y:number):number; + + } + + interface Paper extends Snap.Element { + + clear():void; + el(name:string, attr:Object):Snap.Element; + gradient(gradient:string):any; + g(varargs:any):Object; + group(el:any,...els:any[]):any; + mask(varargs:any):Object; + ptrn(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object; + svg(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object; + toString():string; + use(id?:string):Object; + use(id?:Snap.Element):Object; + + circle(x:number,y:number,r:number):Snap.Element; + ellipse(x:number,y:number,rx:number,ry:number):Snap.Element; + image(src:string,x:number,y:number,width:number,height:number):Snap.Element; + line(x1:number,y1:number,x2:number,y2:number):Snap.Element; + path(pathString?:string):Snap.Element; + polygon(varargs:any[]):Snap.Element; + polyline(varargs:any[]):Snap.Element; + rect(x:number,y:number,width:number,height:number,rx?:number,ry?:number):Snap.Element; + text(x:number,y:number,text:string):Snap.Element; + text(x:number,y:number,text:Array):Snap.Element; + } + + export interface Set { + animate(attrs:Object,duration:number,easing?:Function,callback?:Function):Snap.Element; + attr(params: Object): Snap.Element; + attr(param: string): string; + bind(attr: string, callback: Function): Snap.Set; + bind(attr:string,element:Snap.Element):Snap.Set; + bind(attr:string,element:Snap.Element,eattr:string):Snap.Set; + clear():Snap.Set; + exclude(element:Snap.Element):boolean; + forEach(callback:Function,thisArg?:Object):Snap.Set; + pop():Snap.Element; + push(el:Snap.Element):Snap.Element; + push(els:Snap.Element[]):Snap.Element; + splice(index:number,count:number,insertion?:Object[]):Snap.Element[]; + } + + interface Filter { + blur(x:number,y?:number):string; + brightness(amount:number):string; + contrast(amount:number):string; + grayscale(amount:number):string; + hueRotate(angle:number):string; + invert(amount:number):string; + saturate(amount:number):string; + sepia(amount:number):string; + shadow(dx:number,dy:number,blur?:number,color?:string,opacity?:number):string; + } + + interface Path { + bezierBBox(...args:number[]):Object; + bezierBBox(bez:Array):Object; + findDotsAtSegment(p1x:number,p1y:number,c1x:number, + c1y:number,c2x:number,c2y:number, + p2x:number,p2y:number,t:number):Object; + getBBox(path:string):Object; + getPointAtLength(path:string,length:number):Object; + getSubpath(path:string,from:number,to:number):string; + getTotalLength(path:string):number; + intersection(path1:string,path2:string):Array; + isBBoxIntersect(bbox1:string,bbox2:string):boolean + isPointInside(path:string,x:number,y:number):boolean; + isPointInsideBBox(bbox:string,x:string,y:string):boolean; + map(path:string,matrix:Snap.Matrix):string; + map(path:string,matrix:Object):string; + toAbsolute(path:string):Array; + toCubic(pathString:string):Array; + toCubic(pathString:Array):Array; + toRelative(path:string):Array; + } +} diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 02179ff15..b1660aa7e 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3674,7 +3674,7 @@ declare module THREE { /** * Adds v to this vector. */ - add(a: Object): Vector3; + add(a: Vector): Vector3; addScalar(s: number): Vector3; /** @@ -5434,7 +5434,7 @@ declare module THREE { }; } - export class PlaneBufferGeometry extends Geometry { + export class PlaneBufferGeometry extends BufferGeometry { constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); parameters: { @@ -5445,7 +5445,15 @@ declare module THREE { }; } - export class PlaneGeometry extends PlaneBufferGeometry { + export class PlaneGeometry extends Geometry { + constructor(width: number, height: number, widthSegments?: number, heightSegments?: number); + + parameters: { + width: number; + height: number; + widthSegments: number; + heightSegments: number; + }; } export class PolyhedronGeometry extends Geometry { @@ -5759,4 +5767,4 @@ declare module THREE { declare module 'three' { export=THREE; -} \ No newline at end of file +} diff --git a/timezonecomplete/timezonecomplete-1.9.0.d.ts b/timezonecomplete/timezonecomplete-1.9.0.d.ts new file mode 100644 index 000000000..0490ee94d --- /dev/null +++ b/timezonecomplete/timezonecomplete-1.9.0.d.ts @@ -0,0 +1,1207 @@ +// Type definitions for timezonecomplete 1.9.0 +// Project: https://github.com/SpiritIT/timezonecomplete +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Generated by dts-bundle v0.2.0 + +declare module 'timezonecomplete-1.9.0' { + import basics = require("__timezonecomplete/basics"); + export import TimeUnit = basics.TimeUnit; + export import WeekDay = basics.WeekDay; + export import timeUnitToMilliseconds = basics.timeUnitToMilliseconds; + export import isLeapYear = basics.isLeapYear; + export import daysInMonth = basics.daysInMonth; + export import daysInYear = basics.daysInYear; + export import firstWeekDayOfMonth = basics.firstWeekDayOfMonth; + export import lastWeekDayOfMonth = basics.lastWeekDayOfMonth; + export import weekDayOnOrAfter = basics.weekDayOnOrAfter; + export import weekDayOnOrBefore = basics.weekDayOnOrBefore; + export import weekNumber = basics.weekNumber; + export import weekOfMonth = basics.weekOfMonth; + export import dayOfYear = basics.dayOfYear; + export import secondOfDay = basics.secondOfDay; + import datetime = require("__timezonecomplete/datetime"); + export import DateTime = datetime.DateTime; + import duration = require("__timezonecomplete/duration"); + export import Duration = duration.Duration; + import javascript = require("__timezonecomplete/javascript"); + export import DateFunctions = javascript.DateFunctions; + import period = require("__timezonecomplete/period"); + export import Period = period.Period; + export import PeriodDst = period.PeriodDst; + export import periodDstToString = period.periodDstToString; + import timesource = require("__timezonecomplete/timesource"); + export import TimeSource = timesource.TimeSource; + export import RealTimeSource = timesource.RealTimeSource; + import timezone = require("__timezonecomplete/timezone"); + export import NormalizeOption = timezone.NormalizeOption; + export import TimeZoneKind = timezone.TimeZoneKind; + export import TimeZone = timezone.TimeZone; + import globals = require("__timezonecomplete/globals"); + export import min = globals.min; + export import max = globals.max; +} + +declare module '__timezonecomplete/basics' { + import javascript = require("__timezonecomplete/javascript"); + /** + * Day-of-week. Note the enum values correspond to JavaScript day-of-week: + * Sunday = 0, Monday = 1 etc + */ + export enum WeekDay { + Sunday = 0, + Monday = 1, + Tuesday = 2, + Wednesday = 3, + Thursday = 4, + Friday = 5, + Saturday = 6, + } + /** + * Time units + */ + export enum TimeUnit { + Second = 0, + Minute = 1, + Hour = 2, + Day = 3, + Week = 4, + Month = 5, + Year = 6, + } + /** + * Approximate number of milliseconds for a time unit. + * A day is assumed to have 24 hours, a month is assumed to equal 30 days + * and a year is set to 365 days. + * + * @param unit Time unit e.g. TimeUnit.Month + * @returns The number of milliseconds. + */ + export function timeUnitToMilliseconds(unit: TimeUnit): number; + /** + * @return True iff the given year is a leap year. + */ + export function isLeapYear(year: number): boolean; + /** + * The days in a given year + */ + export function daysInYear(year: number): number; + /** + * @param year The full year + * @param month The month 1-12 + * @return The number of days in the given month + */ + export function daysInMonth(year: number, month: number): number; + /** + * Returns the day of the year of the given date [0..365]. January first is 0. + * + * @param year The year e.g. 1986 + * @param month Month 1-12 + * @param day Day of month 1-31 + */ + export function dayOfYear(year: number, month: number, day: number): number; + /** + * Returns the last instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the last occurrence of the week day in the month + */ + export function lastWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the first instance of the given weekday in the given month + * + * @param year The year + * @param month the month 1-12 + * @param weekDay the desired week day + * + * @return the first occurrence of the week day in the month + */ + export function firstWeekDayOfMonth(year: number, month: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is >= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrAfter(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * Returns the day-of-month that is on the given weekday and which is <= the given day. + * Throws if the month has no such day. + */ + export function weekDayOnOrBefore(year: number, month: number, day: number, weekDay: WeekDay): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @param year The year + * @param month The month [1-12] + * @param day The day [1-31] + * @return Week number [1-5] + */ + export function weekOfMonth(year: number, month: number, day: number): number; + /** + * The ISO 8601 week number for the given date. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @param year Year e.g. 1988 + * @param month Month 1-12 + * @param day Day of month 1-31 + * + * @return Week number 1-53 + */ + export function weekNumber(year: number, month: number, day: number): number; + /** + * Convert a unix milli timestamp into a TimeT structure. + * This does NOT take leap seconds into account. + */ + export function unixToTimeNoLeapSecs(unixMillis: number): TimeStruct; + /** + * Convert a year, month, day etc into a unix milli timestamp. + * This does NOT take leap seconds into account. + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + export function timeToUnixNoLeapSecs(year?: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, milli?: number): number; + /** + * Convert a TimeT structure into a unix milli timestamp. + * This does NOT take leap seconds into account. + */ + export function timeToUnixNoLeapSecs(tm: TimeStruct): number; + /** + * Return the day-of-week. + * This does NOT take leap seconds into account. + */ + export function weekDayNoLeapSecs(unixMillis: number): WeekDay; + /** + * N-th second in the day, counting from 0 + */ + export function secondOfDay(hour: number, minute: number, second: number): number; + /** + * Basic representation of a date and time + */ + export class TimeStruct { + /** + * Year, 1970-... + */ + year: number; + /** + * Month 1-12 + */ + month: number; + /** + * Day of month, 1-31 + */ + day: number; + /** + * Hour 0-23 + */ + hour: number; + /** + * Minute 0-59 + */ + minute: number; + /** + * Seconds, 0-59 + */ + second: number; + /** + * Milliseconds 0-999 + */ + milli: number; + /** + * Create a TimeStruct from a number of unix milliseconds + */ + static fromUnix(unixMillis: number): TimeStruct; + /** + * Create a TimeStruct from a JavaScript date + * + * @param d The date + * @param df Which functions to take (getX() or getUTCX()) + */ + static fromDate(d: Date, df: javascript.DateFunctions): TimeStruct; + /** + * Returns a TimeStruct from an ISO 8601 string WITHOUT time zone + */ + static fromString(s: string): TimeStruct; + /** + * Constructor + * + * @param year Year e.g. 1970 + * @param month Month 1-12 + * @param day Day 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 (no leap seconds) + * @param milli Millisecond 0-999 + */ + constructor(/** + * Year, 1970-... + */ + year?: number, /** + * Month 1-12 + */ + month?: number, /** + * Day of month, 1-31 + */ + day?: number, /** + * Hour 0-23 + */ + hour?: number, /** + * Minute 0-59 + */ + minute?: number, /** + * Seconds, 0-59 + */ + second?: number, /** + * Milliseconds 0-999 + */ + milli?: number); + /** + * Validate a TimeStruct, returns false if invalid. + */ + validate(): boolean; + /** + * The day-of-year 0-365 + */ + yearDay(): number; + /** + * Returns this time as a unix millisecond timestamp + * Does NOT take leap seconds into account. + */ + toUnixNoLeapSecs(): number; + /** + * Deep equals + */ + equals(other: TimeStruct): boolean; + /** + * < operator + */ + lessThan(other: TimeStruct): boolean; + clone(): TimeStruct; + valueOf(): number; + /** + * ISO 8601 string YYYY-MM-DDThh:mm:ss.nnn + */ + toString(): string; + inspect(): string; + } +} + +declare module '__timezonecomplete/datetime' { + import basics = require("__timezonecomplete/basics"); + import duration = require("__timezonecomplete/duration"); + import javascript = require("__timezonecomplete/javascript"); + import timesource = require("__timezonecomplete/timesource"); + import timezone = require("__timezonecomplete/timezone"); + /** + * DateTime class which is time zone-aware + * and which can be mocked for testing purposes. + */ + export class DateTime { + /** + * Actual time source in use. Setting this property allows to + * fake time in tests. DateTime.nowLocal() and DateTime.nowUtc() + * use this property for obtaining the current time. + */ + static timeSource: timesource.TimeSource; + /** + * Current date+time in local time (derived from DateTime.timeSource.now()). + */ + static nowLocal(): DateTime; + /** + * Current date+time in UTC time (derived from DateTime.timeSource.now()). + */ + static nowUtc(): DateTime; + /** + * Current date+time in the given time zone (derived from DateTime.timeSource.now()). + * @param timeZone The desired time zone. + */ + static now(timeZone: timezone.TimeZone): DateTime; + /** + * Constructor. Creates current time in local timezone. + */ + constructor(); + /** + * Constructor + * Non-existing local times are normalized by rounding up to the next DST offset. + * + * @param isoString String in ISO 8601 format. Instead of ISO time zone, + * it may include a space and then and IANA time zone. + * e.g. "2007-04-05T12:30:40.500" (no time zone, naive date) + * e.g. "2007-04-05T12:30:40.500+01:00" (UTC offset without daylight saving time) + * or "2007-04-05T12:30:40.500Z" (UTC) + * or "2007-04-05T12:30:40.500 Europe/Amsterdam" (IANA time zone, with daylight saving time if applicable) + * @param timeZone if given, the date in the string is assumed to be in this time zone. + * Note that it is NOT CONVERTED to the time zone. Useful + * for strings without a time zone + */ + constructor(isoString: string, timeZone?: timezone.TimeZone); + /** + * Constructor. You provide a date, then you say whether to take the + * date.getYear()/getXxx methods or the date.getUTCYear()/date.getUTCXxx methods, + * and then you state which time zone that date is in. + * Non-existing local times are normalized by rounding up to the next DST offset. + * Note that the Date class has bugs and inconsistencies when constructing them with times around + * DST changes. + * + * @param date A date object. + * @param getters Specifies which set of Date getters contains the date in the given time zone: the + * Date.getXxx() methods or the Date.getUTCXxx() methods. + * @param timeZone The time zone that the given date is assumed to be in (may be null for unaware dates) + */ + constructor(date: Date, getFuncs: javascript.DateFunctions, timeZone?: timezone.TimeZone); + /** + * Constructor. Note that unlike JavaScript dates we require fields to be in normal ranges. + * Use the add(duration) or sub(duration) for arithmetic. + * @param year The full year (e.g. 2014) + * @param month The month [1-12] (note this deviates from JavaScript Date) + * @param day The day of the month [1-31] + * @param hour The hour of the day [0-24) + * @param minute The minute of the hour [0-59] + * @param second The second of the minute [0-59] + * @param millisecond The millisecond of the second [0-999] + * @param timeZone The time zone, or null (for unaware dates) + */ + constructor(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, timeZone?: timezone.TimeZone); + /** + * Constructor + * @param unixTimestamp milliseconds since 1970-01-01T00:00:00.000 + * @param timeZone the time zone that the timestamp is assumed to be in (usually UTC). + */ + constructor(unixTimestamp: number, timeZone?: timezone.TimeZone); + /** + * @return a copy of this object + */ + clone(): DateTime; + /** + * @return The time zone that the date is in. May be null for unaware dates. + */ + zone(): timezone.TimeZone; + /** + * Zone name abbreviation at this time + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * @return The abbreviation + */ + zoneAbbreviation(dstDependent?: boolean): string; + /** + * @return the offset w.r.t. UTC in minutes. Returns 0 for unaware dates and for UTC dates. + */ + offset(): number; + /** + * @return The full year e.g. 2014 + */ + year(): number; + /** + * @return The month 1-12 (note this deviates from JavaScript Date) + */ + month(): number; + /** + * @return The day of the month 1-31 + */ + day(): number; + /** + * @return The hour 0-23 + */ + hour(): number; + /** + * @return the minutes 0-59 + */ + minute(): number; + /** + * @return the seconds 0-59 + */ + second(): number; + /** + * @return the milliseconds 0-999 + */ + millisecond(): number; + /** + * @return the day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + weekDay(): basics.WeekDay; + /** + * Returns the day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + dayOfYear(): number; + /** + * The ISO 8601 week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + weekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + weekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + secondOfDay(): number; + /** + * @return Milliseconds since 1970-01-01T00:00:00.000Z + */ + unixUtcMillis(): number; + /** + * @return The full year e.g. 2014 + */ + utcYear(): number; + /** + * @return The UTC month 1-12 (note this deviates from JavaScript Date) + */ + utcMonth(): number; + /** + * @return The UTC day of the month 1-31 + */ + utcDay(): number; + /** + * @return The UTC hour 0-23 + */ + utcHour(): number; + /** + * @return The UTC minutes 0-59 + */ + utcMinute(): number; + /** + * @return The UTC seconds 0-59 + */ + utcSecond(): number; + /** + * Returns the UTC day number within the year: Jan 1st has number 0, + * Jan 2nd has number 1 etc. + * + * @return the day-of-year [0-366] + */ + utcDayOfYear(): number; + /** + * @return The UTC milliseconds 0-999 + */ + utcMillisecond(): number; + /** + * @return the UTC day-of-week (the enum values correspond to JavaScript + * week day numbers) + */ + utcWeekDay(): basics.WeekDay; + /** + * The ISO 8601 UTC week number. Week 1 is the week + * that has January 4th in it, and it starts on Monday. + * See https://en.wikipedia.org/wiki/ISO_week_date + * + * @return Week number [1-53] + */ + utcWeekNumber(): number; + /** + * The week of this month. There is no official standard for this, + * but we assume the same rules for the weekNumber (i.e. + * week 1 is the week that has the 4th day of the month in it) + * + * @return Week number [1-5] + */ + utcWeekOfMonth(): number; + /** + * Returns the number of seconds that have passed on the current day + * Does not consider leap seconds + * + * @return seconds [0-86399] + */ + utcSecondOfDay(): number; + /** + * Convert this date to the given time zone (in-place). + * Throws if this date does not have a time zone. + * @return this (for chaining) + */ + convert(zone?: timezone.TimeZone): DateTime; + /** + * Returns this date converted to the given time zone. + * Unaware dates can only be converted to unaware dates (clone) + * Converting an unaware date to an aware date throws an exception. Use the constructor + * if you really need to do that. + * + * @param zone The new time zone. This may be null to create unaware date. + * @return The converted date + */ + toZone(zone?: timezone.TimeZone): DateTime; + /** + * Convert to JavaScript date with the zone time in the getX() methods. + * Unless the timezone is local, the Date.getUTCX() methods will NOT be correct. + * This is because Date calculates getUTCX() from getX() applying local time zone. + */ + toDate(): Date; + /** + * Add a time duration relative to UTC. Note that this simply adds a number + * of milliseconds to UTC and converts back to zone(), + * There is not DST handling. + * @return this + duration + */ + add(duration: duration.Duration): DateTime; + /** + * Add an amount of time relative to UTC, as regularly as possible. + * + * Adding e.g. 1 hour will increment the utcHour() field, adding 1 month + * increments the utcMonth() field. + * Adding an amount of units leaves lower units intact. E.g. + * adding a month will leave the day() field untouched if possible. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + * + * In case of DST changes, the utc time fields are still untouched but local + * time fields may shift. + */ + add(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Add an amount of time to the zone time, as regularly as possible. + * + * Adding e.g. 1 hour will increment the hour() field of the zone + * date by one. In case of DST changes, the time fields may additionally + * increase by the DST offset, if a non-existing local time would + * be reached otherwise. + * + * Adding a unit of time will leave lower-unit fields intact, unless the result + * would be a non-existing time. Then an extra DST offset is added. + * + * Note adding Months or Years will clamp the date to the end-of-month if + * the start date was at the end of a month, i.e. contrary to JavaScript + * Date#setUTCMonth() it will not overflow into the next month + */ + addLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as add(-1*duration); + */ + sub(duration: duration.Duration): DateTime; + /** + * Same as add(-1*amount, unit); + */ + sub(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Same as addLocal(-1*amount, unit); + */ + subLocal(amount: number, unit: basics.TimeUnit): DateTime; + /** + * Time difference between two DateTimes + * @return this - other + */ + diff(other: DateTime): duration.Duration; + /** + * @return True iff (this < other) + */ + lessThan(other: DateTime): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time in UTC + */ + equals(other: DateTime): boolean; + /** + * @return True iff this and other represent the same time and + * have the same zone + */ + identical(other: DateTime): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: DateTime): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: DateTime): boolean; + /** + * @return The minimum of this and other + */ + min(other: DateTime): DateTime; + /** + * @return The maximum of this and other + */ + max(other: DateTime): DateTime; + /** + * Proper ISO 8601 format string with any IANA zone converted to ISO offset + * E.g. "2014-01-01T23:15:33+01:00" for Europe/Amsterdam + */ + toIsoString(): string; + /** + * Return a string representation of the DateTime according to the + * specified format. The format is implemented as the LDML standard + * (http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns) + * + * @param formatString The format specification (e.g. "dd/MM/yyyy HH:mm:ss") + * @return The string representation of this DateTime + */ + format(formatString: string): string; + /** + * Modified ISO 8601 format string with IANA name if applicable. + * E.g. "2014-01-01T23:15:33.000 Europe/Amsterdam" + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; + /** + * Modified ISO 8601 format string in UTC without time zone info + */ + toUtcString(): string; + } +} + +declare module '__timezonecomplete/duration' { + import basics = require("__timezonecomplete/basics"); + /** + * Time duration. Create one e.g. like this: var d = Duration.hours(1). + * Note that time durations do not take leap seconds etc. into account: + * one hour is simply represented as 3600000 milliseconds. + */ + export class Duration { + /** + * Construct a time duration + * @param n Number of hours + * @return A duration of n hours + */ + static hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes + * @return A duration of n minutes + */ + static minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds + * @return A duration of n seconds + */ + static seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds + * @return A duration of n milliseconds + */ + static milliseconds(n: number): Duration; + /** + * Construct a time duration of 0 + */ + constructor(); + /** + * Construct a time duration from a number of milliseconds + */ + constructor(milliseconds: number); + /** + * Construct a time duration from a string in format + * [-]h[:m[:s[.n]]] e.g. -01:00:30.501 + */ + constructor(input: string); + /** + * Construct a duration from an amount and a time unit. + * @param amount Number of units + * @param unit A time unit i.e. TimeUnit.Second, TimeUnit.Hour etc. + */ + constructor(amount: number, unit: basics.TimeUnit); + /** + * @return another instance of Duration with the same value. + */ + clone(): Duration; + /** + * The entire duration in milliseconds (negative or positive) + */ + milliseconds(): number; + /** + * The millisecond part of the duration (always positive) + * @return e.g. 400 for a -01:02:03.400 duration + */ + millisecond(): number; + /** + * The entire duration in seconds (negative or positive, fractional) + * @return e.g. 1.5 for a 1500 milliseconds duration + */ + seconds(): number; + /** + * The second part of the duration (always positive) + * @return e.g. 3 for a -01:02:03.400 duration + */ + second(): number; + /** + * The entire duration in minutes (negative or positive, fractional) + * @return e.g. 1.5 for a 90000 milliseconds duration + */ + minutes(): number; + /** + * The minute part of the duration (always positive) + * @return e.g. 2 for a -01:02:03.400 duration + */ + minute(): number; + /** + * The entire duration in hours (negative or positive, fractional) + * @return e.g. 1.5 for a 5400000 milliseconds duration + */ + hours(): number; + /** + * The hour part of the duration (always positive). + * Note that this part can exceed 23 hours, because for + * now, we do not have a days() function + * @return e.g. 25 for a -25:02:03.400 duration + */ + wholeHours(): number; + /** + * Sign + * @return "-" if the duration is negative + */ + sign(): string; + /** + * @return True iff (this < other) + */ + lessThan(other: Duration): boolean; + /** + * @return True iff (this <= other) + */ + lessEqual(other: Duration): boolean; + /** + * @return True iff this and other represent the same time duration + */ + equals(other: Duration): boolean; + /** + * @return True iff this > other + */ + greaterThan(other: Duration): boolean; + /** + * @return True iff this >= other + */ + greaterEqual(other: Duration): boolean; + /** + * @return The minimum (most negative) of this and other + */ + min(other: Duration): Duration; + /** + * @return The maximum (most positive) of this and other + */ + max(other: Duration): Duration; + /** + * Multiply with a fixed number. + * @return a new Duration of (this * value) + */ + multiply(value: number): Duration; + /** + * Divide by a fixed number. + * @return a new Duration of (this / value) + */ + divide(value: number): Duration; + /** + * Add a duration. + * @return a new Duration of (this + value) + */ + add(value: Duration): Duration; + /** + * Subtract a duration. + * @return a new Duration of (this - value) + */ + sub(value: Duration): Duration; + /** + * String in [-]hh:mm:ss.nnn notation. All fields are + * always present except the sign. + */ + toFullString(): string; + /** + * String in [-]hh[:mm[:ss[.nnn]]] notation. Fields are + * added as necessary + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * The valueOf() method returns the primitive value of the specified object. + */ + valueOf(): any; + } +} + +declare module '__timezonecomplete/javascript' { + /** + * Indicates how a Date object should be interpreted. + * Either we can take getYear(), getMonth() etc for our field + * values, or we can take getUTCYear(), getUtcMonth() etc to do that. + */ + export enum DateFunctions { + /** + * Use the Date.getFullYear(), Date.getMonth(), ... functions. + */ + Get = 0, + /** + * Use the Date.getUTCFullYear(), Date.getUTCMonth(), ... functions. + */ + GetUTC = 1, + } +} + +declare module '__timezonecomplete/period' { + import basics = require("__timezonecomplete/basics"); + import datetime = require("__timezonecomplete/datetime"); + /** + * Specifies how the period should repeat across the day + * during DST changes. + */ + export enum PeriodDst { + /** + * Keep repeating in similar intervals measured in UTC, + * unaffected by Daylight Saving Time. + * E.g. a repetition of one hour will take one real hour + * every time, even in a time zone with DST. + * Leap seconds, leap days and month length + * differences will still make the intervals different. + */ + RegularIntervals = 0, + /** + * Ensure that the time at which the intervals occur stay + * at the same place in the day, local time. So e.g. + * a period of one day, starting at 8:05AM Europe/Amsterdam time + * will always start at 8:05 Europe/Amsterdam. This means that + * in UTC time, some intervals will be 25 hours and some + * 23 hours during DST changes. + * Another example: an hourly interval will be hourly in local time, + * skipping an hour in UTC for a DST backward change. + */ + RegularLocalTime = 1, + } + /** + * Convert a PeriodDst to a string: "regular intervals" or "regular local time" + */ + export function periodDstToString(p: PeriodDst): string; + /** + * Repeating time period: consists of a starting point and + * a time length. This class accounts for leap seconds and leap days. + */ + export class Period { + /** + * Constructor + * LIMITATION: if dst equals RegularLocalTime, and unit is Second, Minute or Hour, + * then the amount must be a factor of 24. So 120 seconds is allowed while 121 seconds is not. + * This is due to the enormous processing power required by these cases. They are not + * implemented and you will get an assert. + * + * @param start The start of the period. If the period is in Months or Years, and + * the day is 29 or 30 or 31, the results are maximised to end-of-month. + * @param amount The amount of units. + * @param unit The unit. + * @param dst Specifies how to handle Daylight Saving Time. Not relevant + * if the time zone of the start datetime does not have DST. + */ + constructor(start: datetime.DateTime, amount: number, unit: basics.TimeUnit, dst: PeriodDst); + /** + * The start date + */ + start(): datetime.DateTime; + /** + * The amount of units + */ + amount(): number; + /** + * The unit + */ + unit(): basics.TimeUnit; + /** + * The dst handling mode + */ + dst(): PeriodDst; + /** + * The first occurrence of the period greater than + * the given date. The given date need not be at a period boundary. + * Pre: the fromdate and startdate must either both have timezones or not + * @param fromDate: the date after which to return the next date + * @return the first date matching the period after fromDate, given + * in the same zone as the fromDate. + */ + findFirst(fromDate: datetime.DateTime): datetime.DateTime; + /** + * Returns the next timestamp in the period. The given timestamp must + * be at a period boundary, otherwise the answer is incorrect. + * This function has MUCH better performance than findFirst. + * Returns the datetime "count" times away from the given datetime. + * @param prev Boundary date. Must have a time zone (any time zone) iff the period start date has one. + * @param count Optional, must be >= 1 and whole. + * @return (prev + count * period), in the same timezone as prev. + */ + findNext(prev: datetime.DateTime, count?: number): datetime.DateTime; + /** + * Checks whether the given date is on a period boundary + * (expensive!) + */ + isBoundary(occurrence: datetime.DateTime): boolean; + /** + * Returns an ISO duration string e.g. + * 2014-01-01T12:00:00.000+01:00/P1H + * 2014-01-01T12:00:00.000+01:00/PT1M (one minute) + * 2014-01-01T12:00:00.000+01:00/P1M (one month) + */ + toIsoString(): string; + /** + * A string representation e.g. + * "10 years, starting at 2014-03-01T12:00:00 Europe/Amsterdam, keeping regular intervals". + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + } +} + +declare module '__timezonecomplete/timesource' { + /** + * For testing purposes, we often need to manipulate what the current + * time is. This is an interface for a custom time source object + * so in tests you can use a custom time source. + */ + export interface TimeSource { + /** + * Return the current date+time as a javascript Date object + */ + now(): Date; + } + /** + * Default time source, returns actual time + */ + export class RealTimeSource implements TimeSource { + now(): Date; + } +} + +declare module '__timezonecomplete/timezone' { + import javascript = require("__timezonecomplete/javascript"); + /** + * The type of time zone + */ + export enum TimeZoneKind { + /** + * Local time offset as determined by JavaScript Date class. + */ + Local = 0, + /** + * Fixed offset from UTC, without DST. + */ + Offset = 1, + /** + * IANA timezone managed through Olsen TZ database. Includes + * DST if applicable. + */ + Proper = 2, + } + /** + * Option for TimeZone#normalizeLocal() + */ + export enum NormalizeOption { + /** + * Normalize non-existing times by ADDING the DST offset + */ + Up = 0, + /** + * Normalize non-existing times by SUBTRACTING the DST offset + */ + Down = 1, + } + /** + * Time zone. The object is immutable because it is cached: + * requesting a time zone twice yields the very same object. + * Note that we use time zone offsets inverted w.r.t. JavaScript Date.getTimezoneOffset(), + * i.e. offset 90 means +01:30. + * + * Time zones come in three flavors: the local time zone, as calculated by JavaScript Date, + * a fixed offset ("+01:30") without DST, or a IANA timezone ("Europe/Amsterdam") with DST + * applied depending on the time zone rules. + */ + export class TimeZone { + /** + * The local time zone for a given date. Note that + * the time zone varies with the date: amsterdam time for + * 2014-01-01 is +01:00 and amsterdam time for 2014-07-01 is +02:00 + */ + static local(): TimeZone; + /** + * The UTC time zone. + */ + static utc(): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + */ + static zone(offset: number): TimeZone; + /** + * Returns a time zone object from the cache. If it does not exist, it is created. + * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + */ + static zone(s: string): TimeZone; + /** + * Do not use this constructor, use the static + * TimeZone.zone() method instead. + * @param name NORMALIZED name, assumed to be correct + */ + constructor(name: string); + /** + * The time zone identifier. Can be an offset "-01:30" or an + * IANA time zone name "Europe/Amsterdam", or "localtime" for + * the local time zone. + */ + name(): string; + /** + * The kind of time zone (Local/Offset/Proper) + */ + kind(): TimeZoneKind; + /** + * Equality operator. Maps zero offsets and different names for UTC onto + * each other. Other time zones are not mapped onto each other. + */ + equals(other: TimeZone): boolean; + /** + * Is this zone equivalent to UTC? + */ + isUtc(): boolean; + /** + * Does this zone have Daylight Saving Time at all? + */ + hasDst(): boolean; + /** + * Calculate timezone offset from a UTC time. + * + * @param year Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond Millisecond 0-999 + * + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Calculate timezone offset from a zone-local time (NOT a UTC time). + * @param year local full year + * @param month local month 1-12 (note this deviates from JavaScript date) + * @param day local day of month 1-31 + * @param hour local hour 0-23 + * @param minute local minute 0-59 + * @param second local second 0-59 + * @param millisecond local millisecond 0-999 + * @return the offset of this time zone with respect to UTC at the given time, in minutes. + */ + offsetForZone(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForUtcDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Note: will be removed in version 2.0.0 + * + * Convenience function, takes values from a Javascript Date + * Calls offsetForUtc() with the contents of the date + * + * @param date: the date + * @param funcs: the set of functions to use: get() or getUTC() + */ + offsetForZoneDate(date: Date, funcs: javascript.DateFunctions): number; + /** + * Zone abbreviation at given UTC timestamp e.g. CEST for Central European Summer Time. + * + * @param year Full year + * @param month Month 1-12 (note this deviates from JavaScript date) + * @param day Day of month 1-31 + * @param hour Hour 0-23 + * @param minute Minute 0-59 + * @param second Second 0-59 + * @param millisecond Millisecond 0-999 + * @param dstDependent (default true) set to false for a DST-agnostic abbreviation + * + * @return "local" for local timezone, the offset for an offset zone, or the abbreviation for a proper zone. + */ + abbreviationForUtc(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, dstDependent?: boolean): string; + /** + * Normalizes non-existing local times by adding a forward offset change. + * During a forward standard offset change or DST offset change, some amount of + * local time is skipped. Therefore, this amount of local time does not exist. + * This function adds the amount of forward change to any non-existing time. After all, + * this is probably what the user meant. + * + * @param localUnixMillis Unix timestamp in zone time + * @param opt (optional) Round up or down? Default: up + * + * @returns Unix timestamp in zone time, normalized. + */ + normalizeZoneTime(localUnixMillis: number, opt?: NormalizeOption): number; + /** + * The time zone identifier (normalized). + * Either "localtime", IANA name, or "+hh:mm" offset. + */ + toString(): string; + /** + * Used by util.inspect() + */ + inspect(): string; + /** + * Convert an offset number into an offset string + * @param offset The offset in minutes from UTC e.g. 90 minutes + * @return the offset in ISO notation "+01:30" for +90 minutes + */ + static offsetToString(offset: number): string; + /** + * String to offset conversion. + * @param s Formats: "-01:00", "-0100", "-01", "Z" + * @return offset w.r.t. UTC in minutes + */ + static stringToOffset(s: string): number; + } +} + +declare module '__timezonecomplete/globals' { + import datetime = require("__timezonecomplete/datetime"); + import duration = require("__timezonecomplete/duration"); + /** + * Returns the minimum of two DateTimes + */ + export function min(d1: datetime.DateTime, d2: datetime.DateTime): datetime.DateTime; + /** + * Returns the minimum of two Durations + */ + export function min(d1: duration.Duration, d2: duration.Duration): duration.Duration; + /** + * Returns the maximum of two DateTimes + */ + export function max(d1: datetime.DateTime, d2: datetime.DateTime): datetime.DateTime; + /** + * Returns the maximum of two Durations + */ + export function max(d1: duration.Duration, d2: duration.Duration): duration.Duration; +} + diff --git a/timezonecomplete/timezonecomplete-tests-1.9.0.ts b/timezonecomplete/timezonecomplete-tests-1.9.0.ts new file mode 100644 index 000000000..1e05cf7dc --- /dev/null +++ b/timezonecomplete/timezonecomplete-tests-1.9.0.ts @@ -0,0 +1,205 @@ +/// + +import tc = require("timezonecomplete-1.9.0"); + +var b: boolean; +var n: number; +var s: string; +var w: tc.WeekDay; + +n = tc.timeUnitToMilliseconds(tc.TimeUnit.Month); +b = tc.isLeapYear(2014); +n = tc.daysInMonth(2014, 10); +n = tc.daysInYear(2014); +n = tc.dayOfYear(2014, 1, 2); +w = tc.firstWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +w = tc.lastWeekDayOfMonth(2014, 1, tc.WeekDay.Sunday); +n = tc.weekDayOnOrAfter(2014, 1, 14, tc.WeekDay.Monday); +n = tc.weekDayOnOrBefore(2014, 1, 14, tc.WeekDay.Monday); +n = tc.secondOfDay(13, 59, 59); +n = tc.weekOfMonth(2014, 1, 1); + +// DURATION + +var d: tc.Duration; +var d1: tc.Duration = tc.Duration.hours(24); +var d2: tc.Duration = tc.Duration.minutes(24); +var d3: tc.Duration = tc.Duration.seconds(24); +var d4: tc.Duration = tc.Duration.milliseconds(24); +var d5: tc.Duration = new tc.Duration(24); +var d6: tc.Duration = new tc.Duration("00:01"); +var d7: tc.Duration = d6.clone(); +var d8: tc.Duration = new tc.Duration(4, tc.TimeUnit.Second); + +n = d7.wholeHours(); +n = d7.hours(); +n = d7.minutes(); +n = d7.minute(); +n = d7.seconds(); +n = d7.second(); +n = d7.milliseconds(); +n = d7.millisecond(); +s = d7.sign(); +b = d7.lessThan(d6); +b = d7.greaterThan(d6); +d = d7.min(d6); +d = d7.max(d6); +d = d7.multiply(3); +d = d7.divide(0.3); +d = d7.add(d6); +d = d7.sub(d6); +s = d7.toString(); + +// TIMEZONE + +var t: tc.TimeZone; +var k: tc.TimeZoneKind; + +t = tc.TimeZone.local(); +t = tc.TimeZone.utc(); +t = tc.TimeZone.zone(2); +t = tc.TimeZone.zone("+01:00"); +s = t.name(); +k = t.kind(); +b = t.equals(t); +b = t.isUtc(); +n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); +n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); +n = t.offsetForZoneDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.GetUTC); +s = t.toString(); +s = tc.TimeZone.offsetToString(2); +n = tc.TimeZone.stringToOffset("+00:01"); + +// REALTIMESOURCE + +var date: Date = (new tc.RealTimeSource()).now(); + +// DATETIME + +var dt: tc.DateTime; + +var ts: tc.TimeSource = tc.DateTime.timeSource; + +dt = tc.DateTime.nowLocal(); +dt = tc.DateTime.nowUtc(); +dt = tc.DateTime.now(tc.TimeZone.local()); +dt = new tc.DateTime(); +dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); +dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); +dt = new tc.DateTime(date, tc.DateFunctions.Get); +dt = new tc.DateTime(date, tc.DateFunctions.Get, tc.TimeZone.utc()); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123); +dt = new tc.DateTime(2014, 1, 1, 13, 5, 1, 123, tc.TimeZone.utc()); +dt = new tc.DateTime(89949284); +dt = new tc.DateTime(89949284, tc.TimeZone.utc()); +dt = dt.clone(); +t = dt.zone(); +n = dt.offset(); +n = dt.year(); +n = dt.month(); +n = dt.day(); +n = dt.hour(); +n = dt.minute(); +n = dt.second(); +n = dt.weekNumber(); +n = dt.weekOfMonth(); +n = dt.secondOfDay(); +n = dt.dayOfYear(); +n = dt.millisecond(); +n = dt.unixUtcMillis(); +n = dt.utcYear(); +n = dt.utcMonth(); +n = dt.utcDay(); +n = dt.utcHour(); +n = dt.utcMinute(); +n = dt.utcSecond(); +n = dt.utcMillisecond(); +n = dt.utcWeekNumber(); +n = dt.utcWeekOfMonth(); +n = dt.utcSecondOfDay(); +n = dt.utcDayOfYear(); +s = dt.format("%Y-%m-%d"); +dt.convert(tc.TimeZone.local()); +dt = dt.toZone(tc.TimeZone.utc()); +date = dt.toDate(); +dt = dt.add(tc.Duration.seconds(2)); +dt = dt.add(2, tc.TimeUnit.Year); +dt = dt.add(2, tc.TimeUnit.Month); +dt = dt.add(2, tc.TimeUnit.Week); +dt = dt.add(2, tc.TimeUnit.Day); +dt = dt.add(2, tc.TimeUnit.Hour); +dt = dt.add(2, tc.TimeUnit.Minute); +dt = dt.add(2, tc.TimeUnit.Second); +dt = dt.addLocal(2, tc.TimeUnit.Second); +dt = dt.sub(tc.Duration.seconds(2)); +dt = dt.sub(2, tc.TimeUnit.Year); +dt = dt.sub(2, tc.TimeUnit.Month); +dt = dt.sub(2, tc.TimeUnit.Week); +dt = dt.sub(2, tc.TimeUnit.Day); +dt = dt.sub(2, tc.TimeUnit.Hour); +dt = dt.sub(2, tc.TimeUnit.Minute); +dt = dt.sub(2, tc.TimeUnit.Second); +dt = dt.subLocal(2, tc.TimeUnit.Second); +d = dt.diff(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.lessEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterThan(new tc.DateTime(9289234, tc.TimeZone.local())); +b = dt.greaterEqual(new tc.DateTime(9289234, tc.TimeZone.local())); +dt = dt.min(new tc.DateTime(9289234, tc.TimeZone.local())); +dt = dt.max(new tc.DateTime(9289234, tc.TimeZone.local())); +s = dt.toIsoString(); +s = dt.toString(); +s = dt.toUtcString(); + +var wd: tc.WeekDay; +wd = dt.weekDay(); +wd = dt.utcWeekDay(); + +// PERIOD + +s = tc.periodDstToString(tc.PeriodDst.RegularIntervals); +s = tc.periodDstToString(tc.PeriodDst.RegularLocalTime); + +var p: tc.Period; + +p = new tc.Period(tc.DateTime.nowLocal(), 1, tc.TimeUnit.Hour, tc.PeriodDst.RegularLocalTime); +dt = p.start(); +n = p.amount(); +var tu: tc.TimeUnit = p.unit(); +var pd: tc.PeriodDst = p.dst(); +dt = p.findFirst(tc.DateTime.nowLocal()); +dt = p.findNext(dt); +s = p.toIsoString(); +s = p.toString(); +b = p.isBoundary(dt); + + +// GLOBALS +d = tc.min(tc.Duration.seconds(2), tc.Duration.seconds(3)); +d = tc.max(tc.Duration.seconds(2), tc.Duration.seconds(3)); + +dt = tc.min(new tc.DateTime(2), new tc.DateTime(3)); +dt = tc.max(new tc.DateTime(2), new tc.DateTime(3)); + + + + + + + + + + + + + + + + + + + + + + diff --git a/timezonecomplete/timezonecomplete-tests.ts b/timezonecomplete/timezonecomplete-tests.ts index 19dcd84c7..cb07832a6 100644 --- a/timezonecomplete/timezonecomplete-tests.ts +++ b/timezonecomplete/timezonecomplete-tests.ts @@ -26,10 +26,14 @@ var d1: tc.Duration = tc.Duration.hours(24); var d2: tc.Duration = tc.Duration.minutes(24); var d3: tc.Duration = tc.Duration.seconds(24); var d4: tc.Duration = tc.Duration.milliseconds(24); -var d5: tc.Duration = new tc.Duration(24); -var d6: tc.Duration = new tc.Duration("00:01"); -var d7: tc.Duration = d6.clone(); -var d8: tc.Duration = new tc.Duration(4, tc.TimeUnit.Second); +var d5: tc.Duration = tc.hours(24); +var d6: tc.Duration = tc.minutes(24); +var d7: tc.Duration = tc.seconds(24); +var d8: tc.Duration = tc.milliseconds(24); +var d9: tc.Duration = new tc.Duration(24); +var d10: tc.Duration = new tc.Duration("00:01"); +var d11: tc.Duration = d6.clone(); +var d12: tc.Duration = new tc.Duration(4, tc.TimeUnit.Second); n = d7.wholeHours(); n = d7.hours(); @@ -59,10 +63,16 @@ t = tc.TimeZone.local(); t = tc.TimeZone.utc(); t = tc.TimeZone.zone(2); t = tc.TimeZone.zone("+01:00"); +t = tc.local(); +t = tc.utc(); +t = tc.zone(2); +t = tc.zone("+01:00"); +t = tc.zone("Europe/Amsterdam", false); s = t.name(); k = t.kind(); b = t.equals(t); b = t.isUtc(); +b = t.dst(); n = t.offsetForUtc(2014, 1, 1, 13, 0, 5, 123); n = t.offsetForZone(2014, 1, 1, 13, 0, 5, 123); n = t.offsetForUtcDate(new Date(2014, 1, 1, 13, 0, 5, 123), tc.DateFunctions.Get); @@ -84,6 +94,9 @@ var ts: tc.TimeSource = tc.DateTime.timeSource; dt = tc.DateTime.nowLocal(); dt = tc.DateTime.nowUtc(); dt = tc.DateTime.now(tc.TimeZone.local()); +dt = tc.nowLocal(); +dt = tc.nowUtc(); +dt = tc.now(tc.TimeZone.local()); dt = new tc.DateTime(); dt = new tc.DateTime("2014-01-01T13:05:01.123 UTC"); dt = new tc.DateTime("2014-01-01T13:05:01.123", tc.TimeZone.utc()); diff --git a/timezonecomplete/timezonecomplete.d.ts b/timezonecomplete/timezonecomplete.d.ts index 4bf2a6a28..c91f138c6 100644 --- a/timezonecomplete/timezonecomplete.d.ts +++ b/timezonecomplete/timezonecomplete.d.ts @@ -1,4 +1,4 @@ -// Type definitions for timezonecomplete 1.9.0 +// Type definitions for timezonecomplete 1.10.0 // Project: https://github.com/SpiritIT/timezonecomplete // Definitions by: Rogier Schouten // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -22,8 +22,15 @@ declare module 'timezonecomplete' { export import secondOfDay = basics.secondOfDay; import datetime = require("__timezonecomplete/datetime"); export import DateTime = datetime.DateTime; + export import now = datetime.now; + export import nowLocal = datetime.nowLocal; + export import nowUtc = datetime.nowUtc; import duration = require("__timezonecomplete/duration"); export import Duration = duration.Duration; + export import hours = duration.hours; + export import minutes = duration.minutes; + export import seconds = duration.seconds; + export import milliseconds = duration.milliseconds; import javascript = require("__timezonecomplete/javascript"); export import DateFunctions = javascript.DateFunctions; import period = require("__timezonecomplete/period"); @@ -37,6 +44,9 @@ declare module 'timezonecomplete' { export import NormalizeOption = timezone.NormalizeOption; export import TimeZoneKind = timezone.TimeZoneKind; export import TimeZone = timezone.TimeZone; + export import local = timezone.local; + export import utc = timezone.utc; + export import zone = timezone.zone; import globals = require("__timezonecomplete/globals"); export import min = globals.min; export import max = globals.max; @@ -299,9 +309,22 @@ declare module '__timezonecomplete/basics' { declare module '__timezonecomplete/datetime' { import basics = require("__timezonecomplete/basics"); import duration = require("__timezonecomplete/duration"); - import javascript = require("__timezonecomplete/javascript"); import timesource = require("__timezonecomplete/timesource"); + import javascript = require("__timezonecomplete/javascript"); import timezone = require("__timezonecomplete/timezone"); + /** + * Current date+time in local time + */ + export function nowLocal(): DateTime; + /** + * Current date+time in UTC time + */ + export function nowUtc(): DateTime; + /** + * Current date+time in the given time zone + * @param timeZone The desired time zone (optional, defaults to UTC). + */ + export function now(timeZone?: timezone.TimeZone): DateTime; /** * DateTime class which is time zone-aware * and which can be mocked for testing purposes. @@ -314,18 +337,18 @@ declare module '__timezonecomplete/datetime' { */ static timeSource: timesource.TimeSource; /** - * Current date+time in local time (derived from DateTime.timeSource.now()). + * Current date+time in local time */ static nowLocal(): DateTime; /** - * Current date+time in UTC time (derived from DateTime.timeSource.now()). + * Current date+time in UTC time */ static nowUtc(): DateTime; /** - * Current date+time in the given time zone (derived from DateTime.timeSource.now()). - * @param timeZone The desired time zone. + * Current date+time in the given time zone + * @param timeZone The desired time zone (optional, defaults to UTC). */ - static now(timeZone: timezone.TimeZone): DateTime; + static now(timeZone?: timezone.TimeZone): DateTime; /** * Constructor. Creates current time in local timezone. */ @@ -673,6 +696,30 @@ declare module '__timezonecomplete/datetime' { declare module '__timezonecomplete/duration' { import basics = require("__timezonecomplete/basics"); + /** + * Construct a time duration + * @param n Number of hours (may be fractional or negative) + * @return A duration of n hours + */ + export function hours(n: number): Duration; + /** + * Construct a time duration + * @param n Number of minutes (may be fractional or negative) + * @return A duration of n minutes + */ + export function minutes(n: number): Duration; + /** + * Construct a time duration + * @param n Number of seconds (may be fractional or negative) + * @return A duration of n seconds + */ + export function seconds(n: number): Duration; + /** + * Construct a time duration + * @param n Number of milliseconds (may be fractional or negative) + * @return A duration of n milliseconds + */ + export function milliseconds(n: number): Duration; /** * Time duration. Create one e.g. like this: var d = Duration.hours(1). * Note that time durations do not take leap seconds etc. into account: @@ -681,25 +728,25 @@ declare module '__timezonecomplete/duration' { export class Duration { /** * Construct a time duration - * @param n Number of hours + * @param n Number of hours (may be fractional or negative) * @return A duration of n hours */ static hours(n: number): Duration; /** * Construct a time duration - * @param n Number of minutes + * @param n Number of minutes (may be fractional or negative) * @return A duration of n minutes */ static minutes(n: number): Duration; /** * Construct a time duration - * @param n Number of seconds + * @param n Number of seconds (may be fractional or negative) * @return A duration of n seconds */ static seconds(n: number): Duration; /** * Construct a time duration - * @param n Number of milliseconds + * @param n Number of milliseconds (may be fractional or negative) * @return A duration of n milliseconds */ static milliseconds(n: number): Duration; @@ -993,6 +1040,35 @@ declare module '__timezonecomplete/timesource' { declare module '__timezonecomplete/timezone' { import javascript = require("__timezonecomplete/javascript"); + /** + * The local time zone for a given date as per OS settings. Note that time zones are cached + * so you don't necessarily get a new object each time. + */ + export function local(): TimeZone; + /** + * Coordinated Universal Time zone. Note that time zones are cached + * so you don't necessarily get a new object each time. + */ + export function utc(): TimeZone; + /** + * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @returns a time zone with the given fixed offset + */ + export function zone(offset: number): TimeZone; + /** + * Time zone for an offset string or an IANA time zone string. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @param s Empty string for no time zone (null is returned), + * "localtime" for local time, + * a TZ database time zone name (e.g. Europe/Amsterdam), + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for + * "localtime", timezonecomplete will adhere to the computer settings, the DST flag + * does not have any effect. + */ + export function zone(name: string, dst?: boolean): TimeZone; /** * The type of time zone */ @@ -1046,29 +1122,37 @@ declare module '__timezonecomplete/timezone' { */ static utc(): TimeZone; /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @return The time zone with the given offset w.r.t. UTC in minutes, e.g. 90 for +01:30 + * Time zone with a fixed offset + * @param offset offset w.r.t. UTC in minutes, e.g. 90 for +01:30 */ static zone(offset: number): TimeZone; /** - * Returns a time zone object from the cache. If it does not exist, it is created. - * @param s: Empty string for local time, a TZ database time zone name (e.g. Europe/Amsterdam) - * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: - * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + * Time zone for an offset string or an IANA time zone string. Note that time zones are cached + * so you don't necessarily get a new object each time. + * @param s Empty string for no time zone (null is returned), + * "localtime" for local time, + * a TZ database time zone name (e.g. Europe/Amsterdam), + * or an offset string (either +01:30, +0130, +01, Z). For a full list of names, see: + * https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + * @param dst Optional, default true: adhere to Daylight Saving Time if applicable. Note for + * "localtime", timezonecomplete will adhere to the computer settings, the DST flag + * does not have any effect. */ - static zone(s: string): TimeZone; + static zone(s: string, dst?: boolean): TimeZone; /** * Do not use this constructor, use the static * TimeZone.zone() method instead. * @param name NORMALIZED name, assumed to be correct + * @param dst Adhere to Daylight Saving Time if applicable, ignored for local time and fixed offsets */ - constructor(name: string); + constructor(name: string, dst?: boolean); /** * The time zone identifier. Can be an offset "-01:30" or an * IANA time zone name "Europe/Amsterdam", or "localtime" for * the local time zone. */ name(): string; + dst(): boolean; /** * The kind of time zone (Local/Offset/Proper) */ diff --git a/touch-events/touch-event-tests.ts b/touch-events/touch-event-tests.ts new file mode 100644 index 000000000..a1255813c --- /dev/null +++ b/touch-events/touch-event-tests.ts @@ -0,0 +1,33 @@ +/// + +var touchEvent:TouchEvent; +var list:TouchList; +var touch:Touch; + +list = touchEvent.touches; +list = touchEvent.targetTouches; +list = touchEvent.changedTouches; + +var flag:boolean; +flag = touchEvent.altKey; +flag = touchEvent.metaKey; +flag = touchEvent.ctrlKey; +flag = touchEvent.shiftKey; + +var len:number = list.length; +touch = list.item(0); + +var x: number; +var y: number; +var id: number; + +id = touch.identifier; +x = touch.screenX; +y = touch.screenY; +x = touch.clientX; +y = touch.clientY; +x = touch.pageX; +y = touch.pageY; + +var target:EventTarget; +target = touch.target; diff --git a/touch-events/touch-events.d.ts b/touch-events/touch-events.d.ts new file mode 100644 index 000000000..d299b45c4 --- /dev/null +++ b/touch-events/touch-events.d.ts @@ -0,0 +1,30 @@ +// Type definitions for HTML Touch Events +// Project: http://www.w3.org/TR/touch-events/ +// Definitions by: Kevin Barabash +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface TouchEvent extends UIEvent { + touches: TouchList; + targetTouches: TouchList; + changedTouches: TouchList; + altKey: boolean; + metaKey: boolean; + ctrlKey: boolean; + shiftKey: boolean; +} + +interface TouchList { + length: number; + item: (index: number) => Touch; +} + +interface Touch { + identifier: number; + target: EventTarget; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + pageX: number; + pageY: number; +} diff --git a/watch/watch-tests.ts b/watch/watch-tests.ts index 4888d41e2..d6be4092d 100644 --- a/watch/watch-tests.ts +++ b/watch/watch-tests.ts @@ -24,6 +24,7 @@ watch.watchTree(str, (f: any, curr: fs.Stats, prev: fs.Stats) => { watch.watchTree(str, opts, (f: any, curr: fs.Stats, prev: fs.Stats) => { }); +watch.unwatchTree(str); watch.createMonitor(str, (monitor: watch.Monitor) => { }); diff --git a/watch/watch.d.ts b/watch/watch.d.ts index d011b11f7..d80ec2e51 100644 --- a/watch/watch.d.ts +++ b/watch/watch.d.ts @@ -30,6 +30,7 @@ declare module "watch" { export function watchTree(root: string, callback: (f: any, curr: fs.Stats, prev: fs.Stats) => void): void; export function watchTree(root: string, options: Options, callback: (f: any, curr: fs.Stats, prev: fs.Stats) => void): void; + export function unwatchTree(root: string): void; export function createMonitor(root: string, callback: (monitor: Monitor) => void): void; export function createMonitor(root: string, options: Options, callback: (monitor: Monitor) => void): void; } diff --git a/webmidi/webmidi-tests.ts b/webmidi/webmidi-tests.ts index 42708f1c1..a2878afd9 100644 --- a/webmidi/webmidi-tests.ts +++ b/webmidi/webmidi-tests.ts @@ -5,15 +5,15 @@ if (navigator.requestMIDIAccess !== undefined) { navigator.requestMIDIAccess().then(onSuccessCallback, onErrorCallback); } -var onSuccessCallback = (item: Midi.MIDIAccess)=>{ +var onSuccessCallback = (item: WebMidi.MIDIAccess)=>{ this._midiPort = item; - item.onconnect = (event: Midi.MIDIConnectionEvent)=>{ + item.onconnect = (event: WebMidi.MIDIConnectionEvent)=>{ console.log("onconnect"); console.log(event); }; - item.ondisconnect = (event: Midi.MIDIConnectionEvent)=>{ + item.ondisconnect = (event: WebMidi.MIDIConnectionEvent)=>{ console.log("ondisconnect"); console.log(event); }; @@ -56,7 +56,7 @@ var onSuccessCallback = (item: Midi.MIDIAccess)=>{ } for(var cnt = 0; cnt < this._inputs.length; cnt++){ - this._inputs[cnt].onmidimessage = (event: Midi.MIDIMessageEvent)=>{ + this._inputs[cnt].onmidimessage = (event: WebMidi.MIDIMessageEvent)=>{ this.onMidiMessage(event.data); }; } diff --git a/webmidi/webmidi.d.ts b/webmidi/webmidi.d.ts index 59250c3e4..e5a614695 100644 --- a/webmidi/webmidi.d.ts +++ b/webmidi/webmidi.d.ts @@ -10,10 +10,10 @@ interface Navigator { * When invoked, returns a Promise object representing a request for access to MIDI devices on the user's system. * @param options settings that may be provided to the requestMIDIAccess request. */ - requestMIDIAccess (options?: Midi.MidiOptions): Promise; + requestMIDIAccess (options?: WebMidi.MidiOptions): Promise; } -declare module Midi{ +declare module WebMidi{ /** * optional settings that may be provided to the requestMIDIAccess request. */ diff --git a/when/when.d.ts b/when/when.d.ts index 2af3fba9d..bb227cf08 100644 --- a/when/when.d.ts +++ b/when/when.d.ts @@ -79,4 +79,6 @@ declare module When { } } -export = When; +declare module "when" { + export = When; +}